Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
}
like image 853
Binod Karunanayake Avatar asked Aug 02 '19 06:08

Binod Karunanayake


People also ask

Does API gateway retry Lambda?

There won't be an automatic Lambda retry when it's invoked from API Gateway afaik. If you are throttled or the request fails (perhaps because of a Lambda function error), your client is responsible for deciding how to recover and whether or not to retry, likely based on the HTTP response code.

What is Lambda proxy integration?

The Lambda proxy integration allows the client to call a single Lambda function in the backend. The function accesses many resources or features of other AWS services, including calling other Lambda functions.

What is Lambda function URL?

A function URL is a dedicated HTTP(S) endpoint for your Lambda function. You can create and configure a function URL through the Lambda console or the Lambda API. When you create a function URL, Lambda automatically generates a unique URL endpoint for you. Once you create a function URL, its URL endpoint never changes.


1 Answers

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)
    }
like image 128
Binod Karunanayake Avatar answered Sep 28 '22 01:09

Binod Karunanayake