How do I write a Python function that returns a given (json) body with a given HTTP response code?

Question:

I have the following (default) code in an AWS lambda function:

def lambda_handler(event, context):
    return {"statusCode": 200, "body": ""Hello from Lambda!""}

I also have this hooked up to an HTTP endpoint in the REST API section of the AWS web interface. Seemingly, the idea of this is that this will get converted into an HTTP response with body "Hello from Lambda!" and status code 200, but what I actually see when I hit the endpoint with CURL is:

$ curl -X POST https://redacted.execute-api.us-east-1.amazonaws.com/testing/
{"statusCode": 200, "body": ""Hello from Lambda!""}

So the return value of the function just seems to get converted to JSON and sent right through. I’m finding it very hard to Google for answers here. How do I set this thing up so I can control the status response, response body, and response headers from within the lambda function?

Asked By: Jack M

||

Answers:

In order for Lambda status codes to be returned from an API request, you must enable Lambda Proxy Integration, or create a Mapping Template. Both of these are done in the Integration Request section of your Method in API Gateway.

In order to find the Integration Request section of your Lambda, click on the Method (i.e. POST), and you will see Integration Request in the upper right of the four boxes in the Console.

The Lambda Proxy Integration requires your Lambda function must output the result in the format described here :

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

Info on handling Lambda errors for a Custom (not Proxy) Integration are here :

https://docs.aws.amazon.com/apigateway/latest/developerguide/handle-errors-in-lambda-integration.html

Answered By: Chris Miller