

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# API Gateway 中用於 WebSocket API 的資料轉換
<a name="websocket-api-data-transformations"></a>

在 API Gateway 中，WebSocket API 的方法請求可視後端的需求，從對應的整合請求承載擷取不同格式的承載。同樣地，後端可能會依照前端的預期，傳回與方法回應承載不同的整合回應承載。

API Gateway 可讓您使用映射範本轉換，將承載從方法請求映射至對應的整合請求，以及從整合回應映射至對應的方法回應。您會建立映射範本並指定範本選擇表達式，以決定要使用哪個範本來執行必要的資料轉換。

您可以使用資料映射，將 [路由請求](api-gateway-basic-concept.md#apigateway-definition-route-request) 中的資料映射至後端整合。如需進一步了解，請參閱[設定 API Gateway 中 WebSocket API 的資料映射](websocket-api-data-mapping.md)。

## 對應範本和模型
<a name="apigateway-websocket-api-mapping-templats-and-models"></a>

 *對應範本*是以 [Velocity 範本語言 (VTL)](https://velocity.apache.org/engine/devel/vtl-reference.html) 表示，並使用 [JSONPath 表達式](https://goessner.net/articles/JsonPath/)套用至承載的指令碼。如需 API Gateway 對應範本的詳細資訊，請參閱 [API Gateway 中 REST API 的映射範本轉換](models-mappings.md)。

根據 [JSON 結構描述草稿第 4 版](https://datatracker.ietf.org/doc/html/draft-zyp-json-schema-04)，承載可以有一個*資料模型*。您不需要定義任何模型，即可建立對應範本。不過，模型可協助您建立範本，因為 API Gateway 會根據提供的模型產生範本藍圖。如需 API Gateway 模型的詳細資訊，請參閱 [REST API 的資料模型](models-mappings-models.md)。

## 範本選擇表達式
<a name="apigateway-websocket-api-template-selection-expressions"></a>

若要使用對應範本轉換承載，您可以[整合請求](apigateway-websocket-api-integration-requests.md)或[整合回應](apigateway-websocket-api-integration-responses.md)中指定 WebSocket API 範本選取運算式。此表達式的評估結果會判定輸入或輸出範本 (如有)，輸入範本可將請求本文轉換為整合請求本文，輸出範本則可將整合回應本文轉換為路由回應本文。

`Integration.TemplateSelectionExpression` 支援 `${request.body.jsonPath}` 和靜態值。

`IntegrationResponse.TemplateSelectionExpression` 支援 `${request.body.jsonPath}`、`${integration.response.statuscode}`、`${integration.response.header.headerName}`、`${integration.response.multivalueheader.headerName}` 和靜態值。

## 整合回應選擇表達式
<a name="apigateway-websocket-api-integration-response-selection-expressions"></a>

[設定 WebSocket API 的整合回應](apigateway-websocket-api-integration-responses.md)時，您可選擇指定整合回應選擇表達式。此運算式會判定整合回傳時應選取的 `[https://docs.aws.amazon.com/apigatewayv2/latest/api-reference/apis-apiid-integrations-integrationid-integrationresponses-integrationresponseid.html](https://docs.aws.amazon.com/apigatewayv2/latest/api-reference/apis-apiid-integrations-integrationid-integrationresponses-integrationresponseid.html)`。此表達式的值目前正受 API Gateway 限制，規則如下。請注意，此表達式只與*非代理整合*有關；代理整合只要將回應承載回傳給發起人即可，無須建模或修改。

此表達式與上述選擇表達式不同，目前支援*模式比對*格式。此表達式應以斜線包裝。

目前固定的值視 `[https://docs.aws.amazon.com/apigatewayv2/latest/api-reference/apis-apiid-integrations-integrationid.html#apis-apiid-integrations-integrationid-prop-integration-integrationtype](https://docs.aws.amazon.com/apigatewayv2/latest/api-reference/apis-apiid-integrations-integrationid.html#apis-apiid-integrations-integrationid-prop-integration-integrationtype)` 而異：
+ 若是 Lambda 型整合，此值為 `$integration.response.body.errorMessage`。
+ 若是 `HTTP` 及 `MOCK` 整合，此值為 `$integration.response.statuscode`。
+ 若是 `HTTP_PROXY` 及 `AWS_PROXY`，將不會運用此表達式，因為您請求將承載傳遞給發起人。