error trying to parse event from API HTTP integration in lambda Python 3.12 runtime


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/\", line 33, in handler\n    payload = json.loads(event)\n",
    "  File \"/var/lang/lib/python3.12/json/\", 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.

2 Answers
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"])
profile pictureAWS
answered 13 days ago
profile picture
reviewed 12 days ago

This works for me:

import json
import base64

# import requests

def lambda_handler(event, context):
   #print out the body of the request
        # 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 -X POST -d '{"key1":"value1", "key2":"value2"}'

{"message": "{\"key1\":\"value1\", \"key2\":\"value2\"}"}%                 
profile picture
answered 12 days ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions