简体   繁体   中英

Python can't read body in API Gateway request?

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?

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))

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