简体   繁体   中英

AWS Lambda-API gateway "message": "Internal server error" (502 Bad Gateway)

I created a simple AWS Lambda function to add two numbers using python 3.6. It reads val1 & val2 values in json body. When I tested lambda function in lambda console it works fine. But when I call lambda function by a POST request through AWS API gateway using POSTMAN, it responses with "message": "Internal server error" (502 Bad Gateway). Can anyone help me with this error?

Lambda function

import json
def lambda_handler(event, context):
    # TODO implement
    val1 = int(event['val1'])
    val2 = int(event['val2'])
    val3 = val1 + val2
    return {
        'statusCode': 200,
        'headers': {'Content-Type': 'application/json'},
        'body': json.dumps(val3)
    }

JSON body

{
    "val1": "3",
    "val2": "5"
}

This error occurs due to the behaviour of the event object (python dictionary). When you test lambda function in lambda console JSON body will directly passed to the event object. But when you try it through API gateway, not only event object is the request payload but also body attribute is set as a string.

For example your JSON body will be like this in event object

body: "{\n    \"val1\": \"3\",\n    \"val2\": \"5\"\n}"

To resolve this error try json.loads() method to convert body string to json.

import json
def lambda_handler(event, context):
    # TODO implement
    try:
        event = json.loads(event['body'])
        val1 = int(event['val1'])
        val2 = int(event['val2'])
        val3 = val1 + val2
    except:
        val3 = 'request error'
    return {
        'statusCode': 200,
        'headers': {'Content-Type': 'application/json'},
        'body': json.dumps(val3)
    }

I ended up here with the same error only I was using Serverless and Node. I was returning an HTTP response without using stringify on the body. As seen in the bad example below:

Bad:

return {
            statusCode,
            body: body.message,
            headers: {
                "Access-Control-Allow-Origin": "*",
                "Access-Control-Allow-Credentials": true,
            },
        };
    };
}

Good:

return {
            statusCode,
            body: JSON.stringify(body.message),
            headers: {
                "Access-Control-Allow-Origin": "*",
                "Access-Control-Allow-Credentials": true,
            },
        };
    };
}

I hope this helps others who may run into the 502 error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM