LoginSignup
23
17

More than 5 years have passed since last update.

SAM で API Gateway に API Key を設定する

Posted at

この記事は、AWS Serverless Application Model (AWS SAM) で API Gateway の API Key を設定した際の記録です。

はじめに

  • SAM では、API仕様を定義した Swagger を使用することで、API Gateway のリソースを作成できます

参考

API Gateway の API に API Key を指定する

1.Swagger の securityDefinitionsapiKey を定義する

swagger.yml
securityDefinitions:

  SampleApiKey:
    type: apiKey
    name: x-api-key
    in: header

2.API Key を要求する path に対して securityapiKey を指定する

swagger.yml

paths:
  /pet:
    post:
      summary: "Add a new pet to the store"
      operationId: "addPet"
      security:
        - SampleApiKey: []

      (以下省略)

3.SAM の template で AWS::Serverless::Api に加えて以下のリソースを作成する
- AWS::ApiGateway::ApiKey
- AWS::ApiGateway::UsagePlan
- AWS::ApiGateway::UsagePlanKey

template.yml

  SampleApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: Prod
      DefinitionUri: swagger.yml

  SampleApiKey:
    Type: AWS::ApiGateway::ApiKey
    DependsOn: SampleApi
    Properties: 
      Name: sample-api-key
      Enabled: true
      StageKeys: 
        - RestApiId: 
            Ref: SampleApi
          StageName: Prod

  SampleApiUsagePlan:
    Type: AWS::ApiGateway::UsagePlan
    DependsOn: SampleApi
    Properties:
      ApiStages:
      - ApiId: !Ref SampleApi
        Stage: !Ref SampleApiProdStage
        # AWS::Serverless::Api のリソース名 + AWS::Serverless::Api の 'StageName' + Stage 
      Throttle:
        BurstLimit: 200
        RateLimit: 100
      UsagePlanName: sample-api-usage-plan

  SampleApiUsagePlanKey:
    Type: AWS::ApiGateway::UsagePlanKey
    DependsOn:
      - SampleApiKey
      - SampleApiUsagePlan
    Properties : 
      KeyId: !Ref SampleApiKey
      KeyType: API_KEY
      UsagePlanId: !Ref SampleApiUsagePlan

23
17
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23
17