Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get the API endpoint's URL when it's created within the Events property of Cloudformation's Lambda definition

I'm creating a Lambda function via CloudFormation (AWS' SAM: Serverless Application Model) and have defined an API endpoint via the Lambda-function's Events property.

  ...
  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      Description: Do amazing things
      CodeUri: my_function/
      Events:
        Trigger:
          Type: Api
          Properties:
            Path: /p1/{v1}
            Method: post
      Handler: app.run
  ...

I'd now like to use the URL of the endpoint that's been created in another part of the CloudFormation YAML file. I've tried to use the SAM documentation for Lambda but the only return values have to do with the Function's ARN and resource name.

Specifically, thought I think unrelated to the exact question, I want to use the API endpoint as a subscription for an SNS Topic.

¿How can I get the URL of the API Endpoint?

like image 905
Matt Avatar asked Oct 14 '25 14:10

Matt


2 Answers

you can directly reference the RestApi resource like this.

Resources:
  apiGateway:
    Type: AWS::ApiGateway::RestApi
    Properties:
      Name: !Sub ${AWS::StackName}-my-api
      Description: my-api-edge


Outputs:
  apiGatewayInvokeURL:
    Value: !Sub "https://${apiGateway}.execute-api.${AWS::Region}.amazonaws.com/${apiGatewayStageName}"

  lambdaArn:
    Value: !GetAtt "lambdaFunction.Arn"
like image 109
Arun Kamalanathan Avatar answered Oct 17 '25 03:10

Arun Kamalanathan


I think I found the answer across a couple of places.

This Stack Overflow post shows that there is an implicit reference created that you can use as follows

!Ref ServerlessRestApi

This was supported in practice, by a SAM Respository App

And then I re-read, more closely, the SAM API documentation which shows the RestApiId Property. It says

...Typically, this is set to reference an AWS::Serverless::Api resource defined in this template. If not defined, a default AWS::Serverless::Api resource is created..."

So it looks like you can reference it as !Ref ServerlessRestApi without any modification to the YAML in the original question, or you could add the following Property, RestApiId: MyAPI, and reference it as !Ref MyAPI.

However, to get the actual URL, it looks like you have to use a Fn::Sub to glue together a couple of parts. Pahud Hsieh does it in his SAM Repository app above

Outputs:
  APIUrlPrefix:
    Value:
      Fn::Sub:
      - https://${ServerlessRestApi}.execute-api.${Region}.amazonaws.com/Prod/incomingwebhooks/
      - Region:
          Ref: AWS::Region
        ServerlessRestApi:
          Ref: ServerlessRestApi
...
like image 45
Matt Avatar answered Oct 17 '25 04:10

Matt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!