How to handle 2 triggers in 1 lamda function?

0

I have 2 triggers in 1 lamda function, API gateway and AWS IOT , how can i handle 2 separate event jsons in 1 lamda functions, is it possible? IF yes, help me out with the code layout in python.

3 Answers
0
Accepted Answer

Regarding your comment "i need both the events to be processed simultaneously" please note the difference between a Lambda function definition and an instance. If a defined function gets two trigger events it will run two separate instances. If you need coordination between the two I suggest you look at Step Functions as a way for one event flow to wait for the other without consuming Lambda compute time.

If you head this direction it's probably cleaner to split your current function definition into two, each handling one of the two trigger event types, rather than overloading one function definition to cover both.

EXPERT
answered a year ago
0

Hi, this is easily achievable. You will have to customize your code a bit and use if else condition. So I checked the APIGW and IOT payload format from the AWS documentations and they have slightly different format which will be helpful to achieve your case.

----------------SAMPLE CODE----------------
import json

def lambda_handler(event, context):
    # TODO implement
    if "event" in event:
        iotProcessing(event)
    else:
        apigwProcessing(event)
        
def iotProcessing(event):
    print("IOT Event")
    #perform some actions
    #return
    
def apigwProcessing(event):
    print("API Gateway Event")
    #perform some actions
    #return

Documents for payload format

  1. APIGW - https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html
  2. IOT - https://docs.aws.amazon.com/lambda/latest/dg/services-iotevents.html

Note: For sample, I have used REST API with proxy integration as example.

Shivam
answered a year ago
EXPERT
reviewed a year ago
  • I am using a websocket api and i forward data recieved by iot core via mqtt to the lamda function, I am planning so that, whenever a client connects to the websocket it gets the data of iot core in real time, so i need both the events to be processed simultaneously.

0

Yes it can be possible to add more than 1 trigger to lambda function

Below are the Code need to change in code section

import json

def lambda_handler(event, context): # TODO implement if "event" in event: iotProcessing(event) else: apigwProcessing(event)

def iotProcessing(event): print("IOT Event") #perform some actions #return

def apigwProcessing(event): print("API Gateway Event") #perform some actions #return

profile picture
answered a year ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions