简体   繁体   中英

How do I pass variables to Python Lambda from AWS API

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)

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 (eg GET), etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM