ConnectionID またはカスタムトークンを Amazon API Gateway WebSocket API のヘッダーとして VPC リンク統合に渡したいと考えています。これを行うにはどうすればよいですか?
簡単な説明
WebSocket API の場合、バックエンドからコールバックレスポンスを送信するには ConnectionID が必要です。デフォルトでは、WebSocket API は ConnectionID を VPC リンク統合に渡しません。
解決方法
Amazon API Gateway コンソールと AWS CLI を使用する
注意: AWS コマンドラインインターフェイス (AWS CLI) コマンドの実行中にエラーが発生した場合は、AWS CLI の最新バージョンを使用していることを確認してください。
1. 指示に従って REST API VPC リンクを作成し、Network Load Balancer に関連付けます。
2. 指示に従って WebSocket API 統合をセットアップし、VPC リンクのプライベート統合エンドポイントを作成します。
3. 統合 ID を取得するには、以下のような AWS CLI コマンド get-integrations を実行します。
aws apigatewayv2 get-integrations --api-id <api-id>
4. integration.json という名前の JSON ファイルを次の形式で作成して保存します。
{
"ApiId": "<api-id>",
"IntegrationId": "<integration id retrieved from previous step>",
"RequestParameters": {
"integration.request.header.ConnectionId": "context.connectionId", //passing context variable connectionId as ConnectionId header to backend
"integration.request.header.<header-key>": "route.request.body.<parameter>", // passing a request body parameter as header to backend
"integration.request.querystring.<querysting-key>": "'static value'" //passing static value as querystring to backend
}
}
注意:ステップ 5 に進む前に、スラッシュ「//」で示されているコメントを削除してください。
5. 統合を更新するには、以下のような AWS CLI コマンド update-integration を実行します。
aws apigatewayv2 update-integration --cli-input-json file://integration.json
6. これらの変更を適用するには、指示に従って
REST API をデプロイしてください。
AWS CloudFormation を使用する
CloudFormation を使用して Amazon API Gateway を管理している場合、AWS::ApiGatewayV2::Integration リソースを使用して、次のようなリクエストパラメータを設定できます。
Integration:
Type: AWS::ApiGatewayV2::Integration
Properties:
ApiId: !Ref websocket
ConnectionId: !Ref <VPC-Link-connection-id>
ConnectionType: VPC_LINK
IntegrationMethod: <HTTP method to backend >
IntegrationType: <HTTP_PROXY/HTTP>
IntegrationUri: "<endpoint-url>"
RequestParameters:
"integration.request.header.connectionId": "context.connectionId" #passing context variable 'connectionId' as ConnectionId header to backend
"integration.request.header.<header-key>": "route.request.body.<parameter>" #passing a request body parameter as header to backend
"integration.request.querystring.<querystring-key>": "'static value'" #passing static value as querystring to backend
データマッピングを使用して、ルートリクエストからのデータを VPC リンクバックエンド統合にマッピングできます。詳細については、「ルートリクエストデータを統合リクエストパラメータにマッピングする」を参照してください。
関連情報
WebSocket API 統合のセットアップ