8

I am learning AWS SAM and having trouble finding information on how to create an API Key and usage plan through the SAM template.

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31

Resources:
  GetFamilyByIdFunction:
    Type: AWS::Serverless::Function
    Properties:
      Runtime: nodejs8.10
      Handler: get-family-by-id.handler
      CodeUri: get-family-by-id/
      Timeout: 300
      Events:
        GetFamilyByIdApi:
          Type: Api
          Properties:
            Path: "/family/{id}"
            Method: get

I would like to create an API key and associate it with a usage plan for the 'GetFamilyByIdApi' specified above. Any help would be appreciated.

Shivam
  • 3,514
  • 2
  • 13
  • 27
badgerduke
  • 255
  • 4
  • 12

2 Answers2

11

After a bit of digging I figured it out. This solution is when you want to define the value of the api key yourself as opposed to letting API Gateway generate a value. I assume a variation exists for that. Note that 'HvgnApi' refers to my Swagger definition (Type: AWS::Serverless::Api). Enjoy!

  ApiKey: 
    Type: AWS::ApiGateway::ApiKey
    Properties: 
      Name: !Join ["", [{"Ref": "AWS::StackName"}, "-apikey"]]
      Description: "CloudFormation API Key V1"
      Enabled: true
      GenerateDistinctId: false
      Value: abcdefg123456
      StageKeys:
        - RestApiId: !Ref HvgnApi
          StageName: prod

  ApiUsagePlan:
    Type: "AWS::ApiGateway::UsagePlan"
    Properties:
      ApiStages: 
        - ApiId: !Ref HvgnApi
          Stage: prod     
      Description: !Join [" ", [{"Ref": "AWS::StackName"}, "usage plan"]]
      Quota:
        Limit: 1000
        Period: MONTH
      UsagePlanName: !Join ["", [{"Ref": "AWS::StackName"}, "-usage-plan"]]

  ApiUsagePlanKey:
    Type: "AWS::ApiGateway::UsagePlanKey"
    DependsOn: 
      - HvgnApi
    Properties:
      KeyId: !Ref ApiKey
      KeyType: API_KEY
      UsagePlanId: !Ref ApiUsagePlan
badgerduke
  • 255
  • 4
  • 12
  • For me, providing `prod` under `APIKey/Properties/StageKeys/StageName` wouldn't work, I had to do `StageName: !Ref HvgnApiProdStage` instead (not sure if that or `...prodStage` instead, mine was capitalized – Tobias Feil Jul 29 '20 at 14:09
1

This is much easier to do with the latest version of SAM:

  MyAPI:
    Type: AWS::Serverless::Api
    Properties:
      StageName: dev
      Auth:
        ApiKeyRequired: true  # for all methods
        UsagePlan:
          CreateUsagePlan: PER_API
          Description: Usage plan for this API
Greg
  • 751
  • 1
  • 10
  • 11
  • Worked for me, thank you. I guess if we are using SAM template, we should stick to using the Serverless approach rather than the Cloudformation approach. – Hyder B. Mar 03 '23 at 16:09