aws / aws-sam-cli

CLI tool to build, test, debug, and deploy Serverless applications using AWS SAM
https://aws.amazon.com/serverless/sam/
Apache License 2.0
6.47k stars 1.16k forks source link

Lambda response must be valid json #7224

Open nikhilrizal opened 1 week ago

nikhilrizal commented 1 week ago

hey new to sam i just used sam init to get strated with the default python template

SYSTEM AND SAM INFO sam --info /usr/lib/python3/dist-packages/paramiko/transport.py:237: CryptographyDeprecationWarning: Blowfish has been deprecated and will be removed in a future release "class": algorithms.Blowfish, { "version": "1.119.0", "system": { "python": "3.10.12", "os": "Linux-6.5.0-41-generic-x86_64-with-glibc2.35" }, "additional_dependencies": { "docker_engine": "24.0.7", "aws_cdk": "Not available", "terraform": "1.8.2" }, "available_beta_feature_env_vars": [ "SAM_CLI_BETA_FEATURES", "SAM_CLI_BETA_BUILD_PERFORMANCE", "SAM_CLI_BETA_TERRAFORM_SUPPORT", "SAM_CLI_BETA_RUST_CARGO_LAMBDA" ] }

DOCKER INFO docker --version Docker version 24.0.7, build 24.0.7-0ubuntu2~22.04.1

HERE ARE THE CODE (I have not changed anything default template)

import json

import requests

import json

import requests

def lambda_handler(event, context): """Sample pure Lambda function

Parameters
----------
event: dict, required
    API Gateway Lambda Proxy Input Format

    Event doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-format

context: object, required
    Lambda Context runtime methods and attributes

    Context doc: https://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html

Returns
------
API Gateway Lambda Proxy Output Format: dict

    Return doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html
"""

# try:
#     ip = requests.get("http://checkip.amazonaws.com/")
# except requests.RequestException as e:
#     # Send some context about this error to Lambda Logs
#     print(e)

#     raise e

return {
    "statusCode": 200,
    "body": json.dumps({
        "message": "hello world",
        # "location": ip.text.replace("\n", "")
    }),
}

CONSOLE ERROR


COMMAND I RAN
SAM_CLI_CONTAINER_CONNECTION_TIMEOUT=30 sam local start-api --debug --profile xxx

