

# API Gateway 的用于数据转换的变量
<a name="api-gateway-mapping-template-reference"></a>

创建参数映射时，可以使用上下文变量作为数据来源。创建映射模板转换时，可以在用 [Velocity Template Language (VTL)](https://velocity.apache.org/engine/devel/vtl-reference.html) 编写的脚本中使用上下文变量、输入和 util 变量。有关使用这些参考变量的映射模板的示例，请参阅[使用变量来映射 API Gateway 的模板转换的示例](api-gateway-mapping-variable-examples.md)。

有关访问日志记录的参考变量的列表，请参阅 [API Gateway 的访问日志记录的变量](api-gateway-variables-for-access-logging.md)。

## 数据转换的上下文变量
<a name="context-variable-reference"></a>

可以使用以下区分大小写的 `$context` 变量来进行数据转换。


| 参数 | 说明 | 
| --- | --- | 
| \$1context.accountId |  API 拥有者的 AWS 账户 ID。  | 
| \$1context.apiId |  API Gateway 分配给您的 API 的标识符。  | 
| \$1context.authorizer.claims.property |  成功对方法调用方进行身份验证后从 Amazon Cognito 用户池返回的声明的属性。有关更多信息，请参阅 [使用 Amazon Cognito 用户池作为授权方控制对 REST API 的访问](apigateway-integrate-with-cognito.md)。  调用 `$context.authorizer.claims` 将返回 null。   | 
| \$1context.authorizer.principalId |  与由客户端发送的令牌关联并从 API Gateway Lambda 授权方（以前称为自定义授权方）返回的委托人用户标识。有关更多信息，请参阅 [使用 API Gateway Lambda 授权方](apigateway-use-lambda-authorizer.md)。  | 
| \$1context.authorizer.property |  从 API Gateway Lambda 授权方函数返回的 `context` 映射的指定键/值对的字符串化值。例如，如果授权方返回以下 `context` 映射： <pre>"context" : {<br />  "key": "value",<br />  "numKey": 1,<br />  "boolKey": true<br />}</pre> 调用 `$context.authorizer.key` 将返回 `"value"` 字符串，调用 `$context.authorizer.numKey` 将返回 `"1"` 字符串，而调用 `$context.authorizer.boolKey` 将返回 `"true"` 字符串。 对于*属性*，唯一支持的特殊字符是下划线 `(_)` 字符。 有关更多信息，请参阅 [使用 API Gateway Lambda 授权方](apigateway-use-lambda-authorizer.md)。  | 
| \$1context.awsEndpointRequestId |  AWS 端点的请求 ID。  | 
| \$1context.deploymentId | API 部署的 ID。 | 
| \$1context.domainName |  用于调用 API 的完整域名。这应与传入的 `Host` 标头相同。  | 
| \$1context.domainPrefix |  `$context.domainName` 的第一个标签。  | 
| \$1context.error.message |  包含 API Gateway 错误消息的字符串。此变量只能用于 [GatewayResponse](https://docs.aws.amazon.com/apigateway/latest/api/API_GatewayResponse.html) 正文映射模板中（不由 Velocity 模板语言引擎处理）和访问日志记录中的简单变量替换。有关更多信息，请参阅 [使用 CloudWatch 指标监控 WebSocket API 执行](apigateway-websocket-api-logging.md) 和 [设置网关响应以自定义错误响应](api-gateway-gatewayResponse-definition.md#customize-gateway-responses)。  | 
| \$1context.error.messageString | \$1context.error.message 的带引号的值，即 "\$1context.error.message"。 | 
| \$1context.error.responseType |  [GatewayResponse](https://docs.aws.amazon.com/apigateway/latest/api/API_GatewayResponse.html) 的[类型](https://docs.aws.amazon.com/apigateway/latest/api/API_GatewayResponse.html#responseType) 此变量只能用于 [GatewayResponse](https://docs.aws.amazon.com/apigateway/latest/api/API_GatewayResponse.html) 正文映射模板中（不由 Velocity 模板语言引擎处理）和访问日志记录中的简单变量替换。有关更多信息，请参阅 [使用 CloudWatch 指标监控 WebSocket API 执行](apigateway-websocket-api-logging.md) 和 [设置网关响应以自定义错误响应](api-gateway-gatewayResponse-definition.md#customize-gateway-responses)。  | 
| \$1context.error.validationErrorString |  包含详细验证错误消息的字符串。  | 
| \$1context.extendedRequestId | API Gateway 生成并分配给 API 请求的扩展 ID。扩展请求 ID 包含调试和故障排除的有用信息。 | 
| \$1context.httpMethod |  所用的 HTTP 方法。有效值包括：`DELETE`、`GET`、`HEAD`、`OPTIONS`、`PATCH`、`POST` 和 `PUT`。  | 
| \$1context.identity.accountId |  与请求关联的 AWS 账户 ID。  | 
| \$1context.identity.apiKey |  对于需要 API 密钥的 API 方法，此变量是与该方法请求关联的 API 密钥。对于无需 API 密钥的方法，此变量为 null。有关更多信息，请参阅 [API Gateway 中针对 REST API 的使用计划和 API 密钥](api-gateway-api-usage-plans.md)。  | 
| \$1context.identity.apiKeyId | 与需要 API 密钥的 API 请求关联的 API 密钥 ID。 | 
| \$1context.identity.caller |  签发请求的调用方的委托人标识符。对于使用 IAM 授权的资源支持此项。  | 
| \$1context.identity.cognitoAuthenticationProvider |  发出请求的调用方使用的所有 Amazon Cognito 身份验证提供商的逗号分隔列表。仅当使用 Amazon Cognito 凭证对请求签名时才可用。 例如，对于 Amazon Cognito 身份池中的身份，`cognito-idp. region.amazonaws.com/user_pool_id,cognito-idp.region.amazonaws.com/user_pool_id:CognitoSignIn:token subject claim` 有关更多信息，请参阅 *Amazon Cognito 开发人员指南* 中的[使用联合身份](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-identity.html)。 | 
| \$1context.identity.cognitoAuthenticationType |  发出请求的调用方的 Amazon Cognito 身份验证类型。仅当使用 Amazon Cognito 凭证对请求签名时才可用。可能的值包括经过身份验证的身份的 `authenticated` 和未经身份验证的身份的 `unauthenticated`。 | 
| \$1context.identity.cognitoIdentityId |  发出请求的调用方的 Amazon Cognito 身份 ID。仅当使用 Amazon Cognito 凭证对请求签名时才可用。  | 
| \$1context.identity.cognitoIdentityPoolId |  发出请求的调用方的 Amazon Cognito 身份池 ID。仅当使用 Amazon Cognito 凭证对请求签名时才可用。  | 
| \$1context.identity.principalOrgId |  [AWS 组织 ID](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_org_details.html)。  | 
| \$1context.identity.sourceIp |  向 API Gateway 端点发出请求的即时 TCP 连接的源 IP 地址。  | 
| \$1context.identity.clientCert.clientCertPem |  客户端在双向 TLS 身份验证过程中提供的 PEM 编码的客户端证书。当客户端使用已启用双向 TLS 的自定义域名访问 API 时提供。仅在双向 TLS 身份验证失败时才出现在访问日志中。  | 
| \$1context.identity.clientCert.subjectDN |  客户端提供的证书的主题的可分辨名称。当客户端使用已启用双向 TLS 的自定义域名访问 API 时提供。仅在双向 TLS 身份验证失败时才出现在访问日志中。  | 
| \$1context.identity.clientCert.issuerDN |  客户端提供的证书的颁发者的可分辨名称。当客户端使用已启用双向 TLS 的自定义域名访问 API 时提供。仅在双向 TLS 身份验证失败时才出现在访问日志中。  | 
| \$1context.identity.clientCert.serialNumber |  证书的序列号。当客户端使用已启用双向 TLS 的自定义域名访问 API 时提供。仅在双向 TLS 身份验证失败时才出现在访问日志中。  | 
| \$1context.identity.clientCert.validity.notBefore |  证书无效之前的日期。当客户端使用已启用双向 TLS 的自定义域名访问 API 时提供。仅在双向 TLS 身份验证失败时才出现在访问日志中。  | 
| \$1context.identity.clientCert.validity.notAfter |  证书无效后的日期。当客户端使用已启用双向 TLS 的自定义域名访问 API 时提供。仅在双向 TLS 身份验证失败时才出现在访问日志中。  | 
|  \$1context.identity.vpcId | 向 API Gateway 端点发出请求的 VPC 的 VPC ID。 | 
|  \$1context.identity.vpceId |  向 API Gateway 端点发出请求的 VPC 端点的 VPC 端点 ID。仅当您具有私有 API 时才会显示。  | 
| \$1context.identity.user |  将获得资源访问权限授权的用户的委托人标识符。对于使用 IAM 授权的资源支持此项。  | 
| \$1context.identity.userAgent |  API 调用方的 [https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent) 标头。  | 
| \$1context.identity.userArn |  身份验证后标识的有效用户的 Amazon Resource Name (ARN)。有关更多信息，请参阅 [https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users.html](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users.html)。  | 
| \$1context.isCanaryRequest |  如果请求定向到金丝雀，将返回 `true`，如果请求没有定向到金丝雀，将返回 `false`。仅当您启用金丝雀时才会显示。 | 
| \$1context.path | 请求路径。例如，对于 https://\$1rest-api-id\$1.execute-api.\$1region\$1.amazonaws.com/\$1stage\$1/root/child 的非代理请求 URL，\$1context.path 值为 /\$1stage\$1/root/child。 | 
| \$1context.protocol | 请求的协议，例如，HTTP/1.1。 API Gateway API 可以接受 HTTP/2 请求，但 API Gateway 使用 HTTP/1.1 向后端集成发送请求。因此，即使客户端发送的请求使用 HTTP/2，请求协议也会记录为 HTTP/1.1。   | 
| \$1context.requestId |  请求的 ID。客户可以覆盖此请求 ID。使用 `$context.extendedRequestId` 用于 API Gateway 生成的唯一请求 ID。  | 
| \$1context.requestOverride.header.header\$1name |  请求标头覆盖。如果定义此参数，则它将包含要使用的标题，而不是**集成请求**窗格中定义的 **HTTP 标头**。有关更多信息，请参阅 [针对 API Gateway 中的 REST API 覆盖 API 的请求和响应参数以及状态代码](apigateway-override-request-response-parameters.md)。  | 
| \$1context.requestOverride.path.path\$1name |  请求路径覆盖。如果定义此参数，则它将包含要使用的请求路径，而不是**集成请求**窗格中定义的 **URL 路径参数**。有关更多信息，请参阅 [针对 API Gateway 中的 REST API 覆盖 API 的请求和响应参数以及状态代码](apigateway-override-request-response-parameters.md)。  | 
| \$1context.requestOverride.querystring.querystring\$1name |  请求查询字符串覆盖。如果定义此参数，则它将包含要使用的请求查询字符串，而不是**集成请求**窗格中定义的 **URL 查询字符串参数**。有关更多信息，请参阅 [针对 API Gateway 中的 REST API 覆盖 API 的请求和响应参数以及状态代码](apigateway-override-request-response-parameters.md)。  | 
| \$1context.responseOverride.header.header\$1name | 响应标头覆盖。如果定义此参数，则它包含要使用的标头，而不是集成响应窗格中定义为默认映射的响应标头。有关更多信息，请参阅 [针对 API Gateway 中的 REST API 覆盖 API 的请求和响应参数以及状态代码](apigateway-override-request-response-parameters.md)。 | 
| \$1context.responseOverride.status | 响应状态代码覆盖。如果定义此参数，则它包含要使用的状态代码，而不是集成响应窗格中定义为默认映射的方法响应状态。有关更多信息，请参阅 [针对 API Gateway 中的 REST API 覆盖 API 的请求和响应参数以及状态代码](apigateway-override-request-response-parameters.md)。 | 
| \$1context.requestTime | [CLF](https://httpd.apache.org/docs/current/logs.html#common) 格式的请求时间 (dd/MMM/yyyy:HH:mm:ss \$1-hhmm)。 | 
| \$1context.requestTimeEpoch | [Epoch](https://en.wikipedia.org/wiki/Unix_time) 格式的请求时间，以毫秒为单位。 | 
| \$1context.resourceId |  API Gateway 分配给您的资源的标识符。  | 
| \$1context.resourcePath |  资源路径。例如，对于 `https://{rest-api-id}.execute-api.{region}.amazonaws.com/{stage}/root/child` 的非代理请求 URI，`$context.resourcePath` 值为 `/root/child`。有关更多信息，请参阅 [教程：使用 HTTP 非代理集成创建 REST API](api-gateway-create-api-step-by-step.md)。  | 
| \$1context.stage |  API 请求的部署阶段（例如，`Beta` 或 `Prod`）。  | 
| \$1context.wafResponseCode |  从 [AWS WAF](https://docs.aws.amazon.com/waf/latest/developerguide/waf-chapter.html) 中收到的响应：`WAF_ALLOW` 或 `WAF_BLOCK`。如果阶段未与 Web ACL 关联，则不会设置。有关更多信息，请参阅 [在 API Gateway 中使用 AWS WAF 保护 REST API](apigateway-control-access-aws-waf.md)。  | 
| \$1context.webaclArn |  Web ACL 的完整 ARN，用于决定是允许还是阻止请求。如果阶段未与 Web ACL 关联，则不会设置。有关更多信息，请参阅 [在 API Gateway 中使用 AWS WAF 保护 REST API](apigateway-control-access-aws-waf.md)。  | 

## 输入变量
<a name="input-variable-reference"></a>

可以使用以下区分大小写的 `$input` 变量来引用方法请求有效载荷和方法请求参数。可以执行以下功能：


| 变量和函数 | 说明 | 
| --- | --- | 
| \$1input.body |  以字符串形式返回原始请求负载。您可以使用 `$input.body` 来保留整个浮点数，例如 `10.00`。 | 
| \$1input.json(x) | 此函数计算 JSONPath 表达式并以 JSON 字符串形式返回结果。 例如，`$input.json('$.pets')` 返回一个表示 `pets` 结构的 JSON 字符串。 有关 JSONPath 的更多信息，请参阅 [JSONPath](https://goessner.net/articles/JsonPath/) 或[适用于 Java 的 JSONPath](https://github.com/json-path/JsonPath)。 | 
| \$1input.params() |  返回所有请求参数的映射。我们建议您使用 `$util.escapeJavaScript` 对结果进行清理，以避免潜在的注入攻击。要完全控制请求清理，可以使用没有模板的代理集成，并在集成中处理请求清理。 | 
| \$1input.params(x) | 在给定参数名称字符串 `x` 的情况下，返回路径中的方法请求参数值、查询字符串或标头值（按照该顺序搜索）。我们建议您使用 `$util.escapeJavaScript` 对参数进行清理，以避免潜在的注入攻击。要完全控制参数清理，可以使用没有模板的代理集成，并在集成中处理请求清理。 | 
| \$1input.path(x) | 获取一个 JSONPath 表达式字符串 (`x`) 并返回结果的 JSON 对象表达式。这样，您便可通过 [Apache Velocity 模板语言 (VTL)](https://velocity.apache.org/engine/devel/vtl-reference.html) 在本机访问和操作负载的元素。 例如，如果表达式 `$input.path('$.pets')` 返回一个如下所示的对象： <pre>[<br />  { <br />    "id": 1, <br />    "type": "dog", <br />    "price": 249.99 <br />  }, <br />  { <br />    "id": 2, <br />    "type": "cat", <br />    "price": 124.99 <br />  }, <br />  { <br />    "id": 3, <br />    "type": "fish", <br />    "price": 0.99 <br />  } <br />]</pre> `$input.path('$.pets').size()` 将返回 `"3"`。 有关 JSONPath 的更多信息，请参阅 [JSONPath](https://goessner.net/articles/JsonPath/) 或[适用于 Java 的 JSONPath](https://github.com/json-path/JsonPath)。 | 

## 阶段变量
<a name="stagevariables-template-reference"></a>

在方法集成中，可以使用以下阶段变量作为 ARN 和 URL 的占位符。有关更多信息，请参阅 [在 API Gateway 中对 REST API 使用阶段变量](stage-variables.md)。


| 语法 | 说明 | 
| --- | --- | 
| \$1stageVariables.variable\$1name、\$1stageVariables['variable\$1name'] 或 \$1\$1stageVariables['variable\$1name']\$1  |  *variable\$1name* 表示阶段变量名称。  | 

## Util 变量
<a name="util-template-reference"></a>

您可以使用以下区分大小写的 `$util` 变量，以便将实用程序函数用于映射模板。除非另行指定，否则默认字符集为 UTF-8。


| 函数 | 说明 | 
| --- | --- | 
| \$1util.escapeJavaScript() |  使用 JavaScript 字符串规则对字符串中的字符进行转义。  此函数会将任何常规单引号 (`'`) 变成转义单引号 (`\'`)。但是，转义单引号在 JSON 中无效。因此，当此函数的输出用于 JSON 属性时，必须将任何转义单引号 (`\'`) 变回常规单引号 (`'`)。如下例所示:  <pre> "input" : "$util.escapeJavaScript(data).replaceAll("\\'","'")"</pre>   | 
| \$1util.parseJson() |   获取“字符串化的”JSON 并返回结果的对象表示形式。您可以使用此函数的结果通过 Apache Velocity 模板语言 (VTL) 在本机访问和操作负载的元素。例如，如果您具有以下负载： <pre>{"errorMessage":"{\"key1\":\"var1\",\"key2\":{\"arr\":[1,2,3]}}"}</pre>  并使用以下映射模板  <pre>#set ($errorMessageObj = $util.parseJson($input.path('$.errorMessage')))<br />{<br />   "errorMessageObjKey2ArrVal" : $errorMessageObj.key2.arr[0]<br />}<br /></pre> 您将得到以下输出： <pre>{<br />   "errorMessageObjKey2ArrVal" : 1<br />}<br /></pre>  | 
| \$1util.urlEncode() | 将字符串转换为“application/x-www-form-urlencoded”格式。 | 
| \$1util.urlDecode() | 对“application/x-www-form-urlencoded”字符串进行解码。 | 
| \$1util.base64Encode() | 将数据编码为 base64 编码的字符串。 | 
| \$1util.base64Decode() | 对 base64 编码字符串中的数据进行解码。 | 