6

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 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

7 Comments

Hmmm I'm getting a key error when i use your code. { "errorMessage": "'body'", "errorType": "KeyError", "stackTrace": [ " File \"/var/task/lambda_function.py\", line 4, in lambda_handler\n d = json.loads(event['body'])\n" ] }
Are you using Lambda Proxy integration in API Gateway?"
Yea i'm using the proxy integration Type: LAMBDA_PROXY is displayed in Integration Request
Did you debug log event to see what's in it? I assumed this was already working to retrieve the body, because your original code uses it.
Because the body is not actually JSON, perhaps? It's just key=value when it should be {"key":"value"} (assuming you actually meant to pass JSON over the interface).
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.