DEV Community

Franz Wong
Franz Wong

Posted on

Support API versioning with Lambda function and API gateway

When you introduce breaking change to your API and you want to support existing clients at the same time, usually you need to provide multiple API versions. It is very easy to setup API versioning for lambda function and API gateway.

Setup lambda function

Let’s say we have a lambda function called my-hello-world. This is how it looks like. (This is the sample code from AWS)

exports.handler = async (event) => {
    const response = {
        statusCode: 200,
        body: JSON.stringify('Hello from Lambda!'),
    };
    return response;
};

Before we update our source code, we need to publish a version and create an alias first.

aws lambda publish-version --function-name my-hello-world

We have created our version 1. Next step is to create alias version1.

aws lambda create-alias \
  --function-name my-hello-world \
  --name version1 \
  --function-version 1

We have created our alias version1, so we can now update our source code. Make sure the version is selected as $Latest.

Alt Text

Here is the source code. Only message is updated.

exports.handler = async (event) => {
    const response = {
        statusCode: 200,
        body: JSON.stringify('Hello from Franz!'),
    };
    return response;
};

Press Save button to save.

Alt Text

We can now publish new version 2 and create alias version2.

aws lambda publish-version --function-name my-hello-world
aws lambda create-alias \
  --function-name my-hello-world \
  --name version2 \
  --function-version 2

Setup API gateway

Let’s create a new API. I called it my-hello-world-api.

Alt Text

Under /, create 2 resources v1 and v2.

Alt Text

Under v1 and v2, create GET method. Make sure you put my-hello-world:version1 for v1’s GET and my-hello-world:version2 for v2’s GET.

Alt Text

AWS will help you to create the required permission. Just press OK.

Alt Text

It is how it looks like.

Alt Text

We have completed the setup. Now we can test our API.

I tried v1 and v2. You can see the messages in the responses are different.

Alt Text

Alt Text

Top comments (2)

Collapse
 
devparkk profile image
Dev Prakash

Thanks for this article. It was helpful .

Collapse
 
yoavmonto profile image
yoavmonto • Edited

I think there's a short part missing, at the end.
Correct me if I'm wrong, but everytime a stage variable is changed, the policy should be updated.