vbgd
vbgd

Reputation: 1977

How do you create a new version of an API using serverless framework?

I have a simple API developed using serverless framework that is deployed in production. The serverless.yaml is similar to this one:

service: example

provider:
    name: aws

plugins:
    - serverless-plugin-scripts
    - serverless-offline

functions:
    package:
        runtime: nodejs14.x
        handler: build/index.handler
        events:
            - httpApi: "POST /test"

The API will change in the next version and I want to offer backward compatibility to my clients. I want to create a /v1/test route in API Gateway that will point to the new implementation of the function and I want /test to remain the same.

Is there a way to do this using serverless framework?

Upvotes: 1

Views: 650

Answers (1)

Aaron Stuyvenberg
Aaron Stuyvenberg

Reputation: 3777

There are a few things you can do.

  1. Create a new function entirely, with a new route. This option is simplest to implement, but your setup may not allow you to create a new function for some reason (CloudFormation stack limits, or other non-functional reasons).
functions:
    # V0 package function
    package:
        runtime: nodejs14.x
        handler: build/index.handler
        events:
            - httpApi: "POST /test"
    # V1 package function
    packageV1:
        runtime: nodejs14.x
        handler: build/index.handlerv1
        events:
            - httpApi: "POST v1/test"
  1. Use the same function, but append a new path. Then inside your function code inspect the event payload to determine which path was called and use that to modify the response or functionality to adhere to either API spec.
    package:
        runtime: nodejs14.x
        handler: build/index.handler # Both routes share the function, you'll need to modify logic to implement both v0/v1 spec
        events:
            - httpApi: "POST /test" # V0 route
            - httpApi: "POST v1/test" # V1 route

Both of these are good for temporary migrations where you'll eventually deprecate the old API. If you need both in perpetuity, you could also migrate your v0 API into a new stack (or similarly create a new stack for the v1 API).

Lambda is priced per-invocation, not per-function. So with that in mind, I'd suggest creating a totally distinct function, that will make it easier to deprecate and delete when the time comes.

Upvotes: 1

Related Questions