DEV Community

Discussion on: Configuring Serverless Framework for multiple stages

 
upupkenchoong profile image
Ken Choong

I using CDK. so I share some of the snippet, then you will get the idea, not sure about Serverless yaml, never used serverless framework.

First define a API uri like this in a CDK contrust

 `   
 class ApiIntegration(core.Construct):
   @property
   def integration(self):
       return self._integration

   def __init__(self, scope: core.Construct, id: str, function: _lambda,  ** kwargs):
      super().__init__(scope, id, **kwargs)

      api_uri = (  # this API uri
          f"arn:aws:apigateway:"
          f"{core.Aws.REGION}"
          f":lambda:path/2015-03-31/functions/"
          f"{function.function_arn}"
          f":"
          f"${{stageVariables.lambdaAlias}}"
          f"/invocations"
       )

      self._integration = apigateway.Integration(
          type=apigateway.IntegrationType.AWS_PROXY,
          integration_http_method="POST", ## here is always POST. 
          uri=api_uri
       )`
Enter fullscreen mode Exit fullscreen mode

The api_uri will make a endpoint to your lambda. The idea is make a URL for your lambda, then APIgateway will call to this URL for integration.

For the URI I define above, you can look at this example (The URI part in Open 3.0) :
docs.aws.amazon.com/apigateway/lat...

And this one, read at the 6th item
docs.aws.amazon.com/apigateway/lat...

If you using CDK, then you integrate your Apigateway like this:

          api = apigateway.LambdaRestApi(
                      self, "YourApiName",
                       #.. all other stuff 
                  )

          # The contruct define above. 
          my_api_integration = ApiIntegration(self, "MyApiIntegration", function="MyFunctionLambda") 

          # pass the constuct to the method 
         my_api_method = api.add_method(
           "POST", integration=my_api_integration.integration)
Enter fullscreen mode Exit fullscreen mode

So I think in your serverless.yaml, you need to define the API uri like I done above. So the process look like this

User make request -> hit your apigateway endpoint -> apigateway hit your lambda using the "API uri"

Why api_uri?

This is the only way you can pass the {stageVariable.lambdaAlias} value to the lambda. When you get this value inside the lambda, then you can do other crazy shit depends to this lambdaAlias value.

So you get the idea. And remember, grant the apigateway endpoint permission to invoke your lambda.

Thread Thread
 
upupkenchoong profile image
Ken Choong

Recently I answer a question about this topic in SO. If interested you can look it here. Cheers

Thread Thread
 
upupkenchoong profile image
Ken Choong

I have create a whole tutorial series in here using CDK about this topic as well, feel free to take a look