1

I'm trying to code a Lambda function that is invoked via a hit to an API Gateway endpoint. Simply returning the event, I can see that there is a body in the response:

def lambda_handler(event, context):
    return str(event)

Response:

{
    'version': '2.0',
    'routeKey': 'ANY /identify',
    'rawPath': '/default/identify',
    'rawQueryString': '',
    'headers':
    {
       ...
    },
    'requestContext':
    {
       ...
    },
    'body': '<base64 encoded string is here>',
    'isBase64Encoded': True
}

However, as soon as I try to return just the body, I get the following error (multiple examples included which all return the same error).

def lambda_handler(event, context):
    return str(event['body'])
def lambda_handler(event, context):
    return json.loads(event['body'])
def lambda_handler(event, context):
    params = parse_qs(event["body"])
def lambda_handler(event, context):
    return event['body']
{
  "errorMessage": "'body'",
  "errorType": "KeyError",
  "requestId": "5acbcc66-da05-429f-baa9-6c8d83801b4f",
  "stackTrace": [
    "  File \"/var/task/lambda_function.py\", line 10, in lambda_handler\n    return json.loads(event['body'])\n"
  ]
}

Any ideas?

3

1 Answer 1

1

KeyError indicates that you're trying to access a key in a Python dictionary that doesn't exist.

According to the documentation: "API Gateway invokes your function with an event that contains a JSON representation of the HTTP request."

I think that what is happening is when you're returning str(event) it just returns the stringified version of the json event. But when you try to access event[body] in your handler without running json.loads() on the json first, you get the KeyError above instead. I typically run json.loads() first in all my handlers and then assign that to a data object (which is a Python dictionary) as below:

data = json.loads(event["body"])

Then I can use that body:

print("[DEBUG] event['body']: {}".format(data))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.