5

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?

5
  • Try showing event keys by calling event.keys() inside the lambda_handler method and see what pops up. Commented Aug 8, 2020 at 0:19
  • Where exactly would I do that? Where it says event['data']? If I do that and call my python function I still get an internal server error which doesn't really help.. Commented Aug 8, 2020 at 0:24
  • above the return statement Commented Aug 8, 2020 at 0:26
  • 1
    Thanks, if I do that, how/where would I see the output of that line? Commented Aug 8, 2020 at 0:30
  • I'm finding there are quite a few essential assumptions that are largely undocumented about using AWS Lambda. Does AWS convert your response to JSON or not, possibly controlled by a flag in the AWS configuration, how are stderr stdout handled, what is the default logging set up, etc. I like that "where would I see the output" question - exactly! Commented Feb 14, 2023 at 6:09

1 Answer 1

13

Try

import json

def lambda_handler(event, context):
    body = json.loads(event['body'])
    return {
        'statusCode': 200,
        'body': json.dumps(body['data'])
    }
Sign up to request clarification or add additional context in comments.

4 Comments

Try again, I added a json.dumps @WilliamSteenbergen
@WilliamSteenbergen try again
yes that works, thanks so much! the json.loads does it.
@WilliamSteenbergen no prob

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.