bearrider
bearrider

Reputation: 322

AWS lambda api gateway error “Malformed Lambda proxy response”

My AWS ApiGateway invokes this lambda function :

const handler = (event, context) => {

    const theResponse = {
        "statusCode": 200,
        "isBase64Encoded": false,
        "headers": {
            "Content-Type": "application/json"
        },
        "body": "hello, world"
    };

    switch (event.httpMethod) {
        case 'GET':
            theResponse["body"] = `method ${event.httpMethod} detected`;
            break;
        default:
            theResponse["statusCode"] = 404;
            theResponse["body"] = `Unsupported method ${event.httpMethod} detected`;
            break;
    }
    return theResponse;
};


module.exports = {
    handler,
};

Any thoughts to why this errors with :

{"message": "Internal server error"}
Received response. Status: 200, Integration latency: 344 ms
Endpoint response body before transformations: null
Execution failed due to configuration error: Malformed Lambda proxy response
Method completed with status: 502

I tried replacing return (theResponse); with return JSON.stringify(theResponse); but this also returns the same error.

However if I replace return theResponse; with return {"statusCode":200, "body":"hello, world"}; then the API executes without errors.

Looks to me like a lamda_proxy integration issue but I can't see why. thanks.

Upvotes: 0

Views: 427

Answers (1)

Guina Costa
Guina Costa

Reputation: 26

Bearrider!

I guess it is related to the way you are building your response object:

  • Try stringify only the body attribute:

        case 'GET':
            theResponse["body"] = JSON.stringify(`method ${event.httpMethod} detected`);
            break;
        default:
            theResponse["statusCode"] = 404;
            theResponse["body"] = JSON.stringify(`Unsupported method ${event.httpMethod} detected`);
            break;
        }
    

Upvotes: 1

Related Questions