My functions section in serverless.yml
looks similar to:
functions:
MyLambda:
handler: handler.sayHello
name: my-lambda-say-hello
events:
- http:
path: /myPpath
method: post
cors: true
- schedule:
name: my-schedule-event
description: 'bla bla'
rate: rate(10 minutes)
input:
body: '{"name": "John"}'
My handler.sayHello
lambda function looks like:
import json
def sayHello(event, context):
#Works for HTTP
print(json.loads(event['body'])['name'])
#Works for Cloudwatch schedule event
print(event['body']['name']
So basically I have a lambda function that gets a name and prints it.
This Lambda is triggered either by an HTTP request (I send the data as JSON in body) or by scheduled Cloudwatch event.
As you can see in my Lambda function, when I'm trying to extract the name
property when it comes from an HTTP request, I need to json.loads()
the event body object.
However, when it comes from a scheduled event, I don't need to json.loads()
it at all.
Is it possible to somehow make my Lambda support both of those events, without toggling the json.loads()
?
Thanks!
The event
payload of a Lambda function will vary depending on the invoking service. They are not the same across Cloudwatch, API Gateway, or other services like SNS, SQS, EventBridge, DynamoDB, S3 - and more.
Instead, you'll need to add logic which can conditionally extract the name
(and other attributes) depending on the invoking service.
You can either wrap json.loads
in a try/except
block, or you could check if the event
contains a requestContext
key; which would indicate the function was triggered by an HTTP Request through API Gateway.