[Fixed] How do i get/reference api gateway restapi id in serverless.yml?

With this document, I can steam cloudwatch logs to a lambda fucntion

functions:
  myCloudWatchLog:
    handler: myCloudWatchLog.handler
    events:
      - cloudwatchLog: '/aws/lambda/hello'

In this sample, the log group name is hard coded.

But my question is, how do i get current api gateway rest-api id dynamically? Because my lambda function will work on the api gateway log group, which has the name format as:

API-Gateway-Execution-Logs_{rest-api-id}/{stage_name}

Seems the resource I am looking for is AWS::ApiGateway::RestApi

http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html

Fn::GetAtt

Fn::GetAtt returns a value for a specified attribute of this type. This section lists the available attribute and a sample return value.

RootResourceId
The root resource ID for a RestApi resource, such as a0bc123d4e.

So it should be

  RestapiId:
    Fn::GetAtt:
    - ApiGatewayRestApi
    - RootResourceId

Let me test it.

1 Like

@bill a little late but checkout http://www.goingserverless.com/blog/api-gateway-url where I write about using { "Ref" : "ApiGatewayRestApi" } to set an environment variable to the API GW URL.

3 Likes

Thanks, @buggy

That will be easier, use { "Ref" : "ApiGatewayRestApi" } directly.

For anyone else who finds this, note there’s some confusion here about API gateway resources.

  • The RestApiId is the id of the API resource itself, which is returned by a Ref of the implied ApiGatewayRestApi resource that Serverless creates under the hood.

  • The RootResourceId is the id of the REST resource (not to be confused with a CloudFormation resource!) at the root of the API’s path (i.e. “/”). If you are hanging methods or subresources off of root, you’ll need to provide this as the parent resource id. It is available as an attribute of the API resource.

So, for example to define a resource at the path “/mythings”, which needs both the api id and the root resource id, your CF template would look like

ThingsResource:
  Type: AWS::ApiGateway::Resource
  Properties:
    RestApiId:
      Ref: ApiGatewayRestApi
    ParentId:
      Fn::GetAtt:
        - ApiGatewayRestApi
        - RootResourceId
    PathPart: mythings

Hope this helps clarify.

1 Like