2

I have tried searching but my googlefu is failing me.

I have a basic python lambda function:

def lambda_handler(event, context):
    foo = event['bar']
    print(foo)

I then try and do a POST, like this in curl:

curl -X POST https://correctaddress.amazonaws.com/production/test \
-H 'x-api-key: CORRECTKEY' \
-H 'content-type: application/json' \
-H 'bar: Hello World' \

This fails KeyError: 'bar' probably because what I think I am passing as event['bar'] is not being passed as such.

I have tried event['body']['bar'] which also fails.

If I do event['querystringparameters']['bar'] it will work if I use a GET such as:

curl -X POST https://correctaddress.amazonaws.com/production/test?bar=HelloWorld -H 'x-api-key: CORRECTKEY'

I know I am missing something fundamental about the event dictionary, and what it pulls from for a POST, but I can't seem to find the right documentation (unsure of if it would be in API or Lambda's documentation).

My eventual goal is to be able to write something in python using Requests like this:

import requests, json

url = "https://correctaddress.amazonaws.com/production/test"
headers = {'Content-Type': "application/json", 'x-api-key': "CORRECTKEY"}
data = {}
data['bar'] = "Hello World"
res = requests.put(url, json=data, headers=headers)

1 Answer 1

6

The problem is in the way you are executing your curl command.

You are using the -H (--header) argument to add your parameter. But you are expecting a JSON post request.

To do so change your curl statement to something like this:

curl -X POST https://correctaddress.amazonaws.com/production/test \
-H 'x-api-key: CORRECTKEY' \
-H 'content-type: application/json' \
--data '{"bar":"Hello World"}' \

This will make curl do a post request with the appropriate body.

In your Python you can get the postdata as a dictionary using some code similar to this:

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

You should add some error checking for invalid JSON, other request types (e.g. GET), etc.

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

3 Comments

that didn't work... curl -X POST https://correctaddress.amazonaws.com/production/test -H 'x-api-key: CORRECTKEY' -H 'content-type: application/json' --data '{"bar":"Hello World"}' I still get errors. if I use foo = event['body']['bar'] it tells me TypeError: string indices must be integers. If I use foo = event['bar'] it tells me KeyError: 'bar'
Event['body'] is a string containing the JSON data. You can decode it using the json module. json.loads(...)
yup, that's what I ended up doing. Would it be appropriate for you to edit your answer and add that? Maybe it'll help someone in the future as well.

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.