/usr/lib/python3/dist-packages/paramiko/transport.py:237: CryptographyDeprecationWarning: Blowfish has been deprecated and will be removed in a future release "class": algorithms.Blowfish, 2024-07-05 21:32:26,064 | Config file location: /home/nik/codes/BitSweepProject/paymentMockServer/sam_py/samconfig.toml
2024-07-05 21:32:26,068 | Loading configuration values from [default.['local', 'start-api'].parameters]
(env.command_name.section) in config file at '/home/nik/codes/BitSweepProject/paymentMockServer/sam_py/samconfig.toml'... 2024-07-05 21:32:26,069 | Configuration values successfully loaded.
2024-07-05 21:32:26,070 | Configuration values are: {'stack_name': 'sam_py', 'warm_containers': 'EAGER'}
2024-07-05 21:32:26,075 | Using SAM Template at
/home/nik/codes/BitSweepProject/paymentMockServer/sam_py/.aws-sam/build/template.yaml
2024-07-05 21:32:26,102 | Using config file: samconfig.toml, config environment: default
2024-07-05 21:32:26,103 | Expand command line arguments to:
2024-07-05 21:32:26,104 |
--template_file=/home/nik/codes/BitSweepProject/paymentMockServer/sam_py/.aws-sam/build/template.yaml --host=127.0.0.1
--port=3000 --static_dir=public --layer_cache_basedir=/home/nik/.aws-sam/layers-pkg --warm_containers=EAGER
--container_host=localhost --container_host_interface=127.0.0.1
2024-07-05 21:32:26,175 | local start-api command is called
2024-07-05 21:32:27,427 | No Parameters detected in the template
2024-07-05 21:32:27,444 | Sam customer defined id is more priority than other IDs. Customer defined id for resource
HelloWorldFunction is HelloWorldFunction
2024-07-05 21:32:27,445 | There is no customer defined id or cdk path defined for resource ServerlessRestApi, so we will use the resource logical id as the resource id
2024-07-05 21:32:27,447 | 0 stacks found in the template
2024-07-05 21:32:27,448 | No Parameters detected in the template
2024-07-05 21:32:27,461 | Sam customer defined id is more priority than other IDs. Customer defined id for resource
HelloWorldFunction is HelloWorldFunction
2024-07-05 21:32:27,462 | There is no customer defined id or cdk path defined for resource ServerlessRestApi, so we will use the resource logical id as the resource id
2024-07-05 21:32:27,464 | 2 resources found in the stack
2024-07-05 21:32:27,464 | Found Serverless function with name='HelloWorldFunction' and CodeUri='HelloWorldFunction'
2024-07-05 21:32:27,467 | --base-dir is not presented, adjusting uri HelloWorldFunction relative to
/home/nik/codes/BitSweepProject/paymentMockServer/sam_py/.aws-sam/build/template.yaml
2024-07-05 21:32:27,469 | watch resource
/home/nik/codes/BitSweepProject/paymentMockServer/sam_py/.aws-sam/build/template.yaml
2024-07-05 21:32:27,470 | Create Observer for resource
/home/nik/codes/BitSweepProject/paymentMockServer/sam_py/.aws-sam/build/template.yaml with recursive True
2024-07-05 21:32:27,473 | watch resource
/home/nik/codes/BitSweepProject/paymentMockServer/sam_py/.aws-sam/build/template.yaml's parent
/home/nik/codes/BitSweepProject/paymentMockServer/sam_py/.aws-sam/build
2024-07-05 21:32:27,475 | Create Observer for resource
/home/nik/codes/BitSweepProject/paymentMockServer/sam_py/.aws-sam/build with recursive False
2024-07-05 21:32:27,479 | Initializing the lambda functions containers.
2024-07-05 21:32:27,480 | Async execution started
2024-07-05 21:32:27,482 | Invoking function functools.partial(<function
InvokeContext._initialize_all_functions_containers..initialize_function_container at 0x73fd66fbeb90>,
Function(function_id='HelloWorldFunction', name='HelloWorldFunction', functionname='HelloWorldFunction',
runtime='python3.9', memory=128, timeout=30, handler='app.lambda_handler', imageuri=None, packagetype='Zip',
imageconfig=None, codeuri='/home/nik/codes/BitSweepProject/paymentMockServer/sam_py/.aws-sam/build/HelloWorldFunction',
environment=None, rolearn=None, layers=[], events={'HelloWorld': {'Type': 'Api', 'Properties': {'Path': '/hello',
'Method': 'get', 'RestApiId': 'ServerlessRestApi'}}}, metadata={'SamResourceId': 'HelloWorldFunction'}, inlinecode=None, codesign_config_arn=None, architectures=['x86_64'], function_url_config=None,
function_build_info=<FunctionBuildInfo.BuildableZip: ('BuildableZip', 'Regular ZIP function which can be build with SAM
CLI')>, stack_path='', runtime_management_config=None, logging_config=None))
2024-07-05 21:32:27,487 | Waiting for async results
2024-07-05 21:32:27,491 | No environment variables found for function 'HelloWorldFunction'
2024-07-05 21:32:27,492 | Loading AWS credentials from session with profile 'worldleaves'
2024-07-05 21:32:27,504 | Resolving code path.
Cwd=/home/nik/codes/BitSweepProject/paymentMockServer/sam_py/.aws-sam/build,
CodeUri=/home/nik/codes/BitSweepProject/paymentMockServer/sam_py/.aws-sam/build/HelloWorldFunction
2024-07-05 21:32:27,505 | Resolved absolute path to code is
/home/nik/codes/BitSweepProject/paymentMockServer/sam_py/.aws-sam/build/HelloWorldFunction
2024-07-05 21:32:27,507 | Resolving code path.
Cwd=/home/nik/codes/BitSweepProject/paymentMockServer/sam_py/.aws-sam/build,
CodeUri=/home/nik/codes/BitSweepProject/paymentMockServer/sam_py/.aws-sam/build/HelloWorldFunction
2024-07-05 21:32:27,508 | Resolved real code path to
/home/nik/codes/BitSweepProject/paymentMockServer/sam_py/.aws-sam/build/HelloWorldFunction
2024-07-05 21:32:27,519 | watch resource
/home/nik/codes/BitSweepProject/paymentMockServer/sam_py/.aws-sam/build/HelloWorldFunction
2024-07-05 21:32:27,520 | Create Observer for resource
/home/nik/codes/BitSweepProject/paymentMockServer/sam_py/.aws-sam/build/HelloWorldFunction with recursive True
2024-07-05 21:32:27,524 | watch resource
/home/nik/codes/BitSweepProject/paymentMockServer/sam_py/.aws-sam/build/HelloWorldFunction's parent
/home/nik/codes/BitSweepProject/paymentMockServer/sam_py/.aws-sam/build
2024-07-05 21:32:27,526 | Code /home/nik/codes/BitSweepProject/paymentMockServer/sam_py/.aws-sam/build/HelloWorldFunction is not a zip/jar file
2024-07-05 21:32:33,067 | Local image is up-to-date
2024-07-05 21:32:33,076 | Checking free port on 127.0.0.1:5743
2024-07-05 21:32:33,079 | Using local image: public.ecr.aws/lambda/python:3.9-rapid-x86_64.

2024-07-05 21:32:33,080 | Mounting
/home/nik/codes/BitSweepProject/paymentMockServer/sam_py/.aws-sam/build/HelloWorldFunction as /var/task:ro,delegated,
inside runtime container
2024-07-05 21:32:37,462 | Async execution completed
2024-07-05 21:32:37,463 | Containers Initialization is done.
2024-07-05 21:32:37,464 | Found '1' API Events in Serverless function with name 'HelloWorldFunction'
2024-07-05 21:32:37,465 | Detected Inline Swagger definition
2024-07-05 21:32:37,466 | Parsing Swagger document using 2.0 specification
2024-07-05 21:32:37,467 | Found '0' authorizers in resource 'ServerlessRestApi'
2024-07-05 21:32:37,467 | Lambda function integration not found in Swagger document at path='/hello' method='get'
2024-07-05 21:32:37,468 | Found '0' APIs in resource 'ServerlessRestApi'
2024-07-05 21:32:37,469 | Authorizer not found or disabled, returning early
2024-07-05 21:32:37,470 | Removed duplicates from '0' Explicit APIs and '1' Implicit APIs to produce '1' APIs
2024-07-05 21:32:37,471 | 1 APIs found in the template
2024-07-05 21:32:37,473 | Mounting HelloWorldFunction at http://127.0.0.1:3000/hello [GET]
2024-07-05 21:32:37,476 | You can now browse to the above endpoints to invoke your functions. You do not need to
restart/reload SAM CLI while working on your functions, changes will be reflected instantly/automatically. If you used
sam build before running local commands, you will need to re-run sam build for the changes to be picked up. You only need to restart SAM CLI if you update your AWS SAM template
2024-07-05 21:32:37,479 | Localhost server is starting up. Multi-threading = True
2024-07-05 21:32:37,480 | Setting SIGTERM interrupt handler
2024-07-05 21:32:37 WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.

mildaniel commented 1 week ago

Hi @nikhilrizal, thanks for reporting. I tried reproducing on a Linux machine with the same configuration but didn't have any luck. Can you provide your template to see what exact configurations you have? Also, are you running a sam build before running the local commands?

nikhilrizal commented 1 week ago

Hi @nikhilrizal, thanks for reporting. I tried reproducing on a Linux machine with the same configuration but didn't have any luck. Can you provide your template to see what exact configurations you have? Also, are you running a sam build before running the local commands?

Thanks for your response!

Yes, I am building the project with sam build and then running sam local start-api to start the local API.

I managed to resolve the issue by adding --debug --profile xxx --container-host-interface 0.0.0.0 to the sam local start-api command. It seems the problem was related to Docker networking configurations.

It's important to note that many developers might encounter similar issues, and it would be helpful if the documentation provided more guidance or warnings about such configuration nuances.

Template is the same as the started default template but here is the [AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 Description: > sam_py

Sample SAM Template for sam_py

More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst

Globals: Function: Timeout: 30 MemorySize: 128

Resources: HelloWorldFunction: Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction Properties: CodeUri: hello_world/ Handler: app.lambda_handler Runtime: python3.11 Architectures:

Outputs:

ServerlessRestApi is an implicit API created out of Events key under Serverless::Function

Find out more about other implicit resources you can reference within SAM

https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api

HelloWorldApi: Description: "API Gateway endpoint URL for Prod stage for Hello World function" Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/" HelloWorldFunction: Description: "Hello World Lambda Function ARN" Value: !GetAtt HelloWorldFunction.Arn HelloWorldFunctionIamRole: Description: "Implicit IAM Role created for Hello World function" Value: !GetAtt HelloWorldFunctionRole.Arn ]

github-actions[bot] commented 1 week ago

⚠️COMMENT VISIBILITY WARNING⚠️

Comments on closed issues are hard for our team to see. If you need more assistance, please either tag a team member or open a new issue that references this one. If you wish to keep having a conversation with other community members under this issue feel free to do so.