If you’ve tried hooking up Lambda functions to the API Gateway before, chances are that you’ve seen internal server errors when trying to curl your endpoint. Today we’re going to cover one of the common mistakes that result in these errors.

We’ll debug by first testing the Lambda function in isolation, then the API Gateway on top of it. Navigate to your Lambda function, and run the Test button. You should see a successful result as shown below - if not, work on fixing that issue before moving on.

aws lambda successful run

After, let’s look at exactly what is being returned by your Lambda function. In order for it to be processed and forwarded on by the API gateway, it needs to look a certain way.

import json

def lambda_handler(event, context):
    # this object is valid 
    return {
        'statusCode': 200,
        'headers': { 'Content-Type': 'application/json' },
        'body': json.dumps({ 'username': 'bob', 'id': 20 })

The returned object must have a statusCode, body, and headers attribute. In my example above, I included Content-Type in the headers object, but it can be empty if you’d like. body’s value must be a string, if we were to pass in the user object here without turning it into a JSON-encoded string, this would fail.

If your return object doesn’t have these attributes, when you test the Lambda-API Gateway connection an error like this will pop up:

api gateway malformed response

As you can see, the error is a Malformed Lambda proxy response. By making sure that your Lambda function returns the correct format, you’ll avoid these pesky internal server errors.

One more important note, this return format only matters when using the API Gateway-Lambda combination in proxy mode. If you do not check the proxy option, then you can return whatever you’d like, the API gateway will forward it on.

Hopefully this helps you save some time! Again, feel free to contact me or email me at phouse512 at gmail.com if you can’t figure it out.