API Gateway でのデータ変換の設定 - Amazon API Gateway

API Gateway でのデータ変換の設定

このセクションでは、コンソールと AWS CLI を使用して統合リクエストおよびレスポンスを変換するマッピングテンプレートを設定する方法を示します。

API Gateway コンソールを使用してデータ変換を設定する

このチュートリアルでは、.zip ファイル (data-transformation-tutorial-console.zip) を使用して不完全な API と DynamoDB テーブルを作成します。この不完全な API には、GET メソッドと POST メソッドを持つ /pets リソースがあります。

  • GET メソッドは http://petstore-demo-endpoint.execute-api.com/petstore/pets HTTP エンドポイントからデータを取得します。出力データは、PetStore マッピングテンプレート のマッピングテンプレートに従って変換されます。

  • POST メソッドを使用すると、ユーザーはマッピングテンプレートを使用して Amazon DynamoDB テーブルにペット情報を POST できます。

AWS CloudFormation のアプリケーション作成テンプレートをダウンロードして解凍します。このテンプレートを使用して、ペット情報と不完全な API を投稿するための DynamoDB テーブルを作成します。残りのステップは 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] (スタックの名前) で、data-transformation-tutorial-console と入力し、[Next] (次へ) を選択します。

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

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

  9. 送信 を選択します。

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

GET 統合レスポンスをテストするには
  1. data-transformation-tutorial-console の AWS CloudFormation スタックの [リソース] タブで、API の物理 ID を選択します。

  2. メインナビゲーションペインで [リソース][GET] メソッドの順に選択します。

  3. [テスト] タブを選択します。タブを表示するには、右矢印ボタンを選択する必要がある場合があります。

    テストの出力には、次の内容が表示されます。

    [ { "id": 1, "type": "dog", "price": 249.99 }, { "id": 2, "type": "cat", "price": 124.99 }, { "id": 3, "type": "fish", "price": 0.99 } ]

    この出力を PetStore マッピングテンプレート のマッピングテンプレートに従って変換します。

GET 統合レスポンスを変換するには
  1. [統合レスポンス] タブを選択します。

    現在、マッピングテンプレートは定義されていないため、統合レスポンスは変換されません。

  2. [デフォルト - レスポンス][編集] を選択します。

  3. [マッピングテンプレート] を選択し、次の操作を行います。

    1. [マッピングテンプレートの追加] を選択します。

    2. [コンテンツタイプ] に、「application/json」と入力します。

    3. [テンプレート本文] で次のように入力します。

      #set($inputRoot = $input.path('$')) [ #foreach($elem in $inputRoot) { "description" : "Item $elem.id is a $elem.type.", "askingPrice" : $elem.price }#if($foreach.hasNext),#end #end ]

    [Save] を選択します。

GET 統合レスポンスをテストするには
  • [テスト] タブ、[テスト] の順に選択します。

    テストの出力に、変換されたレスポンスが表示されます。

    [ { "description" : "Item 1 is a dog.", "askingPrice" : 249.99 }, { "description" : "Item 2 is a cat.", "askingPrice" : 124.99 }, { "description" : "Item 3 is a fish.", "askingPrice" : 0.99 } ]
