API Gateway で基本的なリクエストの検証を設定する - Amazon API Gateway

API Gateway で基本的なリクエストの検証を設定する

このセクションでは、コンソール、AWS CLI、OpenAPI 定義を使用して API Gateway のリクエストの検証を設定する方法を示します。

API Gateway コンソールを使用してリクエストの検証を設定する

API Gateway コンソールで API リクエストの 3 つの検証から 1 つを選択して、リクエストを検証できます。

  • 本体の検証

  • クエリ文字列パラメータとヘッダーの検証

  • 本文、クエリ文字列パラメータ、ヘッダーの検証

上記のいずれかの検証を API メソッドに適用すると、API Gateway コンソールは検証を API の RequestValidators マップに追加します。

このチュートリアルに従うには、AWS CloudFormation テンプレートを使用して不完全な API Gateway API を作成します。この API には、GET メソッドと POST メソッドを持つ /validator リソースがあります。どちらのメソッドも http://petstore-demo-endpoint.execute-api.com/petstore/pets HTTP エンドポイントと統合されています。次の 2 種類のリクエストの検証を設定します。

  • GET メソッドでは、URL クエリ文字列パラメータに対するリクエストの検証を設定します。

  • POST メソッドでは、リクエスト本文に対するリクエストの検証を設定します。

これにより、特定の API コールのみを API にパススルーできます。

AWS CloudFormation のアプリケーション作成テンプレートをダウンロードして解凍します。このテンプレートを使用して不完全な API を作成します。残りのステップは API Gateway コンソールで完了します。

AWS CloudFormation スタックを作成するには
  1. https://console.aws.amazon.com/cloudformation で AWS CloudFormation コンソール を開きます。

  2. [スタックの作成] を選択し、[With new resources (standard) 新しいリソースを使用 (標準)] を選択します。

  3. [Specify template (テンプレートの指定)] で、[Upload a template file (テンプレートファイルのアップロード)] を選択します。

  4. ダウンロードしたテンプレートを選択します。

  5. [Next (次へ)] を選択します。

  6. [Stack name] (スタックの名前) で、request-validation-tutorial-console と入力し、[Next] (次へ) を選択します。

  7. [Configure stack options] (スタックオプションの設定) で、[Next] (次へ) を選択します。

  8. [Capabilities] (機能) で、AWS CloudFormation がアカウントに IAM リソースを作成できることを承認します。

  9. 送信 を選択します。

AWS CloudFormation は、テンプレートで指定されたリソースをプロビジョニングします。リソースのプロビジョニングには数分かかることがあります。AWS CloudFormation スタックのステータスが CREATE_COMPLETE の場合は、次のステップに進む準備ができています。

新しく作成した API を選択するには
  1. 新しく作成した request-validation-tutorial-console スタックを選択します。

  2. [リソース] をクリックします。

  3. [物理 ID] で API を選択します。このリンクを使用して API Gateway コンソールに移動します。

GET メソッドと POST メソッドを変更する前に、モデルを作成する必要があります。

モデルを作成するには
  1. 受信リクエストの本文でリクエストの検証を使用するには、モデルが必要です。モデルを作成するには、メインナビゲーションペインで [モデル] を選択します。

  2. [モデルの作成] を選択します。

  3. [名前] にPetStoreModelと入力します。

  4. [コンテンツタイプ] として、「application/json」と入力します。一致するコンテンツタイプが見つからない場合、リクエストの検証は実行されません。コンテンツタイプに関係なく同じモデルを使用するには、「$default」と入力します。

  5. [説明] に、モデルの説明として「My PetStore Model」と入力します。

  6. [モデルスキーマ] で、次のモデルをコードエディタに貼り付け、[作成] を選択します。

    { "type" : "object", "required" : [ "name", "price", "type" ], "properties" : { "id" : { "type" : "integer" }, "type" : { "type" : "string", "enum" : [ "dog", "cat", "fish" ] }, "name" : { "type" : "string" }, "price" : { "type" : "number", "minimum" : 25.0, "maximum" : 500.0 } } }

