Multiple Lambdas, Single API Gateway

Multiple Lambdas, Single API Gateway

Building an app using Serverless components is about separating responsabilities. Your logic will mostely end up living in separate Lambda Functions for reasons I will not get into in this post. However, by default, every Serverless Lambda Function deploys with its own API Gateway endpoint, and the result is a different URL for every Lambda. Not ideal.

So I went in a hunt for a solution and I found this 2016 post in the Serverless forum suggesting the usage of simple regex matching on cloudfront's path patterns. Luckily, today Serverless Framework has integrated a much easier solution using API ID and API Resource ID. And in this post, I'll show you how to do it in two simple parts

Part 1: API Gateway

You might want to use CloudFormation to build your API Gateway, but for the sake of simplicity in this post, let's head to the console (Console --> Services --> APIGateway --> Create) and create a REST API.

No alt text provided for this image

Once created, I want you to take a note of the API's ID and the API's root resource ID

The ID next to the API name is the API ID "a06lq49vh1" and the one next to Resources is the the root resource ID "rwvkav6f3a"

No alt text provided for this image

Part 2: Serverless YML

Now, say we are working on two Lambda Functions:

  • user-details
  • event-details

Your Serverless.yml files are probably looking somehow like the ones bellow:

No alt text provided for this image

Now all you have to do, is add two attributes under "Provider" and reference the API and API Resource IDs. Your files should look like this.

No alt text provided for this image

Deploy both your Lambdas, head back to the console, and you will find both Lambdas being served from behind the single point we created earlier. And that's all there is to it.

No alt text provided for this image


Kai Ng

Software Engineer

1y

excellent solution, i am looking for this

Like
Reply

To view or add a comment, sign in

More articles by ⚡️ iLyas Bakouch

Insights from the community

Others also viewed

Explore topics