2

Issue at hand : Malformed Lambda exception only when accessing event data.

When I access the event, API Gateway returns an "Internal server error". A simplified use case of something I'd like to do would be to access the values of a key given to the Lambda from a POST request, proxy integration is used so there should be no need for template mapping.

import json

def lambda_handler(event, context):
   items = {}
   items["hello"] = "name"

   itemsarray = []
   for key, value in event.items() :
       itemsarray.append(key + ":" + value)

   return {
       'statusCode': 200,
       'isBase64Encoded': False,
       'body' : json.dumps(items),
       'headers': {
            'content-type': 'application/json'
        }
   };

Error Message from API Gateway, Lambda itself returns no errors on the code.


Thu Feb 15 13:24:51 UTC 2018 : Received response. Integration latency: 742 ms
Thu Feb 15 13:24:51 UTC 2018 : Endpoint response body before transformations: {"errorMessage": "must be str, not NoneType", "errorType": "TypeError", "stackTrace": [["/var/task/lambda_function.py", 9, "lambda_handler", "itemsarray.append(key + \":\" + value)"]]}
Thu Feb 15 13:24:51 UTC 2018 : Execution failed due to configuration error: Malformed Lambda proxy response
Thu Feb 15 13:24:51 UTC 2018 : Method completed with status: 502

JSON Post Data


{ "dummy": "hello", "data": "world" }

1 Answer 1

4

Answering my own question to save someone hours of pain in years to come. I was tempted to do "NVM got it". Either way here you go.

The event body returns a string.

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

Now for interacting with it. If we had a JSON structure like

{
"someVar": "out",
  "data": {
    "message": "another out"
  }
}

data['data']

would return us "message": "another out"

NOTE In the lambda compiler online. It gives the following error, but once interacting with it via something like postman or API Gateway it works fine. It seems to give a false negative that threw me for an extended period of time.

'body': KeyError
Traceback (most recent call last):
  File "/var/task/lambda_function.py", line N, in lambda_handler
    var= json.loads(event['body'])
KeyError: 'body'

Now raise a beer for my hours wasted and thank God stack overflow is a thing

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

1 Comment

I don't understand how you solved it. Im having the same error rn actually. Well if i passed a json in my apigateway as {"foo":"bar"}. How am i supposed to access that in my python? like this? foo = json.loads(event["body"])["foo"] @eternal_atom

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.