Create an API Key and Usage Plan with SAM
Asked Answered
S

2

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.

Survivor answered 3/3, 2019 at 20:40 Comment(1)
Hi! Did you find any solution?Dailey
S
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
Survivor answered 23/11, 2019 at 18:54 Comment(1)
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 capitalizedTout
F
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
Filaria answered 30/8, 2022 at 22:17 Comment(1)
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.Cryometer

© 2022 - 2024 — McMap. All rights reserved.