Behrooz
Behrooz

Reputation: 1955

AWS API Gateway with Lambda not seeing the body

I have a Lambda function which works perfectly fine when executed directly. As it's just for testing at the moment, it only reads the request body and returns the value of one of the children in response:

exports.handler = async (event) => {

    const response = {
        "isBase64Encoded": false,
        "headers": {
            "Content-Type": "application/json"
        },
        "statusCode": 200,
        "body": event.body.maxNumber
    };
    return response;
};

However, when I create an Api out of it using the AWS Api Gateway, there is a strange behavior happening. If the Lambda function contains the code above, the response body is just empty. However, if instead of a child (the maxNumber in this case), I change the response to return the entire request body, it does return it. Anyhow, while the lambda function works fine in isolation, when behind the API Gateway it appears it cannot see the children of the request body.

I have created both HTTP and REST apis, both with and without the proxy enabled, and no luck. Also cannot find any documentation specifically sampling something like my case (request body). Any help would be greatly appreciated.

Upvotes: 4

Views: 6950

Answers (1)

nirvana124
nirvana124

Reputation: 1033

For API Gateway proxy response, the body should be a string.

First, you need to parse the request body to get the JSON object and inside response, you need to stringify the response body as mentioned below :

const body = JSON.parse(event.body);

const response = {
        "isBase64Encoded": false,
        "headers": {
            "Content-Type": "application/json"
        },
        "statusCode": 200,
        "body": JSON.stringify(body.maxNumber)
    };
    return response;

Upvotes: 4

Related Questions