aws lambda + http api with Payload Format Version 2.0. How to correctly parse the payload with Python 3.12 runtime

0

I am developing a lambda (runtime Python 3.12) that will process events via POST requests to a API Gateway HTTP API.

According to the AWS console, the integration I have set up between the POST route on my API and my lambda function has "Payload format version 2.0 (interpreted response format).

Here is the documentation about that payload format.

That documentation gives me the (apparently wrong) impression that in the Python runtime, the "event" parameter passed to the lambda is a dict that has (among other things) an attribute 'body' that has a value that is a string.

Thus, based on that (again, apparently wrong) impression, my lambda function tries to access the data in the body of the request (which I expect to be a JSON formatted string) like this:

req_body = json.loads(event.body)

When I run a test of my function using the console, my function raises this exception:

{
  "errorMessage": "'dict' object has no attribute 'body'",
  "errorType": "AttributeError",
  "requestId": "83b129eb-cf1e-4afa-9215-a0f3c0d18cec",
  "stackTrace": [
    "  File \"/var/task/lambda_function.py\", line 33, in handler\n    req_body = json.loads(event.body)\n"
  ]
}

Here is a screenshot of the test that is leads to the raised exception: Enter image description here

What do I not correctly understand about the event object delivered to a Python 3.12 lambda function by an HTTP API using Payload format version 2.0?

Thanks.

1개 답변
3
수락된 답변

Hi,

You should rather do :

payload = json.loads(event)
req_body = payload.body

As a matter of fact, you need to convert event to a dict (which I called payload here) before accessing the body attribute of this dict

Best,

Didier

profile pictureAWS
전문가
답변함 2달 전
profile picture
전문가
검토됨 2달 전
profile picture
전문가
검토됨 2달 전
profile picture
전문가
검토됨 2달 전

로그인하지 않았습니다. 로그인해야 답변을 게시할 수 있습니다.

좋은 답변은 질문에 명확하게 답하고 건설적인 피드백을 제공하며 질문자의 전문적인 성장을 장려합니다.

질문 답변하기에 대한 가이드라인