Using Amazon API Gateway stage variables - Amazon API Gateway

Using Amazon API Gateway stage variables

You can use API Gateway stage variables to access the HTTP and Lambda backends for different API deployment stages. You can also use stage variables to pass stage-specific configuration metadata into an HTTP backend as a query parameter and into a Lambda function as a payload that is generated in an input mapping template.

Prerequisites

You must create two stages with a url stage variable set to two different HTTP endpoints: a function stage variable assigned to two different Lambda functions, and a stageName stage variable containing stage-specific metadata.

Access an HTTP endpoint through an API with a stage variable

  1. In the Stages navigation pane, choose beta. Under Stage details, choose the copy icon to copy your API's invoke URL, and then enter your API's invoke URL in a web browser. This starts the beta stage GET request on the root resource of the API.

    Note

    The Invoke URL link points to the root resource of the API in its beta stage. Entering the URL in a web browser calls the beta stage GET method on the root resource. If methods are defined on child resources and not on the root resource itself, entering the URL in a web browser returns a {"message":"Missing Authentication Token"} error response. In this case, you must append the name of a specific child resource to the Invoke URL link.

  2. The response you get from the beta stage GET request is shown next. You can also verify the result by using a browser to navigate to http://httpbin.org/get. This value was assigned to the url variable in the beta stage. The two responses are identical.

  3. In the Stages navigation pane, choose the prod stage. Under Stage details, choose the copy icon to copy your API's invoke URL, and then enter your API's invoke URL in a web browser. This starts the prod stage GET request on the root resource of the API.

  4. The response you get from the prod stage GET request is shown next. You can verify the result by using a browser to navigate to http://petstore-demo-endpoint.execute-api.com/petstore/pets. This value was assigned to the url variable in the prod stage. The two responses are identical.

Pass stage-specific metadata to an HTTP backend through a stage variable in a query parameter expression

This procedure describes how to use a stage variable value in a query parameter expression to pass stage-specific metadata into an HTTP backend. We will use the stageName stage variable declared in Setting stage variables using the Amazon API Gateway console.

  1. In the Resource navigation pane, choose the GET method.

    To add a query string parameter to the method's URL, choose the Method request tab, and then in the Method request settings section, choose Edit.

  2. Choose URL query string parameters and do the following:

    1. Choose Add query string.

    2. For Name, enter stageName.

    3. Keep Required and Caching turned off.

  3. Choose Save.

  4. Choose the Integration request tab, and then in the Integration request settings section, choose Edit.

  5. For Endpoint URL, append ?stageName=${stageVariables.stageName} to the previously defined URL value, so the entire Endpoint URL is http://${stageVariables.url}?stageName=${stageVariables.stageName}.

  6. Choose Deploy API and select the beta stage.

  7. In the main navigation pane, choose Stages. In the Stages navigation pane, choose beta. Under Stage details, choose the copy icon to copy your API's invoke URL, and then enter your API's invoke URL in a web browser.

    Note

    We use the beta stage here because the HTTP endpoint (as specified by the url variable "http://httpbin.org/get") accepts query parameter expressions and returns them as the args object in its response.

  8. You get the following response. Notice that beta, assigned to the stageName stage variable, is passed in the backend as the stageName argument.

    
                  Response from the API's GET method using a proxy for an HTTP endpoint with the
                    url stage variable in the beta stage

Call a Lambda function through an API with a stage variable