POST メソッドからの入力データを変換するには
  1. [POST] メソッドを選択します。

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

    AWS CloudFormation テンプレートでは、いくつかの統合リクエストフィールドが入力されています。

    • 統合タイプは AWS のサービスです。

    • AWS のサービスは DynamoDB です。

    • HTTP メソッドは POST です。

    • アクションは PutItem です。

    • API Gateway が DynamoDB テーブルに項目を入力できるようにする実行ロールは data-transformation-tutorial-console-APIGatewayRole です。AWS CloudFormation は、API Gateway が DynamoDB とやり取りするための最小限のアクセス許可を持つように、このロールを作成済みです。

    DynamoDB テーブルの名前は未指定です。次の手順に従って名前を指定します。

  3. [リクエスト本文のパススルー] で、[なし] を選択します。

    つまり、API はマッピングテンプレートを持たない Content-Type のデータを拒否します。

  4. [マッピングテンプレート] を選択します。

  5. [コンテンツタイプ]application/json に設定されます。つまり、application/json 以外のコンテンツタイプは API によって拒否されます。統合パススルーの動作の詳細については、「統合パススルーの動作」を参照してください。

  6. テキストエディタに次のコードを入力します。

    { "TableName":"data-transformation-tutorial-console-ddb", "Item": { "id": { "N": $input.json("$.id") }, "type": { "S": $input.json("$.type") }, "price": { "N": $input.json("$.price") } } }

    このテンプレートでは、テーブルを data-transformation-tutorial-console-ddb として指定し、項目を idtypeprice として設定します。項目は、POST メソッドの本体から取得されます。データモデルを使用してマッピングテンプレートを作成することもできます。詳細については、「API Gateway でリクエストの検証を使用する」を参照してください。

  7. [保存] ボタンを選択し、マッピングテンプレートを保存します。

POST メソッドからメソッドと統合レスポンスを追加するには

AWS CloudFormation は、空白のメソッドと統合レスポンスを作成済みです。このレスポンスを編集して詳細情報を入力します。レスポンスの編集方法の詳細については、「Amazon API Gateway API リクエストおよびレスポンスデータマッピングリファレンス」を参照してください。

  1. [統合レスポンス] タブの [デフォルト - レスポンス] で、[編集] を選択します。

  2. [マッピングテンプレート][マッピングテンプレートの追加] の順に選択します。

  3. [コンテンツタイプ] に「application/json」と入力します。

  4. コードエディタで、次の出力マッピングテンプレートを入力し、出力メッセージを送信します。

    { "message" : "Your response was recorded at $context.requestTime" }

    コンテキスト変数の詳細については、「データモデル、オーソライザー、マッピングテンプレート、および CloudWatch アクセスログ記録用の $context 変数」を参照してください。

  5. [保存] ボタンを選択し、マッピングテンプレートを保存します。

POST メソッドをテストする

