Skip to content

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:

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

2 Answers
0
Accepted Answer

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"])
AWS
EXPERT
answered a year ago
EXPERT
reviewed a year ago
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'])
        # 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,