これらのモデルの詳細については、「データモデルを理解する」を参照してください。

GET メソッドのリクエスト検証を設定するには
  1. メインナビゲーションペインで [リソース][GET] メソッドの順に選択します。

  2. [メソッドリクエスト] タブの [メソッドリクエスト設定] で、[編集] を選択します。

  3. [リクエストの検証] で、[クエリ文字列パラメータおよびヘッダーを検証] を選択します。

  4. [URL クエリ文字列パラメータ] で、次の操作を行います。

    1. [クエリ文字列の追加] を選択します。

    2. [名前] にpetTypeと入力します。

    3. [必須] をオンにします。

    4. [キャッシュ] はオフのままにします。

  5. [Save] を選択します。

  6. [統合リクエスト] タブの [統合リクエストの設定] で、[編集] を選択します。

  7. [URL クエリ文字列パラメータ] で、次の操作を行います。

    1. [クエリ文字列の追加] を選択します。

    2. [名前] にpetTypeと入力します。

    3. [マッピング元] として「method.request.querystring.petType」と入力します。これは、petType をペットの種類にマッピングします。

      データマッピングの詳細については、データマッピングチュートリアルを参照してください。

    4. [キャッシュ] はオフのままにします。

  8. [Save] を選択します。

GET メソッドのリクエスト検証をテストするには
  1. [テスト] タブを選択します。タブを表示するには、右矢印ボタンを選択する必要がある場合があります。

  2. [クエリ文字列] に「petType=dog」と入力し、[テスト] を選択します。

  3. メソッドテストが 200 OK と犬のリストを返します。

    この出力データを変換する方法については、データマッピングチュートリアルを参照してください。

  4. petType=dog を削除して [テスト] を選択します。

  5. メソッドテストは、400 エラーを返し、次のエラーメッセージを表示します。

    { "message": "Missing required request parameters: [petType]" }
POST メソッドのリクエスト検証を設定するには
  1. メインナビゲーションペインで、[ステージ][POST] メソッドの順に選択します。

  2. [メソッドリクエスト] タブの [メソッドリクエスト設定] で、[編集] を選択します。

  3. [リクエストの検証][本文を検証] を選択します。

  4. [リクエスト本文] で、[モデルを追加] を選択します。

  5. [コンテンツタイプ] に「application/json」と入力し、[モデル][PetStoreModel] を選択します。

  6. [Save] を選択します。

POST メソッドのリクエスト検証をテストするには
  1. [テスト] タブを選択します。タブを表示するには、右矢印ボタンを選択する必要がある場合があります。

  2. [リクエスト本文] で、次の内容をコードエディタに貼り付けます。

    { "id": 2, "name": "Bella", "type": "dog", "price": 400 }

    [テスト] を選択します。

  3. メソッドテストは、200 OK と成功メッセージを返します。

  4. [リクエスト本文] で、次の内容をコードエディタに貼り付けます。

    { "id": 2, "name": "Bella", "type": "dog", "price": 4000 }

    [テスト] を選択します。

  5. メソッドテストは、400 エラーを返し、次のエラーメッセージを表示します。

    { "message": "Invalid request body" }

    テストログの一番下に、無効なリクエスト本文の理由が表示されます。この場合、ペットの価格はモデルに指定されている上限を超えていました。

