Following Best Practices for Versions, Aliases, and Stages
Introduction
You have previously created the following resources:
- Lambda function (ItemsFunction)
- Lambda Versions ($LATEST and 1)
- Lambda Aliases (dev and prod)
- API Gateway Stages (dev and prod)
- API Gateway Resources (ItemsList and Item)
Both the API endpoints are attached to the same Lambda function and they currently use its version 1. This configuration is not very robust and doesn't allow you to update your Lambda function and see the updates in your dev environment.
The recommended best practice is connecting your API Gateway stages to the corresponding Lambda Alias, so that you can easily manage new functionalities, testing, bug fixing, rollbacks, etc. You can achieve this setup by creating a new stage variable and then use this variable as a Lambda alias in your API Gateway backend configuration. Stage Variables can be used to configure the request integration of your resources so that you don't have to modify them every time you want to re-deploy your API.
Instructions
1. In the dev Stage Editor, click on the Stage Variables tab and click Add Stage Variable:
2. Enter the following values before clicking the checkmark icon to save the variable:
- Name: lambdaAlias
- Value: dev
3. Select the prod stage and create a lambdaAlias stage variable with the value of prod.
Now you can update the API Gateway Resources' configuration to use the stage variable.
4. For both the /items GET method and the /items/{ID} GET method, modify the Integration Request Lambda Function to ItemsFunction:${stageVariables.lambdaAlias}. Click OK to the Add Permission to Lambda Function modals that popup.
Note: Since the Lambda alias is now dynamically configured in the API Gateway Stage, you would normally have to manually grant API Gateway the permission to invoke the dev and prod Lambda function aliases. API Gateway warns you about this:
You can grant the permission with the AWS CLI, as recommended by the modal. For the Lab, you don't need to grant any additional permission because you already granted API Gateway access to the dev and prod aliases that are referenced by the stage variables.
5. Re-deploy your dev and prod stages before proceeding (Actions > Deploy API).
To test the API, you can no longer use the Test button in the Method Execution diagram because the method now depends on being executed in the context of a specific stage.
6. Click on Stages > prod and copy the Invoke URL:
7. Paste the Invoke URL into a new browser tab and append /items to the end before navigating to the URL:
The list of items is returned, confirming that the stage variable for the prod stage is configured correctly.
Summary
In this Lab Step, you configured stage variables to reference the Lambda function used for the API Gateway backend integration. Now that API Gateway is correctly configured you are free to update the Lambda function code and play with its alias mapping without coming back to API Gateway.