David
David

Reputation: 3036

AWS Lambda: key error when sending a POST message

I have a very simple problem: my lamda function works fine as long as i do not write something like "a = event["key"], but a = "test":

This is from Cloudwatch: @message
[ERROR] KeyError: 'key1' Traceback (most recent call last): @message
[ERROR] KeyError: 'key1' Traceback (most recent call last): File "/var/task/lambda_function.py", line 5, in lambda_handler a = event["key1]

This is what i have sent with postman (i even tried curl) in the body as raw data:

{
  "key1": "value1",
  "key2": "value2",
  "key3": "value3"
}

My lamda function looks like this:

import json

def lambda_handler(event, context):
    # TODO implement
    a = event["key1"]
    return {
        'statusCode': 200,
        'body': json.dumps(a)
    }

Upvotes: 1

Views: 4746

Answers (2)

David
David

Reputation: 3036

Fastest way for me was to use a HTTP API and use form-data with key1=test. Then i printed event["body"] and found out that my body was base64 encoded. I used the following code to make that visible:

import json
import base64
    
    def lambda_handler(event, context):
        # TODO implement
        a = event["body"]
        print(a)
        message_bytes = base64.b64decode(a)
        message = message_bytes.decode('ascii')
        return {
            'statusCode': 200,
            'body': json.dumps(message)
        }

The output was:

"----------------------------852732202793625384403314\r\nContent-Disposition: form-data; name=\"key1\"\r\n\r\ntest\r\n----------------------------852732202793625384403314--\r\n"

Upvotes: 0

Balu Vyamajala
Balu Vyamajala

Reputation: 10333

REST Api LAMBDA will pass the request as is where as LAMBDA_PROXY will append additonal metadata on query parms, api keys, etc. so, the input request body is passed as json string as attribute body. json.loads(event['body']) will give us the actual request body.

More details on changing integration type is here

Below code can extract key1 from input json object for Lambda_Proxy.

import json

def lambda_handler(event, context):

    print(event)
    a = json.loads(event['body'])['key1']
    return {
        'statusCode': 200,
        'body': json.dumps(a)
    }

Upvotes: 3

Related Questions