简体   繁体   English

Python 无法读取 API 网关请求中的正文?

[英]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.我正在尝试编写一个 Lambda function 代码,该代码是通过对 API 网关端点的命中来调用的。 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. KeyError表示您正在尝试访问 Python 字典中不存在的键。

According to the documentation : "API Gateway invokes your function with an event that contains a JSON representation of the HTTP request."根据文档:“API Gateway 使用包含 HTTP 请求的 JSON 表示的事件调用您的 function。”

I think that what is happening is when you're returning str(event) it just returns the stringified version of the json event.我认为正在发生的事情是当您返回str(event)时,它只返回 json 事件的字符串化版本。 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.但是,当您尝试访问处理程序中的event[body]而不首先在 json 上运行json.loads()时,您会得到上面的KeyError 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:我通常首先在我的所有处理程序中运行json.loads()然后将其分配给data object (这是一个 Python 字典),如下所示:

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

Then I can use that body:然后我可以使用那个身体:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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