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
preguntada hace 2 meses272 visualizaciones
2 Respuestas
0
Respuesta aceptada

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
EXPERTO
respondido hace 2 meses
profile picture
EXPERTO
revisado hace 2 meses
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
respondido hace 2 meses

No has iniciado sesión. Iniciar sesión para publicar una respuesta.

Una buena respuesta responde claramente a la pregunta, proporciona comentarios constructivos y fomenta el crecimiento profesional en la persona que hace la pregunta.

Pautas para responder preguntas