Need to configure serverless resource output to get api gateway api id

Viewed 3171

I have a serverless project that is creating an API Gateway API amongst other things. One of the functions in the project needs to generate a URL for an API endpoint.

My plan is to get the API ID using a resource output in serverless.yml then create the URL and pass it through to the lambda function as an env parameter.

My problem/question is how to get the API ID as a cloud formation output in serverless.yml?

I've tried:

resources:
  Outputs:
    RESTApiId:
      Description: The id of the API created in the API gateway
      Value:
        Ref: name-of-api

but this give the error:

The CloudFormation template is invalid: Unresolved resource dependencies [name-of-api] in the Outputs block of the template
3 Answers

You can write something like this in the serverless.yml file:

provider:
  region: ${opt:region, 'eu-west-1'}
  stage: ${opt:stage, 'dev'}
  environment:
    REST_API_URL:
      Fn::Join:
        - ""
        - - "https://"
          - Ref: "ApiGatewayRestApi"
          - ".execute-api."
          - ${self:provider.region}
          - Ref: "AWS::URLSuffix"
          - "/"
          - ${self:provider.stage}"

Now you can call serverless with optional commandline options --stage and/or --region to override the defaults defined above, e.g:

serverless deploy --stage production --region us-east-1

In your code you can then use the environment variable REST_API_URL

node.js:

const restApiUrl = process.env.REST_API_URL;

python:

import os
rest_api_url = os.environ['REST_API_URL']

Java:

String restApiUrl = System.getenv("REST_API_URL");

Unfortunately, the documentation doesn't mention it:

resources:
  Outputs:
    apiGatewayHttpApiId:
      Value:
        Ref: HttpApi
      Export:
        Name: YourAppHttpApiId
Related