William Steenbergen
William Steenbergen

Reputation: 53

Access json request from python in python AWS lambda function

I have an API in the AWS API gateway, connected to an AWS Lambda function in python, using lambda proxy integration. On my local computer, I am testing this API in python. I want to send a dictionary to the api and have the api return me a function of the elements in the dictionary.

The python code I use to test is:

import requests
import json

url = "https://p68yzl6gu6.execute-api.us-west-1.amazonaws.com/test/helloworld"

headers = {'data': [0,1]}

response = requests.post(url, json=headers)

print(response.text)

Since I cannot send a list through the header argument of requests.post I thought I'd use json. When I try this, I get a {"message": "Internal server error"}. This is my AWS lambda function (python):

import json

def lambda_handler(event, context):
    return {
        'statusCode': 200,
        'body': event['data']
    }

Looking at the logs, 'data' is not a key of event. How do I access the list in the AWS Lambda function? How do I find out what the event dictionary looks like when I test this? Looking forward I want to send a large dict containing dicts and lists. Is this the right way to do it?

Upvotes: 5

Views: 10245

Answers (1)

jellycsc
jellycsc

Reputation: 12359

Try

import json

def lambda_handler(event, context):
    body = json.loads(event['body'])
    return {
        'statusCode': 200,
        'body': json.dumps(body['data'])
    }

Upvotes: 13

Related Questions