eternal_atom
eternal_atom

Reputation: 139

AWS Lambda Malformed Lambda with Proxy Integration when accessing event

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" }

Upvotes: 2

Views: 1408

Answers (1)

eternal_atom
eternal_atom

Reputation: 139

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

Upvotes: 4

Related Questions