

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

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

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

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

------
#### [ Amazon Web Services 管理控制台 ]

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

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

1. 选择一个 REST API。

1. 选择方法。

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

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

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

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

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

1. 选择**保存**。

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

   Amazon Web Services 管理控制台会自动为您添加从 `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`。

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

 在此示例中，您使用 [body](https://docs.amazonaws.cn/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`。

------
#### [ Amazon Web Services 管理控制台 ]

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

1. 通过以下网址登录到 Amazon API Gateway 控制台：[https://console.aws.amazon.com/apigateway](https://console.amazonaws.cn/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 以使更改生效。

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

 在此示例中，您使用 [body](https://docs.amazonaws.cn/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 
  }
]
```

------
#### [ Amazon Web Services 管理控制台 ]

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

1. 通过以下网址登录到 Amazon API Gateway 控制台：[https://console.aws.amazon.com/apigateway](https://console.amazonaws.cn/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 以使更改生效。

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

 在此示例中，您使用 [body](https://docs.amazonaws.cn/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`。

------
#### [ Amazon Web Services 管理控制台 ]

**映射集成响应**

1. 通过以下网址登录到 Amazon API Gateway 控制台：[https://console.aws.amazon.com/apigateway](https://console.amazonaws.cn/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 以使更改生效。

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

 在此示例中，您使用 [body](https://docs.amazonaws.cn/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
        }
      }
    }
  }
}
```

------