Generating an AWS Lambda API endpoint
A handy trick to reference an AWS Lambda API endpoint is to use serverless-pseudo-parameters and Serverless variables to create the endpoint URL that can be passed to lambda function through an environment variable.
Consider the two lambda functions defined in this serverless.yml:
- get-index: Returns an HTML page
- get-stores: Return a list of stores
provider:
  name: aws
  runtime: nodejs12.x
functions:
  get-index:
    handler: functions/get-index.handler
    events:
      - http:
          path: /
          method: get
    environment:
      stores_api: https://#{ApiGatewayRestApi}.execute-api.#{AWS::Region}.amazonaws.com/${self:provider.stage}/stores
  get-stores:
    handler: functions/get-stores.handler
    events:
      - http:
          path: /stores
          method: get
plugins:
  - serverless-pseudo-parametersThe get-index function needs to make a call to the get-stores function to do some logic, like querying a database.
Use pseudo-parameters and Serverless variables to generate the API endpoint URL of the
get-storesAPI endpoint.Store this URL as an environment variable for the
get-indexfunction:
https://#{ApiGatewayRestApi}.execute-api.#{AWS::Region}.amazonaws.com/${self:provider.stage}/storesCloudFormation Pseudo Parameters and Serverless Variables
Pseudo parameters are parameters that are predefined by AWS CloudFormation that return AWS resource IDs.
The available CloudFormation Pseudo Parameters are:
- AWS::AccountId
- AWS::NotificationARNs
- AWS::NoValue
- AWS::Partition
- AWS::Region
- AWS::StackId
- AWS::StackName
- AWS::URLSuffix
#{ApiGatewayRestApi} Resource
Serverless generates a cloudformation-template-update-stack.json CloudFormation template that from our serverless.yml.
"Resources": {
  "ApiGatewayRestApi": {      "Type": "AWS::ApiGateway::RestApi",      "Properties": {
        "Name": "dev-api-service",
        "EndpointConfiguration": {
          "Types": [
            "EDGE"
          ]
        },
        "Policy": ""
      }
  }
  ## Other resources...
}This CloudFormation template specifies ApiGatewayRestApi as an API Gateway REST API resource that contains a collection API Gateway resources.
We can use #{ApiGatewayRestApi} to reference the ApiGatewayRestApi resource from our CloudFormation template.
#{AWS::Region}
#{AWS::Region} references the CloudFormation pseudo parameter to retrieve the AWS Region which our get-stores AWS Lambda resource is being created in.
${self:provider.stage}
${self:provider.stage} self-reference the provider stage variable property in our serverless.yml.