[テスト] タブを選択します。タブを表示するには、右矢印ボタンを選択する必要がある場合があります。

  1. リクエスト本文に、次の例を入力します。

    { "id": "4", "type" : "dog", "price": "321" }
  2. [テスト] を選択します。

    出力に成功メッセージが表示されるはずです。

    DynamoDB コンソール (https://console.aws.amazon.com/dynamodb/) を開いて、サンプル項目がテーブルにあることを確認できます。

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

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

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

AWS CLI を使用してデータ変換を設定する

このチュートリアルでは、.zip ファイル (data-transformation-tutorial-cli.zip} を使用して不完全な API と DynamoDB テーブルを作成します。この不完全な API には、http://petstore-demo-endpoint.execute-api.com/petstore/pets HTTP エンドポイントと統合された GET メソッドを持つ /pets リソースがあります。POST メソッドを作成して DynamoDB テーブルに接続し、マッピングテンプレートを使用して DynamoDB テーブルにデータを入力します。

  • 出力データは、PetStore マッピングテンプレート のマッピングテンプレートに従って変換します。

  • POST メソッドを作成し、ユーザーがマッピングテンプレートを使用して Amazon DynamoDB テーブルにペット情報を POST できるようにします。

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

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

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

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

    • ApiRole。API Gateway が DynamoDB テーブルに項目を配置できるようにするロールの名前です。このチュートリアルの場合、ロール名は data-transformation-tutorial-cli-APIGatewayRole-ABCDEFG です。

    • DDBTableName。DynamoDB テーブルの名前です。このチュートリアルの場合、インスタンス名は data-transformation-tutorial-cli-ddb です。

    • ResourceId。GET メソッドと POST メソッドを公開するペットリソースの ID です。このチュートリアルの場合、リソース ID は efg456 です。

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

データ変換の前に GET メソッドをテストするには
  • 次のコマンドを使用して、GET メソッドをテストします。

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

    テストの出力には、次の内容が表示されます。

    [ { "id": 1, "type": "dog", "price": 249.99 }, { "id": 2, "type": "cat", "price": 124.99 }, { "id": 3, "type": "fish", "price": 0.99 } ]

    この出力を PetStore マッピングテンプレート のマッピングテンプレートに従って変換します。

GET 統合レスポンスを変換するには
  • 次のコマンドを使用して、GET メソッドの統合レスポンスを更新します。rest-api-id と resource-id を実際の値に置き換えます。

    次のコマンドを使用して統合レスポンスを作成します。

    aws apigateway put-integration-response --rest-api-id abc123 \ --resource-id efg456 \ --http-method GET \ --status-code 200 \ --selection-pattern "" \ --response-templates '{"application/json": "#set($inputRoot = $input.path(\"$\"))\n[\n#foreach($elem in $inputRoot)\n {\n \"description\": \"Item $elem.id is a $elem.type\",\n \"askingPrice\": \"$elem.price\"\n }#if($foreach.hasNext),#end\n\n#end\n]"}'
GET メソッドをテストするには
  • 次のコマンドを使用して GET メソッドをテストします。

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

    テストの出力に、変換されたレスポンスが表示されます。

    [ { "description" : "Item 1 is a dog.", "askingPrice" : 249.99 }, { "description" : "Item 2 is a cat.", "askingPrice" : 124.99 }, { "description" : "Item 3 is a fish.", "askingPrice" : 0.99 } ]
POST メソッドを作成するには
  1. 次のコマンドを使用して、/pets リソースで新しいメソッドを作成します。

    aws apigateway put-method --rest-api-id abc123 \ --resource-id efg456 \ --http-method POST \ --authorization-type "NONE" \

    このメソッドを使用すると、AWS CloudFormation スタックで作成した DynamoDB テーブルにペット情報を送信できます。

  2. 次のコマンドを使用して、POST メソッドで AWS のサービス統合を作成します。

    aws apigateway put-integration --rest-api-id abc123 \ --resource-id efg456 \ --http-method POST \ --type AWS \ --integration-http-method POST \ --uri "arn:aws:apigateway:us-east-2:dynamodb:action/PutItem" \ --credentials arn:aws:iam::111122223333:role/data-transformation-tutorial-cli-APIGatewayRole-ABCDEFG \ --request-templates '{"application/json":"{\"TableName\":\"data-transformation-tutorial-cli-ddb\",\"Item\":{\"id\":{\"N\":$input.json(\"$.id\")},\"type\":{\"S\":$input.json(\"$.type\")},\"price\":{\"N\":$input.json(\"$.price\")} }}"}'
  3. 次のコマンドを使用して、POST メソッドの呼び出しが成功した場合のメソッドレスポンスを作成します。

    aws apigateway put-method-response --rest-api-id abc123 \ --resource-id efg456 \ --http-method POST \ --status-code 200
  4. 次のコマンドを使用して、POST メソッドの呼び出しが成功した場合の統合レスポンスを作成します。

    aws apigateway put-integration-response --rest-api-id abc123 \ --resource-id efg456 \ --http-method POST \ --status-code 200 \ --selection-pattern "" \ --response-templates '{"application/json": "{\"message\": \"Your response was recorded at $context.requestTime\"}"}'
POST メソッドをテストするには
  • 次のコマンドを使用して、POST メソッドをテストします。

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

    出力に、成功のメッセージが表示されます。

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

    aws cloudformation delete-stack --stack-name data-transformation-tutorial-cli

完成したデータ変換の AWS CloudFormation テンプレート

次の例は、完成した AWS CloudFormation テンプレートです。これにより、API と、GET メソッドと POST メソッドを持つ /pets リソースを作成します。

  • GET メソッドは、http://petstore-demo-endpoint.execute-api.com/petstore/pets HTTP エンドポイントからデータを取得します。出力データは、PetStore マッピングテンプレート のマッピングテンプレートに従って変換されます。

  • POST メソッドを使用すると、ユーザーはマッピングテンプレートを使用して DynamoDB テーブルにペット情報を POST できます。

AWSTemplateFormatVersion: 2010-09-09 Description: A completed Amazon API Gateway REST API that uses non-proxy integration to POST to an Amazon DynamoDB table and non-proxy integration to GET transformed pets data. Parameters: StageName: Type: String Default: v1 Description: Name of API stage. Resources: DynamoDBTable: Type: 'AWS::DynamoDB::Table' Properties: TableName: !Sub data-transformation-tutorial-complete AttributeDefinitions: - AttributeName: id AttributeType: N KeySchema: - AttributeName: id KeyType: HASH ProvisionedThroughput: ReadCapacityUnits: 5 WriteCapacityUnits: 5 APIGatewayRole: Type: 'AWS::IAM::Role' Properties: AssumeRolePolicyDocument: Version: 2012-10-17 Statement: - Action: - 'sts:AssumeRole' Effect: Allow Principal: Service: - apigateway.amazonaws.com Policies: - PolicyName: APIGatewayDynamoDBPolicy PolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Action: - 'dynamodb:PutItem' Resource: !GetAtt DynamoDBTable.Arn Api: Type: 'AWS::ApiGateway::RestApi' Properties: Name: data-transformation-complete-api ApiKeySourceType: HEADER PetsResource: Type: 'AWS::ApiGateway::Resource' Properties: RestApiId: !Ref Api ParentId: !GetAtt Api.RootResourceId PathPart: 'pets' PetsMethodGet: Type: 'AWS::ApiGateway::Method' Properties: RestApiId: !Ref Api ResourceId: !Ref PetsResource HttpMethod: GET ApiKeyRequired: false AuthorizationType: NONE Integration: Type: HTTP Credentials: !GetAtt APIGatewayRole.Arn IntegrationHttpMethod: GET Uri: http://petstore-demo-endpoint.execute-api.com/petstore/pets/ PassthroughBehavior: WHEN_NO_TEMPLATES IntegrationResponses: - StatusCode: '200' ResponseTemplates: application/json: "#set($inputRoot = $input.path(\"$\"))\n[\n#foreach($elem in $inputRoot)\n {\n \"description\": \"Item $elem.id is a $elem.type\",\n \"askingPrice\": \"$elem.price\"\n }#if($foreach.hasNext),#end\n\n#end\n]" MethodResponses: - StatusCode: '200' PetsMethodPost: Type: 'AWS::ApiGateway::Method' Properties: RestApiId: !Ref Api ResourceId: !Ref PetsResource HttpMethod: POST ApiKeyRequired: false AuthorizationType: NONE Integration: Type: AWS Credentials: !GetAtt APIGatewayRole.Arn IntegrationHttpMethod: POST Uri: arn:aws:apigateway:us-west-1:dynamodb:action/PutItem PassthroughBehavior: NEVER RequestTemplates: application/json: "{\"TableName\":\"data-transformation-tutorial-complete\",\"Item\":{\"id\":{\"N\":$input.json(\"$.id\")},\"type\":{\"S\":$input.json(\"$.type\")},\"price\":{\"N\":$input.json(\"$.price\")} }}" IntegrationResponses: - StatusCode: 200 ResponseTemplates: application/json: "{\"message\": \"Your response was recorded at $context.requestTime\"}" MethodResponses: - StatusCode: '200' ApiDeployment: Type: 'AWS::ApiGateway::Deployment' DependsOn: - PetsMethodGet Properties: RestApiId: !Ref Api StageName: !Sub '${StageName}' Outputs: ApiId: Description: API ID for CLI commands Value: !Ref Api ResourceId: Description: /pets resource ID for CLI commands Value: !Ref PetsResource ApiRole: Description: Role ID to allow API Gateway to put and scan items in DynamoDB table Value: !Ref APIGatewayRole DDBTableName: Description: DynamoDB table name Value: !Ref DynamoDBTable

次のステップ

より複雑なマッピングテンプレートを試すには、以下の例を参照してください。