kenichiro246’s blog

主にC#での仕事をしてます。今はAWSに関わり始めました。

Swagger で AWS の API Gateway を初めて構築してみた

タイトルのとおり構築していきます。
yamlファイルの内容は掘り下げず、まずは API Gateway が作れるところまでとします。

事前準備

まずは Swagger を使うために、VS Code で「Swagger Viewer」をインストールしておきます。

参考

Swagger Spec ファイルの作成

  1. yaml ファイルの作成
    以下の内容が記述された yaml ファイルを作成します。
    バックエンドで PetStore ウェブサイトの HTTP エンドポイントと統合された GET / メソッドのみを公開し、200 OK レスポンスを返すという仕様です。
    AWSには PetStore ウェブサイトというAPIを提供している架空のサイトがありますので、これを使います。
{
  "swagger": "2.0",
  "info": {
    "title": "Simple PetStore (OpenAPI)"
  },
  "schemes": [
    "https"
  ],
  "paths": {
    "/pets": {
      "get": {
        "responses": {
          "200": {
            "description": "200 response"
          }
        },
        "x-amazon-apigateway-integration": {
          "responses": {
            "default": {
              "statusCode": "200"
            }
          },
          "uri": "http://petstore-demo-endpoint.execute-api.com/petstore/pets",
          "passthroughBehavior": "when_no_match",
          "httpMethod": "GET",
          "type": "http"
        }
      }
    },
    "/pets/{petId}": {
      "get": {
        "parameters": [
          {
            "name": "petId",
            "in": "path",
            "required": true,
            "type": "string"
          }
        ],
        "responses": {
          "200": {
            "description": "200 response"
          }
        },
        "x-amazon-apigateway-integration": {
          "responses": {
            "default": {
              "statusCode": "200"
            }
          },
          "requestParameters": {
            "integration.request.path.id": "method.request.path.petId"
          },
          "uri": "http://petstore-demo-endpoint.execute-api.com/petstore/pets/{id}",
          "passthroughBehavior": "when_no_match",
          "httpMethod": "GET",
          "type": "http"
        }
      }
    }
  }
}
  1. VS Code で「Shift + Alt + p」を押して Swagger Viewer を開く
    こんな感じでAPIの定義が見れます。

API Gateway の作成

  1. API Gateway コンソールを開く
  2. API を作成」をクリックする
  3. REST API セクションの「インポート」をクリックする
  4. 以下のとおり入力し、「インポート」をクリックする
項目
プロトコルを選択する REST
新しい API の作成 Swagger あるいは Open API 3 からインポート
Swagger あるいは Open API 3 からインポート 前述に記述した Swagger Spec ファイルを選択
エンドポイントタイプ リージョン

API Gateway の検証

Swaggerで作成した API Gateway をデプロイし、「URL の呼び出し」から以下の全量検索やID検索のように表示されれば成功です。

全量検索

  1. ブラウザで以下のURLを開く
    http://petstore-demo-endpoint.execute-api.com/petstore/pets
  2. 以下の内容が表示されたらOK
[
  {
    "id": 1,
    "type": "dog",
    "price": 249.99
  },
  {
    "id": 2,
    "type": "cat",
    "price": 124.99
  },
  {
    "id": 3,
    "type": "fish",
    "price": 0.99
  }
]

IDでの検索

  1. ブラウザで以下のURLを開く
    http://petstore-demo-endpoint.execute-api.com/petstore/pets/2
  2. 以下の内容が表示されたらOK
{
  "id": 2,
  "type": "cat",
  "price": 124.99
}

yaml ファイルさえあれば、API Gateway にインポートするだけで作成できちゃいますね。簡単。