error trying to parse event from API HTTP integration in lambda 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. My lambda function tries to parse the payload it receives with the following line:

payload = json.loads(event)

When I test the function, this line causes the following exception to be raised:

{
  "errorMessage": "the JSON object must be str, bytes or bytearray, not dict",
  "errorType": "TypeError",
  "requestId": "47eb32f4-97a9-44de-a144-bc19b5d7e959",
  "stackTrace": [
    "  File \"/var/task/lambda_function.py\", line 33, in handler\n    payload = json.loads(event)\n",
    "  File \"/var/lang/lib/python3.12/json/__init__.py\", line 339, in loads\n    raise TypeError(f'the JSON object must be str, bytes or bytearray, '\n"
  ]
}

Here is a screenshot of the test that generates that exception: Enter image description here

Note that this question is following up on the accepted answer to this earlier question.

stu
已提問 2 個月前檢視次數 280 次
2 個答案
0
已接受的答案

The event is already received by the lambda function as python dictionary so you do not need to use json.loads() to parse the event.

What you are probably trying to achieve is to parse the POST json body from the event and convert it from json string to python dictionary. So you need to do something like this:

body = json.loads(event["body"])
profile pictureAWS
專家
已回答 2 個月前
profile picture
專家
已審閱 2 個月前
0

This works for me:

import json
import base64

# import requests


def lambda_handler(event, context):
   #print out the body of the request
    print(event['body'])
    
    try:
        # Decode the Base64 encoded body
        decoded_body = base64.b64decode(event['body']).decode('utf-8')
    except (ValueError, UnicodeDecodeError):
        # Handle decoding errors
        decoded_body = 'Error: Invalid Base64 encoded body'

    return {
        "statusCode": 200,
        "body": json.dumps({
            "message": decoded_body,
        }),
    }

and then when I test it:

curl https://abc123.execute-api.af-south-1.amazonaws.com/Prod/create -X POST -d '{"key1":"value1", "key2":"value2"}'

{"message": "{\"key1\":\"value1\", \"key2\":\"value2\"}"}%                 
profile picture
已回答 2 個月前

您尚未登入。 登入 去張貼答案。

一個好的回答可以清楚地回答問題並提供建設性的意見回饋,同時有助於提問者的專業成長。

回答問題指南