This procedure describes how to use a stage variable to call a Lambda function as a backend of your API. We will use the function stage variable declared earlier. For more information, see Setting stage variables using the Amazon API Gateway console.

  1. Create a Lambda function named HelloWorld using the default Node.js runtime. The code must contain the following:

    export const handler = function(event, context, callback) { if (event.stageName) callback(null, 'Hello, World! I\'m calling from the ' + event.stageName + ' stage.'); else callback(null, 'Hello, World! I\'m not sure where I\'m calling from...'); };

    For more information on how to create a Lambda function, see Getting started with the REST API console.

  2. In the Resources pane, select Create resource, and then do the following:

    1. For Resource path, select /.

    2. For Resource name, enter lambdav1.

    3. Choose Create resource.

  3. Choose the /lambdav1 resource, and then choose Create method.

    Then, do the following:

    1. For Method type, select GET.

    2. For Integration type, select Lambda function.

    3. Keep Lambda proxy integration turned off.

    4. For Lambda function, enter ${stageVariables.function}.

      
                        Create a GET method integrated with a Lambda function as specified by the
                          function stage variable.
      Tip

      When prompted with the Add permission command, copy the AWS CLI command. Run the command on each Lambda function that will be assigned to the function stage variable. For example, if the $stageVariables.function value is HelloWorld, run the following AWS CLI command:

      aws lambda add-permission --function-name arn:aws:lambda:us-east-1:account-id:function:HelloWorld --source-arn arn:aws:execute-api:us-east-1:account-id:api-id/*/GET/lambdav1 --principal apigateway.amazonaws.com --statement-id statement-id-guid --action lambda:InvokeFunction

      Failing to do so results in a 500 Internal Server Error response when invoking the method. Replace ${stageVariables.function} with the Lambda function name that is assigned to the stage variable.

      
                          Run the AWS CLI command to add permission to the Lambda function to be invoked by method you
                            just created.
    5. Choose Create method.

  4. Deploy the API to both the prod and beta stages.

  5. In the main navigation pane, choose Stages. In the Stages navigation pane, choose beta. Under Stage details, choose the copy icon to copy your API's invoke URL, and then enter your API's invoke URL in a web browser. Append /lambdav1 to the URL before you press enter.

    You get the following response.

    "Hello, World! I'm not sure where I'm calling from..."

Pass stage-specific metadata to a Lambda function through a stage variable

This procedure describes how to use a stage variable to pass stage-specific configuration metadata into a Lambda function. You create a POST method and an input mapping template to generate payload using the stageName stage variable you declared earlier.

  1. Choose the /lambdav1 resource, and then choose Create method.

    Then, do the following:

    1. For Method type, select POST.

    2. For Integration type, select Lambda function.

    3. Keep Lambda proxy integration turned off.

    4. For Lambda function, enter ${stageVariables.function}.

    5. When prompted with the Add permission command, copy the AWS CLI command. Run the command on each Lambda function that will be assigned to the function stage variable.

    6. Choose Create method.

  2. Choose the Integration request tab, and then in the Integration request settings section, choose Edit.

  3. Choose Mapping templates, and then choose Add mapping template.

  4. For Content type, enter application/json.

  5. For Template body, enter the following template:

    #set($inputRoot = $input.path('$')) { "stageName" : "$stageVariables.stageName" }
    Note

    In a mapping template, a stage variable must be referenced within quotes (as in "$stageVariables.stageName" or "${stageVariables.stageName}"). In other places, it must be referenced without quotes (as in ${stageVariables.function}).

  6. Choose Save.

  7. Deploy the API to both the beta and prod stages.

  8. To use a REST API client to pass stage-specific metadata, do the following:

    1. In the Stages navigation pane, choose beta. Under Stage details, choose the copy icon to copy your API's invoke URL, and then enter your API's invoke URL in the input field of a REST API client. Append /lambdav1 before you submit your request.

      You get the following response.

      "Hello, World! I'm calling from the beta stage."
    2. In the Stages navigation pane, choose prod. Under Stage details, choose the copy icon to copy your API's invoke URL, and then enter your API's invoke URL in the input field of a REST API client. Append /lambdav1 before you submit your request.

      You get the following response.

      "Hello, World! I'm calling from the prod stage."
  9. To use the Test feature to pass stage-specific metadata, do the following:

    1. In the Resources navigation pane, choose the Test tab. You might need to choose the right arrow button to show the tab.

    2. For function, enter HelloWorld.

    3. For stageName, enter beta.

    4. Choose Test. You do not need to add a body to your POST request.

      You get the following response.

      "Hello, World! I'm calling from the beta stage."
    5. You can repeat the previous steps to test the Prod stage. For stageName, enter Prod.

      You get the following response.

      "Hello, World! I'm calling from the prod stage."