Getting an AWS Lambda Function to work with an API Gateway Trigger

AWS Lambda is Amazon’s way to allow you to write functions that can run without having to provision an EC2 instance. One way that these can be triggered is through an HTTP request using the API Gateway. But out of the box, if you try to do this you will get an HTTP Status code of 502, and if you investigate further using the API Gateway test functionality you will see an error message saying “Execution failed due to configuration error: Malformed Lambda proxy response”

The problem is that there is an extra requirement in place for Lambda functions that are using API Gateway as a trigger. They must return a specifically formatted JSON result as indicated at the bottom of this web page

Unfortunately the default “Hello World” code you are given looks like this, which does not conform to the required JSON format:

exports.handler = (event, context, callback) => {
    // TODO implement
    callback(null, 'Hello from Lambda');

You can get it to work by changing the callback to return an object instead of a string, like this:

exports.handler = (event, context, callback) => {
    callback(null, {
        'statusCode': 200, 
        'headers': {}, 
        'body': 'Hello from Lambda'

There is one more thing that you may need to watch out for. If you are trying to execute your lambda function from client-side code in a web browser, you might also run into an error on the client-side where you get an HTTP status code of 403 and message saying No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 403.

You can get around this problem by enabling CORS on your API Gateway resource.

Leave a Reply

Your email address will not be published. Required fields are marked *