Python AWS Lambda's event body returning string instead of my json object

Viewed 3219

Invocation code

import requests
import json
# Create a new resource
data_object = {'key1':'testing'}
response = requests.post('https://fakeurl.execute-api.us-east-1.amazonaws.com/default/My_Test_Event_Lambda', data=data_object)

print(response._content.decode())

Lambda Code

import json

def lambda_handler(event, context):

    return {
                'statusCode': 200,
                'body': json.dumps(event['body'])
            }

The response I get from invocation is "key1=testing" I don't care so much about the response but i want the lambda function to be able to handle my data passed as json not a string. Example: I want to be able to say event['body']['key1'] and have it return "testing"

Currently API gateways being used as lambda proxy.

1 Answers

The event['body'] you received is a string. You need to parse that from JSON into a dict with:

d = json.loads(event['body'])

Then you can return that dict as the body in your response, if you want, via:

return {
    'statusCode': 200,
    'body': json.dumps(d)
}

As it stands, you're just managing strings.

Related