

# 针对 API Gateway 中 REST API 的数据转换
<a name="rest-api-data-transformations"></a>

**注意**  
本节介绍您在非代理集成中使用的功能。但是，我们建议您尽可能为 REST API 使用代理集成。代理集成具有简化的集成设置，可以随后端演变，而无需停用现有设置。有关更多信息，请参阅 [选择 API Gateway API 集成类型](api-gateway-api-integration-types.md)。

如果您使用非代理集成，则可以使用 API Gateway 的两个功能来转换方法请求和集成响应。如果方法请求采用的有效载荷格式与集成请求有效载荷不同，则可以对方法请求进行转换。如果集成响应返回的有效载荷格式与您需要在方法响应中返回的格式不同，则可以对集成响应进行转换。有关请求生命周期的更多信息，请参阅 [REST API 的示例资源](rest-api-develop.md#rest-api-develop-example)。

以下示例显示了一个数据转换，其中对于标头 `"x-version:beta"`，`x-version` 标头参数转换为 `app-version` 标头参数。从 `x-version` 到 `app-version` 的数据转换发生在集成请求中。这样，集成端点就会收到转换后的标头参数值。当集成端点返回状态代码时，状态代码将在方法响应之前从 `200` 转换为 `204`。

![\[API Gateway 数据转换图\]](http://docs.aws.amazon.com/zh_cn/apigateway/latest/developerguide/images/develop-non-proxy.png)


要创建数据转换，可以使用以下功能：

**参数映射**  
在参数映射中，可以修改集成请求 URL 路径参数、URL 查询字符串参数或 HTTP 标头值，但不能修改集成请求有效载荷。也可以修改 HTTP 响应标头值。使用参数映射为跨源资源共享（CORS）创建静态标头值。  
您可以在代理和非代理集成的集成请求中使用参数映射，但要将参数映射用于集成响应，则需要非代理集成。参数映射不需要使用 [Velocity Template Language (VTL)](https://velocity.apache.org/engine/devel/vtl-reference.html) 编写任何脚本。有关更多信息，请参阅 [API Gateway 中 REST API 的参数映射](rest-api-parameter-mapping.md)。

**映射模板转换**  
在映射模板转换中，可以使用映射模板来映射 URL 路径参数、URL 查询字符串参数、HTTP 标头和集成请求或集成响应正文。**映射模板是使用 [JSONPath 表达式](https://goessner.net/articles/JsonPath/)以 [Velocity Template Language（VTL）](https://velocity.apache.org/engine/devel/vtl-reference.html)表示的脚本，并基于 `Content-type` 标头应用于有效载荷。  
使用映射模板，您可以执行以下操作：  
+ 选择要使用与 AWS 服务（例如 Amazon DynamoDB 或 Lambda 函数或 HTTP 端点）的集成发送哪些数据。有关更多信息，请参阅 [教程：修改集成请求和响应以集成到 AWS 服务](set-up-data-transformations-in-api-gateway.md)。
+ 有条件地覆盖 API 的集成请求和集成响应参数、创建新的标头值并覆盖状态代码。有关更多信息，请参阅 [针对 API Gateway 中的 REST API 覆盖 API 的请求和响应参数以及状态代码](apigateway-override-request-response-parameters.md)。
当集成请求正文的 `Content-type` 标头没有匹配的映射模板时，还可以指定 API 的行为。这称为集成传递行为。有关更多信息，请参阅 [API Gateway 中适用于 REST API 且无映射模板的有效载荷的方法请求行为](integration-passthrough-behaviors.md)。

## 在参数映射与映射模板转换之间进行选择
<a name="rest-api-data-transformations-choose"></a>

我们建议您尽可能使用参数映射来转换数据。如果 API 要求您更改正文，或者要求您根据传入的集成请求或集成响应执行有条件覆盖和修改，并且您无法使用代理集成，请使用映射模板转换。

# API Gateway 中 REST API 的参数映射
<a name="rest-api-parameter-mapping"></a>

**注意**  
如果您使用的是 HTTP API，请参阅[针对 API Gateway 中的 HTTP API 转换 API 请求和响应](http-api-parameter-mapping.md)。

在参数映射中，您可以映射请求或响应参数。您可以使用参数映射表达式或静态值来映射参数。有关映射表达式的列表，请参阅 [API Gateway 中 REST API 的参数映射源参考](rest-api-parameter-mapping-sources.md)。您可以在代理和非代理集成的集成请求中使用参数映射，但要将参数映射用于集成响应，则需要非代理集成。

例如，您可以将方法请求标头参数 `puppies` 映射到集成请求标头参数 `DogsAge0`。然后，如果客户端将标头 `puppies:true` 发送到您的 API，则集成请求会将请求标头 `DogsAge0:true` 发送到集成端点。下图显示了此示例的请求生命周期。

![\[请求的 API Gateway 参数映射示例图\]](http://docs.aws.amazon.com/zh_cn/apigateway/latest/developerguide/images/parameter-mapping-example1.png)


要使用 API Gateway 创建此示例，请参阅[示例 1：将方法请求参数映射到集成请求参数](request-response-data-mappings.md#request-response-data-mappings-example-1)。

 再举一个例子，您也可以将集成响应标头参数 `kittens` 映射到方法响应标头参数 `CatsAge0`。然后，如果集成端点返回 `kittens:false`，则客户端将收到标头 `CatsAge0:false`。下图显示了此示例的请求生命周期。

![\[响应的 API Gateway 参数映射示例图\]](http://docs.aws.amazon.com/zh_cn/apigateway/latest/developerguide/images/parameter-mapping-example2.png)


**Topics**
+ [API Gateway 中 REST API 的参数映射示例](request-response-data-mappings.md)
+ [API Gateway 中 REST API 的参数映射源参考](rest-api-parameter-mapping-sources.md)

# API Gateway 中 REST API 的参数映射示例
<a name="request-response-data-mappings"></a>

以下示例显示如何使用 API Gateway 控制台、OpenAPI 和 CloudFormation 模板创建参数映射表达式。有关如何使用参数映射来创建所需 CORS 标头的示例，请参阅[针对 API Gateway 中的 REST API 的 CORS](how-to-cors.md)。

## 示例 1：将方法请求参数映射到集成请求参数
<a name="request-response-data-mappings-example-1"></a>

以下示例将方法请求标头参数 `puppies` 映射到集成请求标头参数 `DogsAge0`。

------
#### [ AWS 管理控制台 ]

**映射方法请求参数**

1. 通过以下网址登录到 Amazon API Gateway 控制台：[https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway)。

1. 选择一个 REST API。

1. 选择方法。

   您的方法必须具有非代理集成。

1. 对于**方法请求设置**，选择**编辑**。

1. 选择 **HTTP 请求标头**。

1. 选择**添加标头**。

1. 对于**名称**，请输入 **puppies**。

1. 选择**保存**。

1. 选择**集成请求**选项卡，然后对于**集成请求设置**，选择**编辑**。

   AWS 管理控制台会自动为您添加从 `method.request.header.puppies ` 到 `puppies` 的参数映射，但您需要更改**名称**，以匹配集成端点所期望的请求标头参数。

1. 对于**名称**，请输入 **DogsAge0**。

1. 选择**保存**。

1. 重新部署 API 以使更改生效。

以下步骤向您展示如何验证参数映射是否成功。

**（可选）测试参数映射**

1. 选择**测试**选项卡。您可能需要选择右箭头按钮，以显示该选项卡。

1. 对于标头，输入 **puppies:true**。

1. 选择**测试**。

1. 在**日志**中，结果应该类似以下内容：

   ```
   Tue Feb 04 00:28:36 UTC 2025 : Method request headers: {puppies=true}
   Tue Feb 04 00:28:36 UTC 2025 : Method request body before transformations: 
   Tue Feb 04 00:28:36 UTC 2025 : Endpoint request URI: http://petstore-demo-endpoint.execute-api.com/petstore/pets
   Tue Feb 04 00:28:36 UTC 2025 : Endpoint request headers: {DogsAge0=true, x-amzn-apigateway-api-id=abcd1234, Accept=application/json, User-Agent=AmazonAPIGateway_aaaaaaa, X-Amzn-Trace-Id=Root=1-abcd-12344}
   ```

   请求标头参数已从 `puppies` 更改为 `DogsAge0`。

------
#### [ CloudFormation ]

 在此示例中，您使用 [body](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html#cfn-apigateway-restapi-body) 属性将 OpenAPI 定义文件导入到 API Gateway。

```
AWSTemplateFormatVersion: 2010-09-09
Resources:
  Api:
    Type: 'AWS::ApiGateway::RestApi'
    Properties:
      Body:
        openapi: 3.0.1
        info:
          title: ParameterMappingExample
          version: "2025-02-04T00:30:41Z"
        paths:
          /pets:
            get:
              parameters:
                - name: puppies
                  in: header
                  schema:
                    type: string
              responses:
                "200":
                  description: 200 response
              x-amazon-apigateway-integration:
                httpMethod: GET
                uri: http://petstore-demo-endpoint.execute-api.com/petstore/pets
                responses:
                  default:
                    statusCode: "200"
                requestParameters:
                  integration.request.header.DogsAge0: method.request.header.puppies
                passthroughBehavior: when_no_match
                type: http
  ApiGatewayDeployment:
    Type: 'AWS::ApiGateway::Deployment'
    DependsOn: Api 
    Properties: 
      RestApiId: !Ref Api
  ApiGatewayDeployment20250219:
    Type: 'AWS::ApiGateway::Deployment'
    DependsOn: Api 
    Properties: 
      RestApiId: !Ref Api
  Stage:
    Type: 'AWS::ApiGateway::Stage'
    Properties:
       DeploymentId: !Ref ApiGatewayDeployment20250219
       RestApiId: !Ref Api
       StageName: prod
```

------
#### [ OpenAPI ]

```
{
  "openapi" : "3.0.1",
  "info" : {
    "title" : "ParameterMappingExample",
    "version" : "2025-02-04T00:30:41Z"
  },
  "paths" : {
    "/pets" : {
      "get" : {
        "parameters" : [ {
          "name" : "puppies",
          "in" : "header",
          "schema" : {
            "type" : "string"
          }
        } ],
        "responses" : {
          "200" : {
            "description" : "200 response"
          }
        },
        "x-amazon-apigateway-integration" : {
          "httpMethod" : "GET",
          "uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets",
          "responses" : {
            "default" : {
              "statusCode" : "200"
            }
          },
          "requestParameters" : {
            "integration.request.header.DogsAge0" : "method.request.header.puppies"
          },
          "passthroughBehavior" : "when_no_match",
          "type" : "http"
        }
      }
    }
  }
}
```

------

## 示例 2：将多个方法请求参数映射到不同的集成请求参数
<a name="request-response-data-mappings-example-2"></a>

以下示例将多值方法请求查询字符串参数 `methodRequestQueryParam` 映射到集成请求查询字符串参数 `integrationQueryParam`，并将方法请求标头参数 `methodRequestHeaderParam` 映射到集成请求路径参数 `integrationPathParam`。

------
#### [ AWS 管理控制台 ]

**映射方法请求参数**

1. 通过以下网址登录到 Amazon API Gateway 控制台：[https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway)。

1. 选择一个 REST API。

1. 选择方法。

   您的方法必须具有非代理集成。

1. 对于**方法请求设置**，选择**编辑**。

1. 选择 **URL 查询字符串参数**。

1. 选择**添加查询字符串**。

1. 在**名称**中，输入 **methodRequestQueryParam**。

1. 选择 **HTTP 请求标头**。

1. 选择**添加标头**。

1. 对于**名称**，请输入 **methodRequestHeaderParam**。

1. 选择**保存**。

1. 选择**集成请求**选项卡，然后对于**集成请求设置**，选择**编辑**。

1. 选择 **URL 路径参数**。

1. 选择**添加路径参数**。

1. 对于**名称**，请输入 **integrationPathParam**。

1. 对于**映射自**，输入 **method.request.header.methodRequestHeaderParam**。

   这会将您在方法请求中指定的方法请求标头映射到新的集成请求路径参数。

1. 选择 **URL 查询字符串参数**。

1. 选择**添加查询字符串**。

1. 在**名称**中，输入 **integrationQueryParam**。

1. 对于**映射自**，输入 **method.request.multivaluequerystring.methodRequestQueryParam**。

   这会将多值查询字符串参数映射到新的单值集成请求查询字符串参数。

1. 选择**保存**。

1. 重新部署 API 以使更改生效。

------
#### [ CloudFormation ]

 在此示例中，您使用 [body](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html#cfn-apigateway-restapi-body) 属性将 OpenAPI 定义文件导入到 API Gateway。

以下 OpenAPI 定义为 HTTP 集成创建以下参数映射：
+ 将方法请求的名为 `methodRequestHeaderParam` 的标头映射到名为 `integrationPathParam` 的集成请求路径参数
+ 将名为 `methodRequestQueryParam` 的多值方法请求查询字符串映射到名为 `integrationQueryParam` 的集成请求查询字符串

```
AWSTemplateFormatVersion: 2010-09-09
Resources:
  Api:
    Type: 'AWS::ApiGateway::RestApi'
    Properties:
      Body: 
        openapi: 3.0.1
        info:
          title: Parameter mapping example 2
          version: "2025-01-15T19:12:31Z"
        paths:
          /:
            post:
              parameters:
                - name: methodRequestQueryParam
                  in: query
                  schema:
                    type: string
                - name: methodRequestHeaderParam
                  in: header
                  schema:
                    type: string
              responses:
                "200":
                  description: 200 response
              x-amazon-apigateway-integration:
                httpMethod: GET
                uri: http://petstore-demo-endpoint.execute-api.com/petstore/pets
                responses:
                  default:
                    statusCode: "200"
                requestParameters:
                  integration.request.querystring.integrationQueryParam: method.request.multivaluequerystring.methodRequestQueryParam
                  integration.request.path.integrationPathParam: method.request.header.methodRequestHeaderParam
                requestTemplates:
                  application/json: '{"statusCode": 200}'
                passthroughBehavior: when_no_templates
                timeoutInMillis: 29000
                type: http
  ApiGatewayDeployment:
    Type: 'AWS::ApiGateway::Deployment'
    DependsOn: Api 
    Properties: 
      RestApiId: !Ref Api
  ApiGatewayDeployment20250219:
    Type: 'AWS::ApiGateway::Deployment'
    DependsOn: Api 
    Properties: 
      RestApiId: !Ref Api
  Stage:
    Type: 'AWS::ApiGateway::Stage'
    Properties:
       DeploymentId: !Ref ApiGatewayDeployment20250219
       RestApiId: !Ref Api
       StageName: prod
```

------
#### [ OpenAPI ]

以下 OpenAPI 定义为 HTTP 集成创建以下参数映射：
+ 将方法请求的名为 `methodRequestHeaderParam` 的标头映射到名为 `integrationPathParam` 的集成请求路径参数
+ 将名为 `methodRequestQueryParam` 的多值方法请求查询字符串映射到名为 `integrationQueryParam` 的集成请求查询字符串

```
{
  "openapi" : "3.0.1",
  "info" : {
    "title" : "Parameter mapping example 2",
    "version" : "2025-01-15T19:12:31Z"
  },
  "paths" : {
    "/" : {
      "post" : {
        "parameters" : [ {
          "name" : "methodRequestQueryParam",
          "in" : "query",
          "schema" : {
            "type" : "string"
          }
        }, {
          "name" : "methodRequestHeaderParam",
          "in" : "header",
          "schema" : {
            "type" : "string"
          }
        } ],
        "responses" : {
          "200" : {
            "description" : "200 response"
          }
        },
        "x-amazon-apigateway-integration" : {
          "httpMethod" : "GET",
          "uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets",
          "responses" : {
            "default" : {
              "statusCode" : "200"
            }
          },
          "requestParameters" : {
            "integration.request.querystring.integrationQueryParam" : "method.request.multivaluequerystring.methodRequestQueryParam",
            "integration.request.path.integrationPathParam" : "method.request.header.methodRequestHeaderParam"
          },
          "requestTemplates" : {
            "application/json" : "{\"statusCode\": 200}"
          },
          "passthroughBehavior" : "when_no_templates",
          "timeoutInMillis" : 29000,
          "type" : "http"
        }
      }
    }
  }
}
```

------

## 示例 3：将 JSON 请求正文中的字段映射到集成请求参数
<a name="request-response-data-mappings-example-3"></a>

还可以使用 [JSONPath expression](http://goessner.net/articles/JsonPath/index.html#e2) 从 JSON 请求正文中的字段映射集成请求参数。以下示例将方法请求正文映射到名为 `body-header` 的集成请求标头，并将部分请求正文（由 JSON 表达式表示）映射到名为 `pet-price` 的集成请求标头。

要测试此示例，请提供包含价格类别的输入，如下所示：

```
[ 
  { 
    "id": 1, 
    "type": "dog", 
    "price": 249.99 
  }
]
```

------
#### [ AWS 管理控制台 ]

**映射方法请求参数**

1. 通过以下网址登录到 Amazon API Gateway 控制台：[https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway)。

1. 选择一个 REST API。

1. 选择 `POST`、`PUT`、`PATCH` 或 `ANY` 方法。

   您的方法必须具有非代理集成。

1. 对于**集成请求设置**，选择**编辑**。

1. 选择 **URL 请求标头参数**。

1. 选择**添加请求标头参数**。

1. 对于**名称**，请输入 **body-header**。

1. 对于**映射自**，输入 **method.request.body**。

   这会将方法请求正文映射到新的集成请求标头参数。

1. 选择**添加请求标头参数**。

1. 对于**名称**，请输入 **pet-price**。

1. 对于**映射自**，输入 ** method.request.body[0].price**。

   这会将方法请求正文的一部分映射到新的集成请求标头参数。

1. 选择**保存**。

1. 重新部署 API 以使更改生效。

------
#### [ CloudFormation ]

 在此示例中，您使用 [body](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html#cfn-apigateway-restapi-body) 属性将 OpenAPI 定义文件导入到 API Gateway。

```
AWSTemplateFormatVersion: 2010-09-09
Resources:
  Api:
    Type: 'AWS::ApiGateway::RestApi'
    Properties:
      Body: 
        openapi: 3.0.1
        info:
          title: Parameter mapping example 3
          version: "2025-01-15T19:19:14Z"
        paths:
          /:
            post:
              responses:
                "200":
                  description: 200 response
              x-amazon-apigateway-integration:
                httpMethod: GET
                uri: http://petstore-demo-endpoint.execute-api.com/petstore/pets
                responses:
                  default:
                    statusCode: "200"
                requestParameters:
                  integration.request.header.pet-price: method.request.body[0].price
                  integration.request.header.body-header: method.request.body
                requestTemplates:
                  application/json: '{"statusCode": 200}'
                passthroughBehavior: when_no_templates
                timeoutInMillis: 29000
                type: http
  ApiGatewayDeployment:
    Type: 'AWS::ApiGateway::Deployment'
    DependsOn: Api 
    Properties: 
      RestApiId: !Ref Api
  ApiGatewayDeployment20250219:
    Type: 'AWS::ApiGateway::Deployment'
    DependsOn: Api 
    Properties: 
      RestApiId: !Ref Api
  Stage:
    Type: 'AWS::ApiGateway::Stage'
    Properties:
       DeploymentId: !Ref ApiGatewayDeployment20250219
       RestApiId: !Ref Api
       StageName: prod
```

------
#### [ OpenAPI ]

以下 OpenAPI 定义从 JSON 请求正文中的字段映射集成请求参数。

```
{
  "openapi" : "3.0.1",
  "info" : {
    "title" : "Parameter mapping example 3",
    "version" : "2025-01-15T19:19:14Z"
  },
  "paths" : {
    "/" : {
      "post" : {
        "responses" : {
          "200" : {
            "description" : "200 response"
          }
        },
        "x-amazon-apigateway-integration" : {
          "httpMethod" : "GET",
          "uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets",
          "responses" : {
            "default" : {
              "statusCode" : "200"
            }
          },
          "requestParameters" : {
            "integration.request.header.pet-price" : "method.request.body[0].price",
            "integration.request.header.body-header" : "method.request.body"
          },
          "requestTemplates" : {
            "application/json" : "{\"statusCode\": 200}"
          },
          "passthroughBehavior" : "when_no_templates",
          "timeoutInMillis" : 29000,
          "type" : "http"
        }
      }
    }
  }
}
```

------

## 示例 4：将集成响应映射到方法响应
<a name="request-response-data-mappings-example-4"></a>

还可以将集成响应映射到方法响应。以下示例将集成响应正文映射到名为 `location` 的方法响应标头，将集成响应标头 `x-app-id` 映射到方法响应标头 `id`，并将多值集成响应标头 `item` 映射到方法响应标头 `items`。

------
#### [ AWS 管理控制台 ]

**映射集成响应**

1. 通过以下网址登录到 Amazon API Gateway 控制台：[https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway)。

1. 选择一个 REST API。

1. 选择方法。

   您的方法必须具有非代理集成。

1. 选择**方法响应**选项卡，然后对于**响应 200** 选择**编辑**。

1. 对于**标头名称**，选择**添加标头**。

1. 创建三个名为 **id**、**item**、和 **location** 的标头。

1. 选择**保存**。

1. 选择**集成响应**选项卡，然后对于**默认 - 响应**，选择**编辑**。

1. 在**标头映射**下，输入以下内容。

   1. 对于 **id**，输入 **integration.response.header.x-app-id**

   1. 对于**项目**，输入 **integration.response.multivalueheader.item**

   1. 对于**位置**，输入 **integration.response.body.redirect.url**

1. 选择**保存**。

1. 重新部署 API 以使更改生效。

------
#### [ CloudFormation ]

 在此示例中，您使用 [body](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html#cfn-apigateway-restapi-body) 属性将 OpenAPI 定义文件导入到 API Gateway。

```
AWSTemplateFormatVersion: 2010-09-09
Resources:
  Api:
    Type: 'AWS::ApiGateway::RestApi'
    Properties:
      Body:
        openapi: 3.0.1
        info:
          title: Parameter mapping example
          version: "2025-01-15T19:21:35Z"
        paths:
          /:
            post:
              responses:
                "200":
                  description: 200 response
                  headers:
                    item:
                      schema:
                        type: string
                    location:
                      schema:
                        type: string
                    id:
                      schema:
                        type: string
              x-amazon-apigateway-integration:
                type: http
                httpMethod: GET
                uri: http://petstore-demo-endpoint.execute-api.com/petstore/pets
                responses:
                  default:
                    statusCode: "200"
                    responseParameters:
                      method.response.header.id: integration.response.header.x-app-id
                      method.response.header.location: integration.response.body.redirect.url
                      method.response.header.item: integration.response.multivalueheader.item
                requestTemplates:
                  application/json: '{"statusCode": 200}'
                passthroughBehavior: when_no_templates
                timeoutInMillis: 29000
  ApiGatewayDeployment:
    Type: 'AWS::ApiGateway::Deployment'
    DependsOn: Api 
    Properties: 
      RestApiId: !Ref Api
  ApiGatewayDeployment20250219:
    Type: 'AWS::ApiGateway::Deployment'
    DependsOn: Api 
    Properties: 
      RestApiId: !Ref Api
  Stage:
    Type: 'AWS::ApiGateway::Stage'
    Properties:
       DeploymentId: !Ref ApiGatewayDeployment20250219
       RestApiId: !Ref Api
       StageName: prod
```

------
#### [ OpenAPI ]

以下 OpenAPI 定义将集成响应映射到方法响应。

```
{
  "openapi" : "3.0.1",
  "info" : {
    "title" : "Parameter mapping example",
    "version" : "2025-01-15T19:21:35Z"
  },
  "paths" : {
    "/" : {
      "post" : {
        "responses" : {
          "200" : {
            "description" : "200 response",
            "headers" : {
              "item" : {
                "schema" : {
                  "type" : "string"
                }
              },
              "location" : {
                "schema" : {
                  "type" : "string"
                }
              },
              "id" : {
                "schema" : {
                  "type" : "string"
                }
              }
            }
          }
        },
        "x-amazon-apigateway-integration" : {
          "type" : "http",
          "httpMethod" : "GET",
          "uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets",
          "responses" : {
            "default" : {
              "statusCode" : "200",
              "responseParameters" : {
                "method.response.header.id" : "integration.response.header.x-app-id",
                "method.response.header.location" : "integration.response.body.redirect.url",
                "method.response.header.item" : "integration.response.multivalueheader.item"
              }
            }
          },
          "requestTemplates" : {
            "application/json" : "{\"statusCode\": 200}"
          },
          "passthroughBehavior" : "when_no_templates",
          "timeoutInMillis" : 29000
        }
      }
    }
  }
}
```

------

# API Gateway 中 REST API 的参数映射源参考
<a name="rest-api-parameter-mapping-sources"></a>

创建参数映射时，可以指定要修改的方法请求或集成响应参数，并指定如何修改这些参数。

下表显示了可以映射的方法请求参数以及用于创建映射的表达式。在这些表达式中，*name* 是方法请求参数的名称。例如，要映射请求标头参数 `puppies`，请使用表达式 `method.request.header.puppies`。您的表达式必须与正则表达式 `'^[a-zA-Z0-9._$-]+$]'` 匹配。您可以在代理和非代理集成的集成请求中使用参数映射。


| **映射的数据来源** | **映射表达式** | 
| --- | --- | 
| 方法请求路径 | method.request.path.name | 
| 方法请求查询字符串 | method.request.querystring.name | 
| 多值方法请求查询字符串 | method.request.multivaluequerystring.name | 
| 方法请求标头 | method.request.header.name | 
| 多值方法请求标头 | method.request.multivalueheader.name | 
| 方法请求正文 | method.request.body | 
| 方法请求正文 (JsonPath) | `method.request.body.JSONPath_EXPRESSION`. *JSONPath\$1EXPRESSION* 是请求正文的 JSON 字段的 JSONPath 表达式。有关更多信息，请参阅 [JSONPath expression](http://goessner.net/articles/JsonPath/index.html#e2)。  | 
| 阶段变量 | stageVariables.name | 
| 上下文变量 |  `context.name` 名称必须为[受支持的上下文变量](api-gateway-mapping-template-reference.md#context-variable-reference)之一。 | 
| 静态值 | `'static_value'`. *static\$1value* 为字符串文本值，必须括在一对单引号内。例如 `'https://www.example.com'`。 | 

下表显示了可以映射的集成响应参数以及用于创建映射的表达式。在这些表达式中，*name* 是集成响应参数的名称。您可以从任何集成响应标头或集成响应正文、\$1context 变量或静态值映射方法响应标头。要将参数映射用于集成响应，您需要使用非代理集成。


| 映射数据源 | 映射表达式 | 
| --- | --- | 
| 集成响应标头 | integration.response.header.name | 
| 集成响应标头 | integration.response.multivalueheader.name | 
| 集成响应正文 | integration.response.body | 
| 集成响应正文 (JsonPath) | `integration.response.body.JSONPath_EXPRESSION` *JSONPath\$1EXPRESSION* 是响应正文的 JSON 字段的 JSONPath 表达式。有关更多信息，请参阅 [JSONPath expression](http://goessner.net/articles/JsonPath/index.html#e2)。 | 
| 阶段变量 | stageVariables.name | 
| 上下文变量 |  `context.name` 名称必须为[受支持的上下文变量](api-gateway-mapping-template-reference.md#context-variable-reference)之一。 | 
| 静态值 | ` 'static_value'` *static\$1value* 为字符串文本值，必须括在一对单引号内。例如 `'https://www.example.com'`。 | 

# API Gateway 中 REST API 的映射模板转换
<a name="models-mappings"></a>

映射模板转换使用映射模板来修改集成请求或集成响应。**映射模板是以 [Velocity Template Language（VTL）](https://velocity.apache.org/engine/devel/vtl-reference.html)表示的脚本，并使用 [JSONPath](https://goessner.net/articles/JsonPath/) 基于 `Content-type` 标头应用于有效载荷。使用映射模板转换时使用映射模板。此部分介绍与映射模板相关的概念性信息。

下图显示了与 PetStore 集成端点集成的 `POST /pets` 资源的请求生命周期。在此 API 中，用户发送有关宠物的数据，而集成端点返回与宠物关联的收养费。在此请求生命周期中，映射模板转换会将请求正文筛选到集成端点，并从集成端点筛选响应正文。

![\[请求生命周期示例\]](http://docs.aws.amazon.com/zh_cn/apigateway/latest/developerguide/images/mapping-template-transforms.png)


以下各节解释请求和响应生命周期。

## 方法请求和集成请求
<a name="models-mappings-request"></a>

在前面的示例中，如果这是发送到方法请求的请求正文：

```
POST /pets
    HTTP/1.1
    Host:abcd1234.us-west-2.amazonaws.com
    Content-type: application/json
    
  {
    "id": 1,
    "type": "dog",
    "Age": 11,
  }
```

此请求正文的格式不适合集成端点使用，因此 API Gateway 执行映射模板转换。API Gateway 仅执行映射模板转换，因为已为 Content-Type `application/json` 定义了映射模板。如果您没有为 Content-Type 定义映射模板，则默认情况下，API Gateway 会通过集成请求将正文传递到集成端点。要修改此行为，请参阅 [API Gateway 中适用于 REST API 且无映射模板的有效载荷的方法请求行为](integration-passthrough-behaviors.md)。

以下映射模板先转换集成请求中的方法请求数据，然后将数据发送到集成端点：

```
#set($inputRoot = $input.path('$'))
  {
    "dogId" : "dog_"$elem.id,
    "Age": $inputRoot.Age
  }
```

1. `$inputRoot` 变量表示上一部分的原始 JSON 数据中的根对象。指令以 `#` 符号开头。

1. `dog` 是用户的 `id` 和字符串值的串联。

1. `Age` 来自方法请求正文。

然后，将以下输出转发到集成端点：

```
{
    "dogId" : "dog_1",
    "Age": 11
  }
```

## 集成响应和方法响应
<a name="models-mappings-response"></a>

成功请求集成端点后，端点会向 API Gateway 的集成响应发送响应。以下是来自集成端点的示例输出数据：

```
{
    "dogId" : "dog_1",
    "adoptionFee": 19.95,
}
```

方法响应预期的有效载荷与集成响应返回的有效载荷不同。API Gateway 执行映射模板转换。API Gateway 仅执行映射模板转换，因为已为 Content-Type `application/json` 定义了映射模板。如果您没有为 Content-Type 定义映射模板，则默认情况下，API Gateway 会通过对方法响应的集成响应传递正文。要修改此行为，请参阅 [API Gateway 中适用于 REST API 且无映射模板的有效载荷的方法请求行为](integration-passthrough-behaviors.md)。

```
#set($inputRoot = $input.path('$'))
  {
    "adoptionFee" : $inputRoot.adoptionFee,
  }
```

以下输出发送到方法响应：

```
{"adoptionFee": 19.95}
```

这就完成了示例映射模板转换。我们建议尽可能使用代理集成来转换数据，而不是使用映射模板转换。有关更多信息，请参阅 [选择 API Gateway API 集成类型](api-gateway-api-integration-types.md)。

# API Gateway 中适用于 REST API 且无映射模板的有效载荷的方法请求行为
<a name="integration-passthrough-behaviors"></a>

如果方法请求有一个有效载荷，而您没有为 `Content-Type` 标头定义映射模板，则可以选择通过集成请求将客户端提供的请求有效载荷传递到后端，而不进行转换。此过程称为集成传递。

 传入请求的实际传递行为由此设置决定。这里有三个选项：

**当没有模板与请求的 Content-Type 标头匹配时**  
如果您希望在方法请求内容类型不匹配任何与映射模板关联的内容类型时，将方法请求正文通过集成请求发送到后端而不进行转换，则选择此选项。  
调用 API Gateway API 时，您通过将 `WHEN_NO_MATCH` 设置为[集成](https://docs.aws.amazon.com/apigateway/latest/api/API_Integration.html)的 `passthroughBehavior` 属性值来选择此选项。

**未定义任何模板时（推荐）**  
如果您希望在集成请求中未定义映射模板时，将方法请求正文通过集成请求发送到后端而不进行转换，则选择此选项。如果在选择此选项时定义了模板，则具有与任何定义的映射模板都不匹配的有效载荷和内容类型的方法请求将遭到拒绝，并返回“HTTP 415 媒体类型不受支持”响应。  
调用 API Gateway API 时，您通过将 `WHEN_NO_TEMPLATES` 设置为[集成](https://docs.aws.amazon.com/apigateway/latest/api/API_Integration.html)的 `passthroughBehavior` 属性值来选择此选项。

**从不**  
如果您不希望在集成请求中未定义映射模板时，将方法请求正文通过集成请求发送到后端而不进行转换，则选择此选项。如果选择此选项时定义了模板，则会以“HTTP 415 Unsupported Media Type”响应拒绝未映射内容类型的方法请求。  
调用 API Gateway API 时，您通过将 `NEVER` 设置为[集成](https://docs.aws.amazon.com/apigateway/latest/api/API_Integration.html)的 `passthroughBehavior` 属性值来选择此选项。

 以下示例显示了可能的传递行为。

示例 1：`application/json` 内容类型的集成请求中定义了一个映射模板。


| Content-type | 传递选项 | 行为 | 
| --- | --- | --- | 
| 无 API Gateway 默认为 `application/json` | WHEN\$1NO\$1MATCH | 使用模板转换请求负载。 | 
| 无 API Gateway 默认为 `application/json` | WHEN\$1NO\$1TEMPLATES | 使用模板转换请求负载。 | 
| 无 API Gateway 默认为 `application/json` | NEVER | 使用模板转换请求负载。 | 
| application/json | WHEN\$1NO\$1MATCH | 使用模板转换请求负载。 | 
| application/json | WHEN\$1NO\$1TEMPLATES | 使用模板转换请求负载。 | 
| application/json | NEVER | 使用模板转换请求负载。 | 
| application/xml | WHEN\$1NO\$1MATCH | 请求负载未转换，并按原样发送到后端。 | 
| application/xml | WHEN\$1NO\$1TEMPLATES | 请求被拒绝，得到 HTTP 415 Unsupported Media Type 响应。 | 
| application/xml | NEVER | 请求被拒绝，得到 HTTP 415 Unsupported Media Type 响应。 | 

示例 2：`application/xml` 内容类型的集成请求中定义了一个映射模板。


| Content-type | 传递选项 | 行为 | 
| --- | --- | --- | 
| 无 API Gateway 默认为 `application/json` | WHEN\$1NO\$1MATCH | 请求负载未转换，并按原样发送到后端。 | 
| 无 API Gateway 默认为 `application/json` | WHEN\$1NO\$1TEMPLATES | 请求被拒绝，得到 HTTP 415 Unsupported Media Type 响应。 | 
| 无 API Gateway 默认为 `application/json` | NEVER | 请求被拒绝，得到 HTTP 415 Unsupported Media Type 响应。 | 
| application/json | WHEN\$1NO\$1MATCH | 请求负载未转换，并按原样发送到后端。 | 
| application/json | WHEN\$1NO\$1TEMPLATES | 请求被拒绝，得到 HTTP 415 Unsupported Media Type 响应。 | 
| application/json | NEVER | 请求被拒绝，得到 HTTP 415 Unsupported Media Type 响应。 | 
| application/xml | WHEN\$1NO\$1MATCH | 使用模板转换请求负载。 | 
| application/xml | WHEN\$1NO\$1TEMPLATES | 使用模板转换请求负载。 | 
| application/xml | NEVER | 使用模板转换请求负载。 | 

示例 3：集成请求中未定义映射模板。


| Content-type | 传递选项 | 行为 | 
| --- | --- | --- | 
| 无 API Gateway 默认为 `application/json` | WHEN\$1NO\$1MATCH | 请求负载未转换，并按原样发送到后端。 | 
| 无 API Gateway 默认为 `application/json` | WHEN\$1NO\$1TEMPLATES | 请求负载未转换，并按原样发送到后端。 | 
| 无 API Gateway 默认为 `application/json` | NEVER | 请求被拒绝，得到 HTTP 415 Unsupported Media Type 响应。 | 
| application/json | WHEN\$1NO\$1MATCH | 请求负载未转换，并按原样发送到后端。 | 
| application/json | WHEN\$1NO\$1TEMPLATES | 请求负载未转换，并按原样发送到后端。 | 
| application/json | NEVER | 请求被拒绝，得到 HTTP 415 Unsupported Media Type 响应。 | 
| application/xml | WHEN\$1NO\$1MATCH | 请求负载未转换，并按原样发送到后端。 | 
| application/xml | WHEN\$1NO\$1TEMPLATES | 请求负载未转换，并按原样发送到后端。 | 
| application/xml | NEVER | 请求被拒绝，得到 HTTP 415 Unsupported Media Type 响应。 | 

# API Gateway 中 REST API 的附加映射模板示例
<a name="example-photos"></a>

以下示例显示了 API Gateway 中的相册 API，该 API 使用映射模板转换集成请求和集成响应数据。它还使用数据模型来定义方法请求和集成响应有效载荷。有关数据模型的更多信息，请参阅[针对 REST API 的数据模型](models-mappings-models.md)。

## 方法请求和集成请求
<a name="example-photos-request"></a>

以下是定义方法请求正文的模型。此输入模型要求调用方上传一张照片页面，每页至少需要 10 张照片。您可以使用此输入模型生成 SDK 或为您的 API 使用请求验证。在使用请求验证时，如果方法请求正文不符合模型的数据结构，则 API Gateway 会使请求失败。

```
{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "title": "PhotosInputModel",
  "type": "object",
  "properties": {
    "photos": {
      "type": "object",
      "required" : [
      "photo"
      ],
      "properties": {
        "page": { "type": "integer" },
        "pages": { "type": "string" },
        "perpage": { "type": "integer", "minimum" : 10 },
        "total": { "type": "string" },
        "photo": {
          "type": "array",
          "items": {
            "type": "object",
            "properties": {
              "id": { "type": "string" },
              "owner": { "type": "string" },
              "photographer_first_name" : {"type" : "string"},
              "photographer_last_name" : {"type" : "string"},
              "secret": { "type": "string" },
              "server": { "type": "string" },
              "farm": { "type": "integer" },
              "title": { "type": "string" },
              "ispublic": { "type": "boolean" },
              "isfriend": { "type": "boolean" },
              "isfamily": { "type": "boolean" }
            }
          }
        }
      }
    }
  }
}
```

以下是遵循先前数据模型的数据结构的方法请求正文示例。

```
{
  "photos": {
    "page": 1,
    "pages": "1234",
    "perpage": 100,
    "total": "123398",
    "photo": [
      {
        "id": "12345678901",
        "owner": "23456789@A12",
        "photographer_first_name" : "Saanvi",
        "photographer_last_name" : "Sarkar",
        "secret": "abc123d456",
        "server": "1234",
        "farm": 1,
        "title": "Sample photo 1",
        "ispublic": true,
        "isfriend": false,
        "isfamily": false
      },
      {
        "id": "23456789012",
        "owner": "34567890@B23",
        "photographer_first_name" : "Richard",
        "photographer_last_name" : "Roe",
        "secret": "bcd234e567",
        "server": "2345",
        "farm": 2,
        "title": "Sample photo 2",
        "ispublic": true,
        "isfriend": false,
        "isfamily": false
      }
    ]
  }
}
```

在此示例中，如果之前的方法请求正文是由客户端提交的，则此映射模板会转换有效载荷，以匹配集成端点所需的格式。

```
#set($inputRoot = $input.path('$'))
{
  "photos": [
#foreach($elem in $inputRoot.photos.photo)
    {
      "id": "$elem.id",
      "photographedBy": "$elem.photographer_first_name $elem.photographer_last_name",
      "title": "$elem.title",
      "ispublic": $elem.ispublic,
      "isfriend": $elem.isfriend,
      "isfamily": $elem.isfamily
    }#if($foreach.hasNext),#end
		
#end
  ]
}
```

以下示例是来自转换的输出数据：

```
{
  "photos": [
    {
      "id": "12345678901",
      "photographedBy": "Saanvi Sarkar",
      "title": "Sample photo 1",
      "ispublic": true,
      "isfriend": false,
      "isfamily": false
    },		
    {
      "id": "23456789012",
      "photographedBy": "Richard Roe",
      "title": "Sample photo 2",
      "ispublic": true,
      "isfriend": false,
      "isfamily": false
    }		
  ]
}
```

这些数据发送到集成请求，然后发送到集成端点。

## 集成响应和方法响应
<a name="photos-example-response"></a>

以下是来自集成端点的照片数据的输出模型示例。您可以将此模型用于方法响应模型，这在为 API 生成强类型 SDK 时是必需的。这会导致输出将在 Java 或 Objective-C 中强制转换为适当的类。

```
{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "title": "PhotosOutputModel",
  "type": "object",
  "properties": {
    "photos": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "id": { "type": "string" },
          "photographedBy": { "type": "string" },
          "title": { "type": "string" },
          "ispublic": { "type": "boolean" },
          "isfriend": { "type": "boolean" },
          "isfamily": { "type": "boolean" }
        }
      }
    }
  }
}
```

集成端点可能不会以符合此模型的数据结构的响应进行响应。例如，集成响应可能如下所示：

```
  "photos": [
    {
      "id": "12345678901",
      "photographedBy": "Saanvi Sarkar",
      "title": "Sample photo 1",
      "description": "My sample photo 1",
      "public": true,
      "friend": false,
      "family": false
    },		
    {
      "id": "23456789012",
      "photographedBy": "Richard Roe",
      "title": "Sample photo 2",
      "description": "My sample photo 1",
      "public": true,
      "friend": false,
      "family": false
    }		
  ]
}
```

以下示例映射模板将集成响应数据转换为方法响应所期望的格式：

```
#set($inputRoot = $input.path('$'))
{
  "photos": [
#foreach($elem in $inputRoot.photos.photo)
    {
      "id": "$elem.id",
      "photographedBy": "$elem.photographer_first_name $elem.photographer_last_name",
      "title": "$elem.title",
      "ispublic": $elem.public,
      "isfriend": $elem.friend,
      "isfamily": $elem.family
    }#if($foreach.hasNext),#end
		
#end
  ]
}
```

以下示例是来自转换的输出数据：

```
{
  "photos": [
    {
      "id": "12345678901",
      "photographedBy": "Saanvi Sarkar",
      "title": "Sample photo 1",
      "ispublic": true,
      "isfriend": false,
      "isfamily": false
    },		
    {
      "id": "23456789012",
      "photographedBy": "Richard Roe",
      "title": "Sample photo 2",
      "ispublic": true,
      "isfriend": false,
      "isfamily": false
    }		
  ]
}
```

这些数据发送到方法响应，然后再发送回客户端。

# 针对 API Gateway 中的 REST API 覆盖 API 的请求和响应参数以及状态代码
<a name="apigateway-override-request-response-parameters"></a>

您可以使用映射模板转换来覆盖任何类型的请求参数、响应标头或响应状态代码。可以使用映射模板来执行以下操作：
+ 执行多对一参数映射
+ 在应用标准 API Gateway 映射后覆盖参数
+ 根据正文内容或其他参数值有条件地映射参数
+ 以编程方式创建新参数
+ 覆盖由集成端点返回的状态代码

覆盖是最终的。对于每个参数，覆盖只能应用一次。如果您多次尝试覆盖同一个参数，则 API Gateway 会返回 `5XX` 响应。如果您必须在整个模板中多次覆盖相同的参数，我们建议创建一个变量并在模板末尾应用覆盖。仅在解析整个模板后应用模板。

## 示例 1：基于集成正文覆盖状态代码
<a name="apigateway-override-request-response-examples"></a>

以下示例使用[示例 API](api-gateway-create-api-from-example.md) 基于集成响应正文覆盖状态代码。

------
#### [ AWS 管理控制台 ]

**基于集成响应正文覆盖状态代码**

1. 通过以下网址登录到 Amazon API Gateway 控制台：[https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway)。

1. 选择**创建 API**。

1. 对于 **REST API**，选择**构建**。

1. 对于 **API 详细信息**，选择**示例 API**。

1. 选择**创建 API**。

   API Gateway 创建一个示例宠物商店 API。要检索有关宠物的信息，您使用 API 方法请求 `GET /pets/{petId}`，其中 `{petId}` 是与宠物的 ID 号相对应的路径参数。

   在此示例中，当检测到错误条件时，您将 `GET` 方法的响应代码覆盖为 `400`。

1. 在**资源**树中，选择 `/{petId}` 下的 `GET` 方法。

1. 首先，测试 API 的当前实现。

   选择**测试**选项卡。您可能需要选择右箭头按钮，以显示该选项卡。

1. 对于 **petId**，输入 **-1**，然后选择**测试**。

   **响应正文**指示超出范围错误：

   ```
   {
     "errors": [
       {
         "key": "GetPetRequest.petId",
         "message": "The value is out of range."
       }
     ]
   }
   ```

   此外，**日志**下的最后一行的结尾为：`Method completed with status: 200`。

   集成已成功完成，但出现错误。现在，您将根据集成响应覆盖状态代码。

1. 在**集成响应**选项卡上，对于**默认 - 响应**，选择**编辑**。

1. 选择**映射模板**。

1. 选择**添加映射模板**。

1. 对于**内容类型**，输入 **application/json**。

1. 对于**模板正文**，输入以下内容：

   ```
   #set($inputRoot = $input.path('$'))
   $input.json("$")
   #if($inputRoot.toString().contains("error"))
   #set($context.responseOverride.status = 400)
   #end
   ```

   如果集成响应包含字符串 `error`，则此映射模板使用 `$context.responseOverride.status` 变量将状态代码覆盖为 `400`。

1. 选择**保存**。

1. 选择**测试**选项卡。

1. 对于 **petId**，输入 **-1**。

1. 在结果中，**响应正文**表示超出范围错误：

   ```
   {
     "errors": [
       {
         "key": "GetPetRequest.petId",
         "message": "The value is out of range."
       }
     ]
   }
   ```

   不过，**日志**下的最后一行现在的结尾为：`Method completed with status: 400`。

------
#### [ CloudFormation ]

 在此示例中，您使用 [body](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html#cfn-apigateway-restapi-body) 属性将 OpenAPI 定义文件导入到 API Gateway。

```
AWSTemplateFormatVersion: 2010-09-09
Resources:
  Api:
    Type: 'AWS::ApiGateway::RestApi'
    Properties:
      Body: 
        openapi: 3.0.1
        info:
          title: PetStore Example 1
          description: Example pet store API.
          version: "2025-01-14T00:13:18Z"
        paths:
          /pets/{petId}:
            get:
              parameters:
                - name: petId
                  in: path
                  required: true
                  schema:
                    type: string
              responses:
                "200":
                  description: 200 response
              x-amazon-apigateway-integration:
                httpMethod: GET
                uri: http://petstore.execute-api.us-east-1.amazonaws.com/petstore/pets/{petId}
                responses:
                  default:
                    statusCode: "200"
                    responseTemplates:
                      application/json: |-
                        #set($inputRoot = $input.path('$'))
                        $input.json("$")
                        #if($inputRoot.toString().contains("error"))
                        #set($context.responseOverride.status = 400)
                        #end
                requestParameters:
                  integration.request.path.petId: method.request.path.petId
                passthroughBehavior: when_no_match
                type: http
        components:
          schemas:
            Pet:
              type: object
              properties:
                id:
                  type: integer
                type:
                  type: string
                price:
                  type: number
  ApiGatewayDeployment:
    Type: 'AWS::ApiGateway::Deployment'
    DependsOn: Api 
    Properties: 
      RestApiId: !Ref Api
  ApiGatewayDeployment20250219:
    Type: 'AWS::ApiGateway::Deployment'
    DependsOn: Api 
    Properties: 
      RestApiId: !Ref Api
  Stage:
    Type: 'AWS::ApiGateway::Stage'
    Properties:
       DeploymentId: !Ref ApiGatewayDeployment20250219
       RestApiId: !Ref Api
       StageName: prod
```

------
#### [ OpenAPI ]

以下 OpenAPI 定义创建 `GET pets/{petId}` 资源并根据集成主体覆盖状态代码。

```
{
  "openapi" : "3.0.1",
  "info" : {
    "title" : "PetStore Example 1",
    "description" : "Example pet store API.",
    "version" : "2025-01-14T00:13:18Z"
  },
  "paths" : {
    "/pets/{petId}" : {
      "get" : {
        "parameters" : [ {
          "name" : "petId",
          "in" : "path",
          "required" : true,
          "schema" : {
            "type" : "string"
          }
        } ],
        "responses" : {
          "200" : {
            "description" : "200 response"
          }
        },
        "x-amazon-apigateway-integration" : {
          "httpMethod" : "GET",
          "uri" : "http://petstore.execute-api.us-east-1.amazonaws.com/petstore/pets/{petId}",
          "responses" : {
            "default" : {
              "statusCode" : "200",
              "responseTemplates" : {
                "application/json" : "#set($inputRoot = $input.path('$'))\n$input.json(\"$\")\n#if($inputRoot.toString().contains(\"error\"))\n#set($context.responseOverride.status = 400)\n#end"
              }
            }
          },
          "requestParameters" : {
            "integration.request.path.petId" : "method.request.path.petId"
          },
          "passthroughBehavior" : "when_no_match",
          "type" : "http"
        }
      }
    }
  },
  "components" : {
    "schemas" : {
      "Pet" : {
        "type" : "object",
        "properties" : {
          "id" : {
            "type" : "integer"
          },
          "type" : {
            "type" : "string"
          },
          "price" : {
            "type" : "number"
          }
        }
      }
    }
  }
}
```

------

## 示例 2：覆盖请求标头并创建新标头
<a name="apigateway-override-request-response-examples-2"></a>

以下示例使用[示例 API](api-gateway-create-api-from-example.md) 来覆盖请求标头并创建新的标头。

------
#### [ AWS 管理控制台 ]

**通过创建新标头覆盖方法的请求标头**

1. 通过以下网址登录到 Amazon API Gateway 控制台：[https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway)。

1. 选择您在先前教程中创建的示例 API。API 的名称应为 **PetStore**。

1. 在**资源**树中，选择 `/pet` 下的 `GET` 方法。

1. 在**方法请求**选项卡上，对于**方法请求设置**，选择**编辑**。

1. 选择 **HTTP 请求标头**，然后选择**添加标头**。

1. 对于**名称**，请输入 **header1**。

1. 选择**添加标头**，然后创建第二个标头，名为 **header2**。

1. 选择**保存**。

   现在，您可以使用映射模板将这些标头合并为一个标头值。

1. 在**集成请求**选项卡上，对于**集成请求设置**，选择**编辑**。

1. 对于**请求正文传递**，选择**当未定义模板时（推荐）**。

1. 选择**映射模板**，然后执行以下操作：

   1. 选择**添加映射模板**。

   1. 对于**内容类型**，输入 **application/json**。

   1. 对于**模板正文**，输入以下内容：

      ```
      #set($header1Override = "pets")
      #set($header3Value = "$input.params('header1')$input.params('header2')")
      $input.json("$")
      #set($context.requestOverride.header.header3 = $header3Value)
      #set($context.requestOverride.header.header1 = $header1Override)
      #set($context.requestOverride.header.multivalueheader=[$header1Override, $header3Value])
      ```

      此映射模板使用字符串 `pets` 覆盖 `header1`，并创建一个名为 `$header3Value` 的多值标头，该标头将 `header1` 和 `header2` 组合在一起。

1. 选择**保存**。

1. 选择**测试**选项卡。

1. 在**标头**下，复制以下代码：

   ```
   header1:header1Val
   header2:header2Val
   ```

1. 选择 **Test (测试)**。

   在**日志**中，您应看到一个包含此文本的条目：

   ```
   Endpoint request headers: {header3=header1Valheader2Val, 
   header2=header2Val, header1=pets, x-amzn-apigateway-api-id=api-id,
   Accept=application/json, multivalueheader=pets,header1Valheader2Val}
   ```

------
#### [ CloudFormation ]

 在此示例中，您使用 [body](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html#cfn-apigateway-restapi-body) 属性将 OpenAPI 定义文件导入到 API Gateway。

```
AWSTemplateFormatVersion: 2010-09-09
Resources:
  Api:
    Type: 'AWS::ApiGateway::RestApi'
    Properties:
      Body: 
        openapi: 3.0.1
        info:
          title: PetStore Example 2
          description: Example pet store API.
          version: "2025-01-14T00:36:18Z"
        paths:
          /pets:
            get:
              parameters:
                - name: header2
                  in: header
                  schema:
                    type: string
                - name: page
                  in: query
                  schema:
                    type: string
                - name: type
                  in: query
                  schema:
                    type: string
                - name: header1
                  in: header
                  schema:
                    type: string
              responses:
                "200":
                  description: 200 response
              x-amazon-apigateway-integration:
                httpMethod: GET
                uri: http://petstore.execute-api.us-east-1.amazonaws.com/petstore/pets
                responses:
                  default:
                    statusCode: "200"
                requestParameters:
                  integration.request.header.header1: method.request.header.header1
                  integration.request.header.header2: method.request.header.header2
                  integration.request.querystring.page: method.request.querystring.page
                  integration.request.querystring.type: method.request.querystring.type
                requestTemplates:
                  application/json: |-
                    #set($header1Override = "pets")
                    #set($header3Value = "$input.params('header1')$input.params('header2')")
                    $input.json("$")
                    #set($context.requestOverride.header.header3 = $header3Value)
                    #set($context.requestOverride.header.header1 = $header1Override)
                    #set($context.requestOverride.header.multivalueheader=[$header1Override, $header3Value])
                passthroughBehavior: when_no_match
                type: http
        components:
          schemas:
            Pet:
              type: object
              properties:
                id:
                  type: integer
                type:
                  type: string
                price:
                  type: number
  ApiGatewayDeployment:
    Type: 'AWS::ApiGateway::Deployment'
    DependsOn: Api 
    Properties: 
      RestApiId: !Ref Api
  ApiGatewayDeployment20250219:
    Type: 'AWS::ApiGateway::Deployment'
    DependsOn: Api 
    Properties: 
      RestApiId: !Ref Api
  Stage:
    Type: 'AWS::ApiGateway::Stage'
    Properties:
       DeploymentId: !Ref ApiGatewayDeployment20250219
       RestApiId: !Ref Api
       StageName: prod
```

------
#### [ OpenAPI ]

 以下 OpenAPI 定义创建 `GET pets` 资源，并覆盖请求标头和创建新的标头。

```
{
  "openapi" : "3.0.1",
  "info" : {
    "title" : "PetStore Example 2",
    "description" : "Example pet store API.",
    "version" : "2025-01-14T00:36:18Z"
  },
  "paths" : {
    "/pets" : {
      "get" : {
        "parameters" : [ {
          "name" : "header2",
          "in" : "header",
          "schema" : {
            "type" : "string"
          }
        }, {
          "name" : "page",
          "in" : "query",
          "schema" : {
            "type" : "string"
          }
        }, {
          "name" : "type",
          "in" : "query",
          "schema" : {
            "type" : "string"
          }
        }, {
          "name" : "header1",
          "in" : "header",
          "schema" : {
            "type" : "string"
          }
        } ],
        "responses" : {
          "200" : {
            "description" : "200 response"
          }
        },
        "x-amazon-apigateway-integration" : {
          "httpMethod" : "GET",
          "uri" : "http://petstore.execute-api.us-east-1.amazonaws.com/petstore/pets",
          "responses" : {
            "default" : {
              "statusCode" : "200"
            }
          },
          "requestParameters" : {
            "integration.request.header.header1" : "method.request.header.header1",
            "integration.request.header.header2" : "method.request.header.header2",
            "integration.request.querystring.page" : "method.request.querystring.page",
            "integration.request.querystring.type" : "method.request.querystring.type"
          },
          "requestTemplates" : {
            "application/json" : "#set($header1Override = \"pets\")\n#set($header3Value = \"$input.params('header1')$input.params('header2')\")\n$input.json(\"$\")\n#set($context.requestOverride.header.header3 = $header3Value)\n#set($context.requestOverride.header.header1 = $header1Override)\n#set($context.requestOverride.header.multivalueheader=[$header1Override, $header3Value])"
          },
          "passthroughBehavior" : "when_no_match",
          "type" : "http"
        }
      }
    }
  }
}
```

------

要使用映射模板覆盖，请添加以下一个或多个 `$context` 变量。有关 `$context` 变量的列表，请参阅[数据转换的上下文变量](api-gateway-mapping-template-reference.md#context-variable-reference)。

# 教程：修改集成请求和响应以集成到 AWS 服务
<a name="set-up-data-transformations-in-api-gateway"></a>

以下教程展示了如何使用映射模板转换来设置映射模板，以使用控制台和 AWS CLI 转换集成请求和响应。

**Topics**
+ [使用 API Gateway 控制台设置数据转换](#mapping-example-console)
+ [使用 AWS CLI 设置数据转换](#mapping-example-cli)
+ [已完成的数据转换 CloudFormation 模板](#api-gateway-data-transformations-full-cfn-stack)

## 使用 API Gateway 控制台设置数据转换
<a name="mapping-example-console"></a>

在本教程中，您将使用以下 .zip 文件 [data-transformation-tutorial-console.zip](samples/data-transformation-tutorial-console.zip) 创建不完整的 API 和 DynamoDB 表。这个不完整的 API 拥有的 `/pets` 资源具有 `GET` 和 `POST` 方法。
+ `GET` 方法将从 `http://petstore-demo-endpoint.execute-api.com/petstore/pets` HTTP 端点获取数据。输出数据将根据[API Gateway 中 REST API 的映射模板转换](models-mappings.md)中的映射模板进行转换。
+ `POST` 方法将允许用户使用映射模板将宠物信息 `POST` 到 Amazon DynamoDB 表中。

下载并解压缩[适用于 CloudFormation 的应用程序创建模板](samples/data-transformation-tutorial-console.zip)。您将使用此模板创建 DynamoDB 表来发布宠物信息和不完整的 API。您将在 API Gateway 控制台中完成其余步骤。

**创建 CloudFormation 堆栈**

1. 打开 CloudFormation 控制台，地址：[https://console.aws.amazon.com/cloudformation](https://console.aws.amazon.com/cloudformation/)。

1. 选择**创建堆栈**，然后选择**使用新资源(标准)**。

1. 对于**指定模板**，选择**上传模板文件**。

1. 选择您下载的模板。

1. 选择**下一步**。

1. 对于**堆栈名称**，输入 **data-transformation-tutorial-console**，然后选择**下一步**。

1. 对于**配置堆栈选项**，请选择**下一步**。

1. 对于**功能**，请确认 CloudFormation 可以在您的账户中创建 IAM 资源。

1. 选择**下一步**，然后选择**提交**。

CloudFormation 预置在模板中指定的资源。完成资源预置可能需要几分钟时间。当 CloudFormation 堆栈的状态为 **CREATE\$1COMPLETE** 时，您就可以继续下一步了。

**测试 `GET` 集成响应**

1. 在 **data-transformation-tutorial-console** 的 CloudFormation 堆栈的**资源**选项卡上，选择您的 API 的物理 ID。

1. 在主导航窗格中，选择**资源**，然后选择 **GET** 方法。

1. 选择**测试**选项卡。您可能需要选择右箭头按钮，以显示该选项卡。

   测试的输出将显示以下内容：

   ```
   [
     {
       "id": 1,
       "type": "dog",
       "price": 249.99
     },
     {
       "id": 2,
       "type": "cat",
       "price": 124.99
     },
     {
       "id": 3,
       "type": "fish",
       "price": 0.99
     }
   ]
   ```

   您将根据[API Gateway 中 REST API 的映射模板转换](models-mappings.md)中的映射模板转换此输出。

**转换 `GET` 集成响应**

1. 选择**集成响应**选项卡。

   目前，没有定义任何映射模板，因此不会转换集成响应。

1. 对于**默认 - 响应**，选择**编辑**。

1. 选择**映射模板**，然后执行以下操作：

   1. 选择**添加映射模板**。

   1. 对于**内容类型**，输入 **application/json**。

   1. 对于**模板正文**，输入以下内容：

      ```
      #set($inputRoot = $input.path('$'))
      [
      #foreach($elem in $inputRoot)
        {
          "description" : "Item $elem.id is a $elem.type.",
          "askingPrice" : $elem.price
        }#if($foreach.hasNext),#end
      
      #end
      ]
      ```

   选择**保存**。

**测试 `GET` 集成响应**
+ 选择**测试**选项卡，然后选择**测试**。

  测试的输出将显示转换后的响应。

  ```
  [
    {
      "description" : "Item 1 is a dog.",
      "askingPrice" : 249.99
    },
    {
      "description" : "Item 2 is a cat.",
      "askingPrice" : 124.99
    },
    {
      "description" : "Item 3 is a fish.",
      "askingPrice" : 0.99
    }
  ]
  ```

**转换来自 `POST` 方法的输入数据**

1. 选择 **POST** 方法。

1. 选择**集成请求**选项卡，然后对于**集成请求设置**，选择**编辑**。

   CloudFormation 模板已填充了一些集成请求字段。
   +  集成类型为 AWS 服务。
   +  AWS 服务是 DynamoDB。
   +  HTTP 方法为 `POST`。
   +  操作是 `PutItem`。
   +  允许 API Gateway 将项目放入 DynamoDB 表的执行角色是 `data-transformation-tutorial-console-APIGatewayRole`。CloudFormation 创建此角色以允许 API Gateway 拥有与 DynamoDB 交互的最低权限。

    尚未指定 DynamoDB 表的名称。您将在以下步骤中指定名称。

1. 对于**请求正文传递**，选择**从不**。

   这意味着 API 将拒绝其 Content-Type（内容类型）没有映射模板的数据。

1. 选择**映射模板**。

1. **内容类型**设置为 `application/json`。这意味着 API 将拒绝所有不是 application/json 的内容类型。有关集成传递行为的更多信息，请参阅[API Gateway 中适用于 REST API 且无映射模板的有效载荷的方法请求行为](integration-passthrough-behaviors.md)

1. 在文本编辑器中输入以下代码。

   ```
   {
       "TableName":"data-transformation-tutorial-console-ddb",
       "Item": {
           "id": {
               "N": $input.json("$.id")
           },
           "type": {
               "S": $input.json("$.type")
           },
           "price": {
               "N": $input.json("$.price")
           }
       }
   }
   ```

    此模板将表指定为 `data-transformation-tutorial-console-ddb` 并将项目设置为 `id`、`type` 和 `price`。这些项目将来自 `POST` 方法的正文。您也可以使用数据模型来帮助创建映射模板。有关更多信息，请参阅 [针对 API Gateway 中的 REST API 的请求验证](api-gateway-method-request-validation.md)。

1. 选择**保存**以保存映射模板。

**从 `POST` 方法添加方法和集成响应**

CloudFormation 创建了一个空白方法和集成响应。您将编辑此回复以提供更多信息。有关如何编辑响应的更多信息，请参阅[API Gateway 中 REST API 的参数映射示例](request-response-data-mappings.md)。

1. 在**集成响应**选项卡上，对于**默认 - 响应**，选择**编辑**。

1. 选择**映射模板**，然后选择**添加映射模板**。

1. 对于 **Content-Type**，输入 **application/json**。

1. 在代码编辑器中，输入以下输出映射模板以发送输出消息：

   ```
   { "message" : "Your response was recorded at $context.requestTime" }
   ```

   有关上下文变量的更多信息，请参阅[数据转换的上下文变量](api-gateway-mapping-template-reference.md#context-variable-reference)。

1. 选择**保存**以保存映射模板。

**测试 `POST` 方法**

选择**测试**选项卡。您可能需要选择右箭头按钮，以显示该选项卡。

1. 在请求正文中，输入以下示例。

   ```
   {
             "id": "4",
             "type" : "dog",
             "price": "321"
   }
   ```

1. 选择**测试**。

   输出应显示您的成功消息。

    您可以通过 [https://console.aws.amazon.com/dynamodb/](https://console.aws.amazon.com/dynamodb/) 打开 DynamoDB 控制台，以验证示例项目是否在您的表中。

**删除 CloudFormation 堆栈**

1. 打开 CloudFormation 控制台，地址：[https://console.aws.amazon.com/cloudformation](https://console.aws.amazon.com/cloudformation/)。

1. 选择您的 CloudFormation 堆栈。

1. 选择**删除**，然后确认您的选择。

## 使用 AWS CLI 设置数据转换
<a name="mapping-example-cli"></a>

在本教程中，您将使用以下 .zip 文件 [data-transformation-tutorial-cli.zip](samples/data-transformation-tutorial-cli.zip) 创建不完整的 API 和 DynamoDB 表。这个不完整的 API 所具有的 `/pets` 资源包含与 `http://petstore-demo-endpoint.execute-api.com/petstore/pets` HTTP 端点集成的 `GET` 方法。您将创建 `POST` 方法以连接到 DynamoDB 表，并使用映射模板将数据输入到 DynamoDB 表中。
+ 您将根据[API Gateway 中 REST API 的映射模板转换](models-mappings.md)中的映射模板转换输出数据。
+ 您将创建 `POST` 方法，以允许用户使用映射模板将宠物信息 `POST` 到 Amazon DynamoDB 表中。

**创建 CloudFormation 堆栈**

下载并解压缩[适用于 CloudFormation 的应用程序创建模板](samples/data-transformation-tutorial-cli.zip)。

要完成以下教程，您需要 [AWS Command Line Interface（AWS CLI）版本 2](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)。

对于长命令，使用转义字符 (`\`) 将命令拆分为多行。
**注意**  
在 Windows 中，操作系统的内置终端不支持您经常使用的某些 Bash CLI 命令（例如 `zip`）。[安装 Windows Subsystem for Linux](https://learn.microsoft.com/en-us/windows/wsl/install)，获取 Ubuntu 和 Bash 与 Windows 集成的版本。本指南中的示例 CLI 命令使用 Linux 格式。如果您使用的是 Windows CLI，则必须重新格式化包含内联 JSON 文档的命令。

1.  输入以下命令创建 CloudFormation 堆栈。

   ```
   aws cloudformation create-stack --stack-name data-transformation-tutorial-cli --template-body file://data-transformation-tutorial-cli.zip --capabilities CAPABILITY_NAMED_IAM 
   ```

1. CloudFormation 预置在模板中指定的资源。完成资源预置可能需要几分钟时间。使用以下命令查看 CloudFormation 的状态。

   ```
   aws cloudformation describe-stacks --stack-name data-transformation-tutorial-cli
   ```

1. 当 CloudFormation 堆栈的状态为 `StackStatus: "CREATE_COMPLETE"` 时，使用以下命令检索将来步骤的相关输出值。

   ```
    aws cloudformation describe-stacks --stack-name data-transformation-tutorial-cli --query "Stacks[*].Outputs[*].{OutputKey: OutputKey, OutputValue: OutputValue, Description: Description}"
   ```

   输出值包括：
   + ApiRole，这是允许 API Gateway 在 DynamoDB 表中放置项目的角色名称。对于本教程，角色名称为 `data-transformation-tutorial-cli-APIGatewayRole-ABCDEFG`。
   + DDBTableName，这是 DynamoDB 表的名称。对于本教程，表名称为 `data-transformation-tutorial-cli-ddb`
   + ResourceId，这是公开 `GET` 和 `POST` 方法的宠物资源的 ID。对于本教程，资源 ID 为 `efg456`
   + ApiId，这是 API 的 ID。对于本教程，API ID 为 `abc123`。

**在数据转换之前测试 `GET` 方法**
+ 使用以下命令测试 `GET` 方法。

  ```
  aws apigateway test-invoke-method --rest-api-id abc123 \
            --resource-id efg456 \
            --http-method GET
  ```

  测试的输出将显示以下内容。

  ```
  [
    {
      "id": 1,
      "type": "dog",
      "price": 249.99
    },
    {
      "id": 2,
      "type": "cat",
      "price": 124.99
    },
    {
      "id": 3,
      "type": "fish",
      "price": 0.99
    }
  ]
  ```

  您将根据[API Gateway 中 REST API 的映射模板转换](models-mappings.md)中的映射模板转换此输出。

**转换 `GET` 集成响应**
+ 使用以下命令更新 `GET` 方法的集成响应。将 *rest-api-id* 和 *resource-id* 替换为您的值。

  使用以下命令创建集成响应。

  ```
  aws apigateway put-integration-response --rest-api-id abc123 \
    --resource-id efg456 \
    --http-method GET \
    --status-code 200 \
    --selection-pattern "" \
    --response-templates '{"application/json": "#set($inputRoot = $input.path(\"$\"))\n[\n#foreach($elem in $inputRoot)\n {\n  \"description\": \"Item $elem.id is a $elem.type\",\n  \"askingPrice\": \"$elem.price\"\n }#if($foreach.hasNext),#end\n\n#end\n]"}'
  ```

**测试 `GET` 方法**
+ 使用以下命令测试 `GET` 方法。

  ```
  aws apigateway test-invoke-method --rest-api-id abc123 \
    --resource-id efg456 \
    --http-method GET \
  ```

  测试的输出将显示转换后的响应。

  ```
  [
    {
      "description" : "Item 1 is a dog.",
      "askingPrice" : 249.99
    },
    {
      "description" : "Item 2 is a cat.",
      "askingPrice" : 124.99
    },
    {
      "description" : "Item 3 is a fish.",
      "askingPrice" : 0.99
    }
  ]
  ```

**创建 `POST` 方法**

1. 使用以下命令在您的 `/pets` 资源上创建新的方法。

   ```
   aws apigateway put-method --rest-api-id abc123 \
     --resource-id efg456 \
     --http-method POST \
     --authorization-type "NONE" \
   ```

   此方法允许您将宠物信息发送到您在 CloudFormation 堆栈中创建的 DynamoDB 表。

1.  使用以下命令在 `POST` 方法上创建 AWS 服务 集成。

   ```
   aws apigateway put-integration --rest-api-id abc123 \
     --resource-id efg456 \
     --http-method POST \
     --type AWS \
     --integration-http-method POST \
     --uri "arn:aws:apigateway:us-east-2:dynamodb:action/PutItem" \
     --credentials arn:aws:iam::111122223333:role/data-transformation-tutorial-cli-APIGatewayRole-ABCDEFG \
     --request-templates '{"application/json":"{\"TableName\":\"data-transformation-tutorial-cli-ddb\",\"Item\":{\"id\":{\"N\":$input.json(\"$.id\")},\"type\":{\"S\":$input.json(\"$.type\")},\"price\":{\"N\":$input.json(\"$.price\")} }}"}'
   ```

1.  使用以下命令为成功调用 `POST` 方法创建方法响应。

   ```
   aws apigateway put-method-response --rest-api-id abc123 \
     --resource-id efg456 \
     --http-method POST \
     --status-code 200
   ```

1. 使用以下命令为成功调用 `POST` 方法创建集成响应。

   ```
   aws apigateway put-integration-response --rest-api-id abc123 \
     --resource-id efg456 \
     --http-method POST \
     --status-code 200 \
     --selection-pattern "" \
     --response-templates '{"application/json": "{\"message\": \"Your response was recorded at $context.requestTime\"}"}'
   ```

**测试 `POST` 方法**
+ 使用以下命令测试 `POST` 方法。

  ```
  aws apigateway test-invoke-method --rest-api-id abc123 \
    --resource-id efg456 \
    --http-method POST \
    --body '{\"id\": \"4\", \"type\": \"dog\", \"price\": \"321\"}'
  ```

  输出将显示成功消息。

**删除 CloudFormation 堆栈**
+ 使用以下命令删除您的 CloudFormation 资源。

  ```
  aws cloudformation delete-stack  --stack-name data-transformation-tutorial-cli
  ```

## 已完成的数据转换 CloudFormation 模板
<a name="api-gateway-data-transformations-full-cfn-stack"></a>

以下示例是一个已完成的 CloudFormation 模板，它创建了一个 API 和一个 DynamoDB 表，该表的 `/pets` 资源具有 `GET` 和 `POST` 方法。
+ `GET` 方法将从 `http://petstore-demo-endpoint.execute-api.com/petstore/pets` HTTP 端点获取数据。输出数据将根据[API Gateway 中 REST API 的映射模板转换](models-mappings.md)中的映射模板进行转换。
+ `POST` 方法将允许用户使用映射模板将宠物信息 `POST` 到 DynamoDB 表中。

### 示例 CloudFormation 模板
<a name="mapping-template-cfn-example"></a>

```
AWSTemplateFormatVersion: 2010-09-09
Description: A completed Amazon API Gateway REST API that uses non-proxy integration to POST to an Amazon DynamoDB table and non-proxy integration to GET transformed pets data.
Parameters:
  StageName:
    Type: String
    Default: v1
    Description: Name of API stage.
Resources:
  DynamoDBTable:
    Type: 'AWS::DynamoDB::Table'
    Properties:
      TableName: !Sub data-transformation-tutorial-complete
      AttributeDefinitions:
        - AttributeName: id
          AttributeType: N
      KeySchema:
        - AttributeName: id
          KeyType: HASH
      ProvisionedThroughput:
        ReadCapacityUnits: 5
        WriteCapacityUnits: 5
  APIGatewayRole:
    Type: 'AWS::IAM::Role'
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17		 	 	 
        Statement:
          - Action:
              - 'sts:AssumeRole'
            Effect: Allow
            Principal:
              Service:
                - apigateway.amazonaws.com
      Policies:
        - PolicyName: APIGatewayDynamoDBPolicy
          PolicyDocument:
            Version: 2012-10-17		 	 	 
            Statement:
              - Effect: Allow
                Action:
                  - 'dynamodb:PutItem'
                Resource: !GetAtt DynamoDBTable.Arn
  Api:
    Type: 'AWS::ApiGateway::RestApi'
    Properties:
      Name: data-transformation-complete-api
      ApiKeySourceType: HEADER
  PetsResource:
    Type: 'AWS::ApiGateway::Resource'
    Properties:
      RestApiId: !Ref Api
      ParentId: !GetAtt Api.RootResourceId
      PathPart: 'pets'
  PetsMethodGet:
    Type: 'AWS::ApiGateway::Method'
    Properties:
      RestApiId: !Ref Api
      ResourceId: !Ref PetsResource
      HttpMethod: GET
      ApiKeyRequired: false
      AuthorizationType: NONE
      Integration:
        Type: HTTP
        Credentials: !GetAtt APIGatewayRole.Arn
        IntegrationHttpMethod: GET
        Uri: http://petstore-demo-endpoint.execute-api.com/petstore/pets/
        PassthroughBehavior: WHEN_NO_TEMPLATES
        IntegrationResponses:
          - StatusCode: '200'
            ResponseTemplates:
              application/json: "#set($inputRoot = $input.path(\"$\"))\n[\n#foreach($elem in $inputRoot)\n {\n  \"description\": \"Item $elem.id is a $elem.type\",\n  \"askingPrice\": \"$elem.price\"\n }#if($foreach.hasNext),#end\n\n#end\n]"
      MethodResponses:
        - StatusCode: '200'
  PetsMethodPost:
    Type: 'AWS::ApiGateway::Method'
    Properties:
      RestApiId: !Ref Api
      ResourceId: !Ref PetsResource
      HttpMethod: POST
      ApiKeyRequired: false
      AuthorizationType: NONE
      Integration:
        Type: AWS
        Credentials: !GetAtt APIGatewayRole.Arn
        IntegrationHttpMethod: POST
        Uri: arn:aws:apigateway:us-west-1:dynamodb:action/PutItem
        PassthroughBehavior: NEVER
        RequestTemplates: 
          application/json: "{\"TableName\":\"data-transformation-tutorial-complete\",\"Item\":{\"id\":{\"N\":$input.json(\"$.id\")},\"type\":{\"S\":$input.json(\"$.type\")},\"price\":{\"N\":$input.json(\"$.price\")} }}"
        IntegrationResponses:
          - StatusCode: 200
            ResponseTemplates:
              application/json: "{\"message\": \"Your response was recorded at $context.requestTime\"}"
      MethodResponses:
        - StatusCode: '200'

  ApiDeployment:
    Type: 'AWS::ApiGateway::Deployment'
    DependsOn:
      - PetsMethodGet
    Properties:
      RestApiId: !Ref Api
      StageName: !Sub '${StageName}'
Outputs:
  ApiId:
    Description: API ID for CLI commands
    Value: !Ref Api
  ResourceId:
    Description: /pets resource ID for CLI commands
    Value: !Ref PetsResource
  ApiRole:
    Description: Role ID to allow API Gateway to put and scan items in DynamoDB table
    Value: !Ref APIGatewayRole
  DDBTableName:
    Description: DynamoDB table name
    Value: !Ref DynamoDBTable
```

# 使用变量来映射 API Gateway 的模板转换的示例
<a name="api-gateway-mapping-variable-examples"></a>

以下示例显示了如何在映射模板中使用 `$context`、`input` 和 `util` 变量。您可以使用模拟集成或用于将输入事件返回到 API Gateway 的 Lambda 非代理集成。有关数据转换的所有支持的变量的列表，请参阅 [API Gateway 的用于数据转换的变量](api-gateway-mapping-template-reference.md)。

## 示例 1：将多个 `$context` 变量传递到集成端点
<a name="context-variables-template-example"></a>

以下示例显示了一个映射模板，该模板将传入的 `$context` 变量映射到后端变量，这些变量在集成请求负载中的名称稍有不同：

```
{
    "stage" : "$context.stage",
    "request_id" : "$context.requestId",
    "api_id" : "$context.apiId",
    "resource_path" : "$context.resourcePath",
    "resource_id" : "$context.resourceId",
    "http_method" : "$context.httpMethod",
    "source_ip" : "$context.identity.sourceIp",
    "user-agent" : "$context.identity.userAgent",
    "account_id" : "$context.identity.accountId",
    "api_key" : "$context.identity.apiKey",
    "caller" : "$context.identity.caller",
    "user" : "$context.identity.user",
    "user_arn" : "$context.identity.userArn"
}
```

此映射模板的输出应与以下内容类似：

```
{
  stage: 'prod',
  request_id: 'abcdefg-000-000-0000-abcdefg',
  api_id: 'abcd1234',
  resource_path: '/',
  resource_id: 'efg567',
  http_method: 'GET',
  source_ip: '192.0.2.1',
  user-agent: 'curl/7.84.0',
  account_id: '111122223333',
  api_key: 'MyTestKey',
  caller: 'ABCD-0000-12345',
  user: 'ABCD-0000-12345',
  user_arn: 'arn:aws:sts::111122223333:assumed-role/Admin/carlos-salazar'
}
```

其中一个变量是 API 密钥。此示例假设方法需要 API 密钥。

## 示例 2：通过 JSON 有效载荷将所有请求参数传递给集成端点
<a name="input-examples-mapping-templates"></a>

以下示例通过 JSON 有效载荷将所有请求参数（包括 `path`、`querystring` 和 `header` 参数）传递到集成端点：

```
#set($allParams = $input.params())
{
  "params" : {
    #foreach($type in $allParams.keySet())
    #set($params = $allParams.get($type))
    "$type" : {
      #foreach($paramName in $params.keySet())
      "$paramName" : "$util.escapeJavaScript($params.get($paramName))"
      #if($foreach.hasNext),#end
      #end
    }
    #if($foreach.hasNext),#end
    #end
  }
}
```

如果请求具有以下输入参数：
+ 名为 `myparam` 的路径参数
+ 查询字符串参数 `querystring1=value1,value2`
+ 标头 `"header1" : "value1"`。

此映射模板的输出应与以下内容类似：

```
{"params":{"path":{"example2":"myparamm"},"querystring":{"querystring1":"value1,value2"},"header":{"header1":"value1"}}}
```

## 示例 3：将方法请求的一部分传递给集成端点
<a name="input-example-json-mapping-template"></a>

 以下示例使用输入参数 `name` 仅检索 `name` 参数，并使用输入参数 `input.json('$')` 检索方法请求的整个正文：

```
{
    "name" : "$input.params('name')",
    "body" : $input.json('$') 
}
```

对于包含查询字符串参数 `name=Bella&type=dog` 和以下正文的请求：

```
{
    "Price" : "249.99",
    "Age": "6"
}
```

此映射模板的输出应与以下内容类似：

```
{
    "name" : "Bella",
    "body" : {"Price":"249.99","Age":"6"}
}
```

此映射模板移除了查询字符串参数 `type=dog`。

 如果 JSON 输入包含无法通过 JavaScript 解析的非转义字符，则 API Gateway 可能会返回 400 响应。应用 `$util.escapeJavaScript($input.json('$'))` 来确保正确解析 JSON 输入。

上面的示例在应用了 `$util.escapeJavaScript($input.json('$'))` 之后会如下所示：

```
{
    "name" : "$input.params('name')",
    "body" : "$util.escapeJavaScript($input.json('$'))"
}
```

在这种情况下，此映射模板的输出应与以下内容类似：

```
{
    "name" : "Bella",
    "body": {"Price":"249.99","Age":"6"}
}
```

## 示例 4：使用 JSONPath 表达式将方法请求的一部分传递给集成端点
<a name="input-example-inputs-mapping-template"></a>

以下示例使用 JSONPath 表达式从请求正文中仅检索输入参数 `name` 和 `Age`：

```
{
    "name" : "$input.params('name')",
    "body" : $input.json('$.Age')  
}
```

对于包含查询字符串参数 `name=Bella&type=dog` 和以下正文的请求：

```
{
    "Price" : "249.99",
    "Age": "6"
}
```

此映射模板的输出应与以下内容类似：

```
{
    "name" : "Bella",
    "body" : "6"
}
```

此映射模板从正文中移除查询字符串参数 `type=dog` 和 `Price` 字段。

 如果方法请求负载包含无法通过 JavaScript 解析的非转义字符，则 API Gateway 可能会返回 `400` 响应。应用 `$util.escapeJavaScript()` 来确保正确解析 JSON 输入。

上面的示例在应用了 `$util.escapeJavaScript($input.json('$.Age'))` 之后会如下所示：

```
{
    "name" : "$input.params('name')",
    "body" : "$util.escapeJavaScript($input.json('$.Age'))" 
}
```

在这种情况下，此映射模板的输出应与以下内容类似：

```
{
    "name" : "Bella",
    "body": "\"6\""
}
```

## 示例 5：使用 JSONPath 表达式将有关方法请求的信息传递到集成端点
<a name="input-example-request-and-response"></a>

以下示例使用 `$input.params()`、`$input.path()` 和 `$input.json()` 向集成端点发送有关方法请求的信息。此映射模板使用 `size()` 方法来提供列表中元素的数量。

```
{
    "id" : "$input.params('id')",
    "count" : "$input.path('$.things').size()",
    "things" : $input.json('$.things')
}
```

对于包含路径参数 `123` 和以下正文的请求：

```
{
      "things": {
            "1": {},
            "2": {},
            "3": {}
      }
}
```

此映射模板的输出应与以下内容类似：

```
{"id":"123","count":"3","things":{"1":{},"2":{},"3":{}}}
```

 如果方法请求负载包含无法通过 JavaScript 解析的非转义字符，则 API Gateway 可能会返回 `400` 响应。应用 `$util.escapeJavaScript()` 来确保正确解析 JSON 输入。

上面的示例在应用了 `$util.escapeJavaScript($input.json('$.things'))` 之后会如下所示：

```
{
     "id" : "$input.params('id')",
     "count" : "$input.path('$.things').size()",
     "things" : "$util.escapeJavaScript($input.json('$.things'))"
}
```

此映射模板的输出应与以下内容类似：

```
{"id":"123","count":"3","things":"{\"1\":{},\"2\":{},\"3\":{}}"}
```

# 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 编码字符串中的数据进行解码。 | 