Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

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

couzie
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
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  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
ユーザーは見つかりませんでした