0
votes

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)
    }
2
you are calling the lambda from cli or aws api call or lambda from api gateway?Balu Vyamajala
from Postman to the API gateway, it is working, but somehow the variables, which are "posted" are not foundDavid
you are using LAMBDA or LAMBDA_PROXY in integration request in API Gateway?Balu Vyamajala
Here , i just suspecting that if you are using LAMBDA_PROXY , the schema sent to Lambda will be different, it will append additional metadata and all.Balu Vyamajala

2 Answers

1
votes

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)
    }
0
votes

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"