背景と目的
APIGatewayとLambdaを一緒に使う場合、設定項目がたくさん用意されていて自由度は高いのだが、いろいろありすぎてどんな時に何をすればいいかわからなくなる。公式ドキュメントを読まずともある程度のことが分かるようにメモしておく。
前提
APIGateway
設定
バイナリメディアタイプ
バイナリとして受け入れるContent-Typeを設定する。たとえば、application/octet-streamやimage/jpegなど。設定しておかないと、Unsupported Media Typeというレスポンスが帰ってきてしまう。ここで設定したら、統合リクエスト>マッピングテンプレートの$input.bodyにbase64エンコードされた文字列が入るようになる。
リソース
メソッドリクエスト
編集中
統合リクエスト
HTTPヘッダー
マッピングテンプレート
リクエストのパススルー
- そのままだと、リクエストボディがJSONであることを期待して、jsonパースしてLambdaの引数event.body-jsonに入れる。JSONパースできない場合、Lambdaに到達する前に怒られる。
- Content-Typeがtext/plainの場合、以下のようにすれば文字列を入れられる。
"body-json": "$input.body"
統合レスポンス
編集中
メソッドレスポンス
編集中
Lambda
引数event
マッピングテンプレートの生成 = リクエストのパススルーのとき
{ "body-json": "{ボディ}", "params": { "path": { "pathParameter": "value", : }, "querystring": { "queryParameter": "value", : }, "header": { "Accept": "*/*", "Accept-Encoding": "gzip, deflate, br", "Cache-Control": "no-cache", "CloudFront-Forwarded-Proto": "https", "CloudFront-Is-Desktop-Viewer": "true", "CloudFront-Is-Mobile-Viewer": "false", "CloudFront-Is-SmartTV-Viewer": "false", "CloudFront-Is-Tablet-Viewer": "false", "CloudFront-Viewer-Country": "US", "Content-Type": "{Content-Type}", "Host": "{api-id}.execute-api.ap-northeast-1.amazonaws.com", "User-Agent": "PostmanRuntime/7.29.0", "Via": "1.1 22512dca1de1fae848b2509fed0309aa.cloudfront.net (CloudFront)", "X-Amz-Cf-Id": "FXfKr5sbNKhgGGfyTwehKew20UNqXsoPp7xyDL-y8TqgAkwCnWr94w==", "X-Amzn-Trace-Id": "Root=1-6215f7c0-12c8260b2b11d6fe7f74d914", "X-Forwarded-For": "54.86.50.139, 130.176.137.78", "X-Forwarded-Port": "443", "X-Forwarded-Proto": "https" } }, "stage-variables": { "type": "object", "description": "ステージ変数" }, "context": { "account-id": "", "api-id": "{api-id}", "api-key": "", "authorizer-principal-id": "", "caller": "", "cognito-authentication-provider": "", "cognito-authentication-type": "", "cognito-identity-id": "", "cognito-identity-pool-id": "", "http-method": "POST", "stage": "{デプロイ先ステージ}", "source-ip": "{アクセス元IPアドレス}", "user": "", "user-agent": "********************", "user-arn": "", "request-id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "resource-id": "{リソースID}", "resource-path": "{リソースパス}" } }
event.params.header
event.body-json
- APIGateway>統合リクエスト>マッピングテンプレートで、リクエストのパススルーを選んだ場合、リクエストボディがそのまま入るが、JSONである必要がある。
- JSON以外の場合は、APIGateway>統合リクエスト>マッピングテンプレートを参照。
event.stage-variables
APIGatewayのステージ変数で定義した値が入る。
{ "stage-variables": { "abc": "value", : } }