1

How to test if event contains body json element? I get the following error [ERROR] KeyError: 'body'. I want to ensure that even curl can call lambda function as well as other lambda functions can call this lambda. But when the request is not through curl, then there is no body element hence I'm trying to create a if condition to set variables.

from modules.ZabbixSender import ZabbixSender
import json

def lambda_handler(event, context):
    
    print(event)

    if event["body"]: // KEY ERROR
        requestBody = json.loads(event["body"])
    else:
        requestBody = json.loads(event)
        
    print(requestBody)

    Host = requestBody['Host']
    Key = requestBody['Key'] 
    Value = requestBody['Value']

    sender = ZabbixSender("10.10.10.10", 10051)
    sender.add(Host, Key, Value)
    sender.send()
    
    return {
        "statusCode": 200,
        "headers": {
            "Content-Type": "application/json"
        },
        "body": json.dumps({
            "Host": Host,
            "Key" : Key,
            "Value" : Value,
            "Status": "Successfully updated Zabix Server"
        })
    }
user630702
  • 2,529
  • 5
  • 35
  • 98

2 Answers2

1

If event is a dictionary you could simply use the get method on dictionaries. Like this:

if event.get("body"):
    requestBody = json.loads(event["body"])
else:
    requestBody = json.loads(event)

or event better you could drop this into a one-liner:

requestBody = json.loads(event["body"]) if event.get("body") else json.loads(event)

In this way if the key exists on the dictionary it will return the value of the key, otherwise it will return None. This should give you the behavior that you expect.

EnriqueBet
  • 1,482
  • 2
  • 15
  • 23
1

You can try this:

if "body" in event:
    requestBody = json.loads(event["body"])
else:
    requestBody = json.loads(event)

which can be written to

requestBody = json.loads(event["body"]) if "body" in event else json.loads(event)
Ballack
  • 906
  • 6
  • 12