Reputation: 191
Can I write one Lambda Function to Handle Multiple REST API Requests. I have my data in Dynamo DB
Flow: API Gateway-->Lambda Function-->Dynamo DB Example:
Request1:GET Method-Need to pull data from Table1
/device/{device_id}/start/{start_date}/end/{end_date}/events
Request2:GET Method-Need to pull data from Table2
/device/{device_id}/start/{start_date}/end/{end_date}/event_count
Request3:POST Method-Need to put data from Table3
/device/{device_id}/start/{start_date}/end/{end_date}/fault_events
What is the best solution should I write 3 different lambda functions to handle 3 different requests or can I handle all the 3 requests in one BIG Lambda Function.
Upvotes: 15
Views: 17641
Reputation: 11472
If your motivation for wanting to group different APIs into the same lambda is complexity of the codebase, one option is to have a single codebase but with multiple endpoints defined for different lambda functions.
Upvotes: 1
Reputation: 1845
As many pointed out, it really depends by your use case. In general it should be fine to handle multiple endpoints in one Lambda function. One approach you can use, if you are using Node.JS, is wrapping an express web server inside a Lambda function. That way you will be able to both test the function locally (by running the web server) and use it in lambda (by wrapping the server inside the Lambda proxy). But again, it really depends on your use case, and as Jason mentioned you should also be careful to not split them too much
Upvotes: 0
Reputation: 8887
You have to find the right balance based on what your application/service does. In general I like to break things down into pretty small pieces, but you need to be careful you aren't going too far, and creating nano-services, which many consider an anti-pattern due to the maintenance overhead you end up creating.
Upvotes: 4
Reputation: 5056
Yes, you can have one Lambda function that handle more than one API. The question is why?
Doing this is considered (almost) an anti-pattern as you won't be able to scale independently the various scenario.
These are two slides from the link pasted above from Chris Munns talk at last re:invent and I strongly agree.
Upvotes: 16
Reputation: 221
While I don't know enough about your use case to recommend using 1 or multiple Lambda, I can explain one way of working with all queries inside one function.
You can pass in parameters from the lambda event, which come from the AWS API parameters and then use these to determine following logic. An example would look like this -
def lambda_handler(event, context):
try:
type_query = str(event['queryStringParameters']['type_query'])
if type_query == 'x':
...do the things
elif type_query == 'y':
...do the other things
elif type_query == 'z':
...do the 3rd thing
except:
return {
'body': "Invalid Params"
}
Hope this helps!
Upvotes: 6