如何將 ConnectionId 或自訂字符作為 Amazon API Gateway WebSocket API 的標題傳送至 VPC 連結整合?

2 分的閱讀內容
0

我想將 ConnectionId 或自訂字符傳送至 VPC 連結整合作為我的 Amazon API Gateway WebSocket API 的標題。該如何進行?

簡短描述

對於 WebSocket API,需要ConnectionId 才能從後端傳送回呼回應。根據預設,WebSocket API 不會將 ConnectionId 傳送至 VPC 連結整合。

解析度

使用 Amazon API Gateway 主控台和 AWS CLI

**注意:**如果您在執行 AWS Command Line Interface (AWS CLI) 命令時收到錯誤,請確保您使用的是最新的 AWS CLI 版本

1.    依照指示建立 REST API VPC 連結,並將其與您的 Network Load Balancer 建立關聯。

2.    依照指示設定 WebSocket API 整合,並建立 VPC 連結私有整合端點

3.    若要擷取整合 ID,請執行類似下列內容的 AWS CLI 命令取得整合

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 命令更新整合

aws apigatewayv2 update-integration --cli-input-json file://integration.json

6.    若要套用這些變更,請依照指示 部署 REST API

使用 AWS CloudFormation

如果您使用 CloudFormation 管理 Amazon API Gateway,可以使用 AWS:: ApiGatewayV2:: 整合資源來設定類似下列內容的請求參數:

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 整合

AWS 官方
AWS 官方已更新 1 年前