Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
14
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

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

この記事は、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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
14
Help us understand the problem. What are the problem?