AWS CloudFormation スタックを削除するには
  1. AWS CloudFormation コンソール (https://console.aws.amazon.com/cloudformation) を開きます。

  2. AWS CloudFormation スタックを選択します。

  3. [Delete] (削除) を選択し、選択を確定します。

次のステップ

AWS CLI を使用して基本的なリクエストの検証を設定する

AWS CLI を使用してリクエストの検証を設定するための検証を作成できます。このチュートリアルに従うには、AWS CloudFormation テンプレートを使用して不完全な API Gateway API を作成します。

注記

これはコンソールチュートリアルと同じ AWS CloudFormation テンプレートではありません。

事前に公開されている /validator リソースを使用して GET メソッドと POST メソッドを作成します。どちらのメソッドも http://petstore-demo-endpoint.execute-api.com/petstore/pets HTTP エンドポイントと統合されます。次の 2 つのリクエストの検証を設定します。

  • GET メソッドでは、params-only 検証を作成して URL クエリ文字列パラメータを検証します。

  • POST メソッドでは、body-only 検証を作成してリクエスト本文を検証します。

これにより、特定の API コールのみを API にパススルーできます。

AWS CloudFormation スタックを作成するには

AWS CloudFormation のアプリケーション作成テンプレートをダウンロードして解凍します。

次のチュートリアルを完了するには、AWS Command Line Interface (AWS CLI) バージョン 2 が必要です。

コマンドが長い場合は、エスケープ文字 (\) を使用してコマンドを複数行に分割します。

注記

Windows では、一般的に使用する Bash CLI コマンドの一部 (zip など) が、オペレーティングシステムの組み込みターミナルでサポートされていません。Ubuntu および Bash の Windows 統合バージョンを取得するには、Windows Subsystem for Linux をインストールします。このガイドの CLI コマンドの例では、Linux フォーマットを使用しています。Windows CLI を使用している場合、インライン JSON ドキュメントを含むコマンドを再フォーマットする必要があります。

  1. 次のコマンドを使用して AWS CloudFormation スタックを作成します。

    aws cloudformation create-stack --stack-name request-validation-tutorial-cli --template-body file://request-validation-tutorial-cli.zip --capabilities CAPABILITY_NAMED_IAM
  2. AWS CloudFormation は、テンプレートで指定されたリソースをプロビジョニングします。リソースのプロビジョニングには数分かかることがあります。次のコマンドを使用して AWS CloudFormation スタックのステータスを確認します。

    aws cloudformation describe-stacks --stack-name request-validation-tutorial-cli
  3. AWS CloudFormation スタックのステータスが StackStatus: "CREATE_COMPLETE" になったら、次のコマンドを使用して関連する出力値を取得し、以後のステップで使用します。

    aws cloudformation describe-stacks --stack-name request-validation-tutorial-cli --query "Stacks[*].Outputs[*].{OutputKey: OutputKey, OutputValue: OutputValue, Description: Description}"

    出力値は以下のとおりです。

    • ApiId。API の ID です。このチュートリアルの場合、API ID は abc123 です。

    • ResourceId。GET メソッドと POST メソッドが公開されている検証リソースの ID です。このチュートリアルの場合、リソース ID は efg456 です。

リクエストの検証を作成してモデルをインポートするには
  1. AWS CLI でリクエストの検証を行うには、検証が必要です。リクエストパラメータのみを検証する検証を作成するには、次のコマンドを使用します。

    aws apigateway create-request-validator --rest-api-id abc123 \ --no-validate-request-body \ --validate-request-parameters \ --name params-only

    params-only 検証の ID をメモしておきます。

  2. リクエスト本文のみを検証する検証を作成するには、次のコマンドを使用します。

    aws apigateway create-request-validator --rest-api-id abc123 \ --validate-request-body \ --no-validate-request-parameters \ --name body-only

    body-only 検証の ID をメモしておきます。

  3. 受信リクエストの本文でリクエストの検証を行うには、モデルが必要です。モデルをインポートするには、以下のコマンドを使用します。

    aws apigateway create-model --rest-api-id abc123 --name PetStoreModel --description 'My PetStore Model' --content-type 'application/json' --schema '{"type": "object", "required" : [ "name", "price", "type" ], "properties" : { "id" : {"type" : "integer"},"type" : {"type" : "string", "enum" : [ "dog", "cat", "fish" ]},"name" : { "type" : "string"},"price" : {"type" : "number","minimum" : 25.0, "maximum" : 500.0}}}}'

    一致するコンテンツタイプが見つからない場合、リクエストの検証は実行されません。コンテンツタイプに関係なく同じモデルを使用するには、キーとして $default を指定します。

GET メソッドと POST メソッドを作成するには
  1. 次のコマンドを使用して、GET HTTP メソッドを /validate リソースに追加します。このコマンドは、GET メソッドを作成して、params-only 検証を追加し、必要に応じてクエリ文字列 petType を設定します。

    aws apigateway put-method --rest-api-id abc123 \ --resource-id efg456 \ --http-method GET \ --authorization-type "NONE" \ --request-validator-id aaa111 \ --request-parameters "method.request.querystring.petType=true"

    次のコマンドを使用し、POST HTTP メソッドを /validate リソースに追加します。このコマンドは、POST メソッドを作成して、body-only 検証を追加し、モデルを本文専用の検証にアタッチします。

    aws apigateway put-method --rest-api-id abc123 \ --resource-id efg456 \ --http-method POST \ --authorization-type "NONE" \ --request-validator-id bbb222 \ --request-models 'application/json'=PetStoreModel
  2. 次のコマンドを使用して、GET /validate メソッドの 200 OK レスポンスを設定します。

    aws apigateway put-method-response --rest-api-id abc123 \ --resource-id efg456 \ --http-method GET \ --status-code 200

    次のコマンドを使用して、POST /validate メソッドの 200 OK レスポンスを設定します。

    aws apigateway put-method-response --rest-api-id abc123 \ --resource-id efg456 \ --http-method POST \ --status-code 200
  3. 次のコマンドを使用して、GET /validation メソッドの指定された HTTP エンドポイントを Integration に設定します。

    aws apigateway put-integration --rest-api-id abc123 \ --resource-id efg456 \ --http-method GET \ --type HTTP \ --integration-http-method GET \ --request-parameters '{"integration.request.querystring.type" : "method.request.querystring.petType"}' \ --uri 'http://petstore-demo-endpoint.execute-api.com/petstore/pets'

    次のコマンドを使用して、POST /validation メソッドの指定された HTTP エンドポイントを Integration に設定します。

    aws apigateway put-integration --rest-api-id abc123 \ --resource-id efg456 \ --http-method POST \ --type HTTP \ --integration-http-method GET \ --uri 'http://petstore-demo-endpoint.execute-api.com/petstore/pets'
  4. 次のコマンドを使用して、GET /validation メソッドの統合レスポンスを設定します。

    aws apigateway put-integration-response --rest-api-id abc123 \ --resource-id efg456\ --http-method GET \ --status-code 200 \ --selection-pattern ""

    次のコマンドを使用して、POST /validation メソッドの統合レスポンスを設定します。

    aws apigateway put-integration-response --rest-api-id abc123 \ --resource-id efg456 \ --http-method POST \ --status-code 200 \ --selection-pattern ""
API をテストするには
  1. クエリ文字列に対するリクエストの検証を実行する GET メソッドをテストするには、次のコマンドを使用します。

    aws apigateway test-invoke-method --rest-api-id abc123 \ --resource-id efg456 \ --http-method GET \ --path-with-query-string '/validate?petType=dog'

    結果として、200 OK と犬のリストが返されます。

  2. 次のコマンドを使用して、クエリ文字列 petType を含めずにテストします。

    aws apigateway test-invoke-method --rest-api-id abc123 \ --resource-id efg456 \ --http-method GET

    結果として 400 エラーが返されます。

  3. リクエスト本文に対するリクエストの検証を実行する POST メソッドをテストするには、次のコマンドを使用します。

    aws apigateway test-invoke-method --rest-api-id abc123 \ --resource-id efg456 \ --http-method POST \ --body '{"id": 1, "name": "bella", "type": "dog", "price" : 400 }'

    結果として、200 OK と成功メッセージが返されます。

  4. 次のコマンドを実行し、無効な本文を使用してテストします。

    aws apigateway test-invoke-method --rest-api-id abc123 \ --resource-id efg456 \ --http-method POST \ --body '{"id": 1, "name": "bella", "type": "dog", "price" : 1000 }'

    犬の価格がモデルで定義されている最大価格を超えているため、結果として 400 エラーが返されます。

AWS CloudFormation スタックを削除するには
  • AWS CloudFormation リソースを削除するには、次のコマンドを使用します。

    aws cloudformation delete-stack --stack-name request-validation-tutorial-cli

OpenAPI 定義を使用して基本的なリクエストの検証を設定する

API レベルでリクエストの検証を宣言するには、x-amazon-apigateway-request-validators オブジェクト マップ内の x-amazon-apigateway-request-validators.requestValidator オブジェクト オブジェクトのセットを指定して、リクエストのどの部分を検証するかを選択します。OpenAPI 定義の例では、次の 2 つの検証があります。

  • all 検証では、本文 (RequestBodyModel データモデルを使用) とパラメータの両方を検証します。

  • param-only 検証では、パラメータのみを検証します。

API のすべてのメソッドでリクエストの検証を有効にするには、OpenAPI 定義の API レベルで x-amazon-apigateway-request-validator プロパティ プロパティを指定します。OpenAPI 定義の例の場合、all 検証は、オーバーライドされない限り、すべての API メソッドで使用されます。モデルを使用して本文を検証する際、一致するコンテンツタイプが見つからない場合、リクエストの検証は実行されません。コンテンツタイプに関係なく同じモデルを使用するには、キーとして $default を指定します。

個々のメソッドでリクエストの検証を有効にするには、メソッドレベルで x-amazon-apigateway-request-validator プロパティを指定します。OpenAPI 定義の例の場合、param-only 検証は GET メソッドの all 検証を上書きします。

OpenAPI のサンプルを API Gateway にインポートするには、リージョン API を API Gateway にインポートする または エッジ最適化 API を API Gateway にインポートする に対する次の手順を参照してください。

OpenAPI 3.0
{ "openapi" : "3.0.1", "info" : { "title" : "ReqValidators Sample", "version" : "1.0.0" }, "servers" : [ { "url" : "/{basePath}", "variables" : { "basePath" : { "default" : "/v1" } } } ], "paths" : { "/validation" : { "get" : { "parameters" : [ { "name" : "q1", "in" : "query", "required" : true, "schema" : { "type" : "string" } } ], "responses" : { "200" : { "description" : "200 response", "headers" : { "test-method-response-header" : { "schema" : { "type" : "string" } } }, "content" : { "application/json" : { "schema" : { "$ref" : "#/components/schemas/ArrayOfError" } } } } }, "x-amazon-apigateway-request-validator" : "params-only", "x-amazon-apigateway-integration" : { "httpMethod" : "GET", "uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets", "responses" : { "default" : { "statusCode" : "400", "responseParameters" : { "method.response.header.test-method-response-header" : "'static value'" }, "responseTemplates" : { "application/xml" : "xml 400 response template", "application/json" : "json 400 response template" } }, "2\\d{2}" : { "statusCode" : "200" } }, "requestParameters" : { "integration.request.querystring.type" : "method.request.querystring.q1" }, "passthroughBehavior" : "when_no_match", "type" : "http" } }, "post" : { "parameters" : [ { "name" : "h1", "in" : "header", "required" : true, "schema" : { "type" : "string" } } ], "requestBody" : { "content" : { "application/json" : { "schema" : { "$ref" : "#/components/schemas/RequestBodyModel" } } }, "required" : true }, "responses" : { "200" : { "description" : "200 response", "headers" : { "test-method-response-header" : { "schema" : { "type" : "string" } } }, "content" : { "application/json" : { "schema" : { "$ref" : "#/components/schemas/ArrayOfError" } } } } }, "x-amazon-apigateway-request-validator" : "all", "x-amazon-apigateway-integration" : { "httpMethod" : "POST", "uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets", "responses" : { "default" : { "statusCode" : "400", "responseParameters" : { "method.response.header.test-method-response-header" : "'static value'" }, "responseTemplates" : { "application/xml" : "xml 400 response template", "application/json" : "json 400 response template" } }, "2\\d{2}" : { "statusCode" : "200" } }, "requestParameters" : { "integration.request.header.custom_h1" : "method.request.header.h1" }, "passthroughBehavior" : "when_no_match", "type" : "http" } } } }, "components" : { "schemas" : { "RequestBodyModel" : { "required" : [ "name", "price", "type" ], "type" : "object", "properties" : { "id" : { "type" : "integer" }, "type" : { "type" : "string", "enum" : [ "dog", "cat", "fish" ] }, "name" : { "type" : "string" }, "price" : { "maximum" : 500.0, "minimum" : 25.0, "type" : "number" } } }, "ArrayOfError" : { "type" : "array", "items" : { "$ref" : "#/components/schemas/Error" } }, "Error" : { "type" : "object" } } }, "x-amazon-apigateway-request-validators" : { "all" : { "validateRequestParameters" : true, "validateRequestBody" : true }, "params-only" : { "validateRequestParameters" : true, "validateRequestBody" : false } } }
OpenAPI 2.0
{ "swagger" : "2.0", "info" : { "version" : "1.0.0", "title" : "ReqValidators Sample" }, "basePath" : "/v1", "schemes" : [ "https" ], "paths" : { "/validation" : { "get" : { "produces" : [ "application/json", "application/xml" ], "parameters" : [ { "name" : "q1", "in" : "query", "required" : true, "type" : "string" } ], "responses" : { "200" : { "description" : "200 response", "schema" : { "$ref" : "#/definitions/ArrayOfError" }, "headers" : { "test-method-response-header" : { "type" : "string" } } } }, "x-amazon-apigateway-request-validator" : "params-only", "x-amazon-apigateway-integration" : { "httpMethod" : "GET", "uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets", "responses" : { "default" : { "statusCode" : "400", "responseParameters" : { "method.response.header.test-method-response-header" : "'static value'" }, "responseTemplates" : { "application/xml" : "xml 400 response template", "application/json" : "json 400 response template" } }, "2\\d{2}" : { "statusCode" : "200" } }, "requestParameters" : { "integration.request.querystring.type" : "method.request.querystring.q1" }, "passthroughBehavior" : "when_no_match", "type" : "http" } }, "post" : { "consumes" : [ "application/json" ], "produces" : [ "application/json", "application/xml" ], "parameters" : [ { "name" : "h1", "in" : "header", "required" : true, "type" : "string" }, { "in" : "body", "name" : "RequestBodyModel", "required" : true, "schema" : { "$ref" : "#/definitions/RequestBodyModel" } } ], "responses" : { "200" : { "description" : "200 response", "schema" : { "$ref" : "#/definitions/ArrayOfError" }, "headers" : { "test-method-response-header" : { "type" : "string" } } } }, "x-amazon-apigateway-request-validator" : "all", "x-amazon-apigateway-integration" : { "httpMethod" : "POST", "uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets", "responses" : { "default" : { "statusCode" : "400", "responseParameters" : { "method.response.header.test-method-response-header" : "'static value'" }, "responseTemplates" : { "application/xml" : "xml 400 response template", "application/json" : "json 400 response template" } }, "2\\d{2}" : { "statusCode" : "200" } }, "requestParameters" : { "integration.request.header.custom_h1" : "method.request.header.h1" }, "passthroughBehavior" : "when_no_match", "type" : "http" } } } }, "definitions" : { "RequestBodyModel" : { "type" : "object", "required" : [ "name", "price", "type" ], "properties" : { "id" : { "type" : "integer" }, "type" : { "type" : "string", "enum" : [ "dog", "cat", "fish" ] }, "name" : { "type" : "string" }, "price" : { "type" : "number", "minimum" : 25.0, "maximum" : 500.0 } } }, "ArrayOfError" : { "type" : "array", "items" : { "$ref" : "#/definitions/Error" } }, "Error" : { "type" : "object" } }, "x-amazon-apigateway-request-validators" : { "all" : { "validateRequestParameters" : true, "validateRequestBody" : true }, "params-only" : { "validateRequestParameters" : true, "validateRequestBody" : false } } }