

# 针对 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`，不会使用此表达式，因为您请求将负载传递给调用方。