

# 针对 API Gateway 中的 REST API 的 HTTP 集成
<a name="setup-http-integrations"></a>

 您可以使用 HTTP 代理集成或 HTTP 自定义集成将 API 方法与 HTTP 终端节点进行集成。

API Gateway 支持以下终端节点端口：80、443 和 1024-65535。

 借助代理集成，进行设置非常简单。如果不考虑内容编码或缓存，则只需根据后端要求设置 HTTP 方法和 HTTP 终端节点 URI。

 借助自定义集成，进行设置更为复杂。除了执行代理集成设置步骤，还需要指定如何将传入请求数据映射到集成请求以及如何将生成的集成响应数据映射到方法响应。

**Topics**
+ [在 API Gateway 中设置 HTTP 代理集成](#api-gateway-set-up-http-proxy-integration-on-proxy-resource)
+ [在 API Gateway 中设置 HTTP 自定义集成](#set-up-http-custom-integrations)

## 在 API Gateway 中设置 HTTP 代理集成
<a name="api-gateway-set-up-http-proxy-integration-on-proxy-resource"></a>

要设置具有 HTTP 代理集成类型的代理资源，请创建一个具有“贪婪”路径参数（例如，`/parent/{proxy+}`）的 API 资源，并将该资源与 `https://petstore-demo-endpoint.execute-api.com/petstore/{proxy}` 方法上的 HTTP 后端终端节点（例如，`ANY`）集成。“贪婪”路径参数必须位于资源路径的末尾。

与处理非代理资源一样，您可以通过 API Gateway 控制台、导入 OpenAPI 定义文件或直接调用 API Gateway REST API 来设置具有 HTTP 代理集成的代理资源。有关使用 API Gateway 控制台配置与 HTTP 集成的代理资源的详细说明，请参阅 [教程：利用 HTTP 代理集成创建 REST API](api-gateway-create-api-as-simple-proxy-for-http.md)。

以下 OpenAPI 定义文件显示了一个 API 的示例，该 API 具有与 [PetStore](http://petstore-demo-endpoint.execute-api.com/petstore/pets) 网站集成的代理资源。

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

```
{
   "openapi": "3.0.0",
   "info": {
      "version": "2016-09-12T23:19:28Z",
      "title": "PetStoreWithProxyResource"
   },
   "paths": {
      "/{proxy+}": {
         "x-amazon-apigateway-any-method": {
            "parameters": [
               {
                  "name": "proxy",
                  "in": "path",
                  "required": true,
                  "schema": {
                     "type": "string"
                  }
               }
            ],
            "responses": {},
            "x-amazon-apigateway-integration": {
               "responses": {
                  "default": {
                     "statusCode": "200"
                  }
               },
               "requestParameters": {
                  "integration.request.path.proxy": "method.request.path.proxy"
               },
               "uri": "http://petstore-demo-endpoint.execute-api.com/petstore/{proxy}",
               "passthroughBehavior": "when_no_match",
               "httpMethod": "ANY",
               "cacheNamespace": "rbftud",
               "cacheKeyParameters": [
                  "method.request.path.proxy"
               ],
               "type": "http_proxy"
            }
         }
      }
   },
   "servers": [
      {
         "url": "https://4z9giyi2c1.execute-api.us-east-1.amazonaws.com/{basePath}",
         "variables": {
            "basePath": {
              "default": "/test"
            }
         }
      }
   ]
}
```

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

```
{
  "swagger": "2.0",
  "info": {
    "version": "2016-09-12T23:19:28Z",
    "title": "PetStoreWithProxyResource"
  },
  "host": "4z9giyi2c1.execute-api.us-east-1.amazonaws.com",
  "basePath": "/test",
  "schemes": [
    "https"
  ],
  "paths": {
    "/{proxy+}": {
      "x-amazon-apigateway-any-method": {
        "produces": [
          "application/json"
        ],
        "parameters": [
          {
            "name": "proxy",
            "in": "path",
            "required": true,
            "type": "string"
          }
        ],
        "responses": {},
        "x-amazon-apigateway-integration": {
          "responses": {
            "default": {
              "statusCode": "200"
            }
          },
          "requestParameters": {
            "integration.request.path.proxy": "method.request.path.proxy"
          },
          "uri": "http://petstore-demo-endpoint.execute-api.com/petstore/{proxy}",
          "passthroughBehavior": "when_no_match",
          "httpMethod": "ANY",
          "cacheNamespace": "rbftud",
          "cacheKeyParameters": [
            "method.request.path.proxy"
          ],
          "type": "http_proxy"
        }
      }
    }
  }
}
```

------

在本示例中，代理资源的 `method.request.path.proxy` 路径参数上声明了一个缓存键。这是您使用 API Gateway 控制台创建 API 时的默认设置。API 的基本路径 (`/test`，与一个阶段对应) 映射到网站的 PetStore 页面 (`/petstore`)。单个集成请求可以使用 API 的“贪婪”路径变量和“捕获所有”的 `ANY` 方法镜像整个 PetStore 网站。建立镜像的过程如下所示。
+ **将 `ANY` 设置为 `GET` 并将 `{proxy+}` 设置为 `pets`**

  从前端发起的方法请求：

  ```
  GET https://4z9giyi2c1.execute-api.us-west-2.amazonaws.com/test/pets HTTP/1.1
  ```

  发送到后端的集成请求：

  ```
  GET http://petstore-demo-endpoint.execute-api.com/petstore/pets HTTP/1.1
  ```

  `ANY` 方法和代理资源的运行时实例都是有效的。此调用将返回一个 `200 OK` 响应以及包含从后端返回的第一批宠物的负载。
+ **将 `ANY` 设置为 `GET` 并将 `{proxy+}` 设置为 `pets?type=dog`**

  ```
  GET https://4z9giyi2c1.execute-api.us-west-2.amazonaws.com/test/pets?type=dog HTTP/1.1
  ```

  发送到后端的集成请求：

  ```
  GET http://petstore-demo-endpoint.execute-api.com/petstore/pets?type=dog HTTP/1.1
  ```

  `ANY` 方法和代理资源的运行时实例都是有效的。此调用将返回一个 `200 OK` 响应以及包含从后端返回的第一批指定宠物狗的负载。
+ **将 `ANY` 设置为 `GET` 并将 `{proxy+}` 设置为 `pets/{petId}`**

  从前端发起的方法请求：

  ```
  GET https://4z9giyi2c1.execute-api.us-west-2.amazonaws.com/test/pets/1 HTTP/1.1
  ```

  发送到后端的集成请求：

  ```
  GET http://petstore-demo-endpoint.execute-api.com/petstore/pets/1 HTTP/1.1
  ```

  `ANY` 方法和代理资源的运行时实例都是有效的。此调用将返回一个 `200 OK` 响应以及包含从后端返回的指定宠物的负载。
+ **将 `ANY` 设置为 `POST` 并将 `{proxy+}` 设置为 `pets`**

  从前端发起的方法请求：

  ```
  POST https://4z9giyi2c1.execute-api.us-west-2.amazonaws.com/test/pets HTTP/1.1
  Content-Type: application/json
  Content-Length: ...
  
  {
    "type" : "dog",
    "price" : 1001.00
  }
  ```

  发送到后端的集成请求：

  ```
  POST http://petstore-demo-endpoint.execute-api.com/petstore/pets HTTP/1.1
  Content-Type: application/json
  Content-Length: ...
  
  {
    "type" : "dog",
    "price" : 1001.00
  }
  ```

  `ANY` 方法和代理资源的运行时实例都是有效的。此调用将返回一个 `200 OK` 响应以及包含从后端返回的新创建的宠物的负载。
+ **将 `ANY` 设置为 `GET` 并将 `{proxy+}` 设置为 `pets/cat`**

  从前端发起的方法请求：

  ```
  GET https://4z9giyi2c1.execute-api.us-west-2.amazonaws.com/test/pets/cat
  ```

  发送到后端的集成请求：

  ```
  GET http://petstore-demo-endpoint.execute-api.com/petstore/pets/cat
  ```

  代理资源路径的运行时实例与后端终端节点不对应，且生成的请求无效。因此，系统会返回 `400 Bad Request` 响应，并显示以下错误消息。

  ```
  {
    "errors": [
      {
        "key": "Pet2.type",
        "message": "Missing required field"
      },
      {
        "key": "Pet2.price",
        "message": "Missing required field"
      }
    ]
  }
  ```
+ **将 `ANY` 设置为 `GET` 并将 `{proxy+}` 设置为 `null`**

  从前端发起的方法请求：

  ```
  GET https://4z9giyi2c1.execute-api.us-west-2.amazonaws.com/test
  ```

  发送到后端的集成请求：

  ```
  GET http://petstore-demo-endpoint.execute-api.com/petstore/pets
  ```

  目标资源是代理资源的父资源，但未在该资源上的 API 中定义 `ANY` 方法的运行时实例。因此，此 `GET` 请求将返回一个 `403 Forbidden` 响应，而 API Gateway 返回 `Missing Authentication Token` 错误消息。如果 API 在父资源 (`ANY`) 上公开 `GET` 或 `/` 方法，则此调用将返回一个 `404 Not Found` 响应，同时从后端返回 `Cannot GET /petstore` 消息。

对于任何客户端请求，如果目标终端节点 URL 无效或 HTTP 命令动词有效但不受支持，则后端将返回 `404 Not Found` 响应。对于不受支持的 HTTP 方法，系统会返回 `403 Forbidden` 响应。

## 在 API Gateway 中设置 HTTP 自定义集成
<a name="set-up-http-custom-integrations"></a>

 使用 HTTP 自定义集成（也称为非代理集成），您可以更好地控制在 API 方法和 API 集成之间传递哪些数据以及如何传递数据。您可以使用数据映射执行此操作。

作为方法请求设置的一部分，您需要设置 [Method](https://docs.aws.amazon.com/apigateway/latest/api/API_Method.html)（方法）资源中的 [requestParameters](https://docs.aws.amazon.com/apigateway/latest/api/API_Method.html#requestParameters) 属性。这会声明对于从客户端预配置的方法请求参数，哪些要先映射到集成请求参数或适用的正文属性，然后再分派到后端。然后，作为集成请求设置的一部分，在相应的 [Integration](https://docs.aws.amazon.com/apigateway/latest/api/API_Integration.html)（集成）资源上设置 [requestParameters](https://docs.aws.amazon.com/apigateway/latest/api/API_Integration.html#requestParameters) 属性，以指定参数到参数的映射。您还要设置 [requestTemplates](https://docs.aws.amazon.com/apigateway/latest/api/API_Integration.html#requestTemplates) 属性，以指定映射模板，为每个支持的内容类型设置一个映射模板。映射模板将方法请求参数或正文映射到集成请求正文。

 同样，作为方法响应设置的一部分，您可以在 [MethodResponse](https://docs.aws.amazon.com/apigateway/latest/api/API_MethodResponse.html) 资源上设置 [responseParameters](https://docs.aws.amazon.com/apigateway/latest/api/API_MethodResponse.html#responseParameters) 属性。这可声明哪些方法响应参数将分派到客户端，哪些将从已从后端返回的集成响应参数或某些适用的正文属性进行映射。然后，您设置 [selectionPattern](https://docs.aws.amazon.com/apigateway/latest/api/API_IntegrationResponse.html#selectionPattern)，以根据来自后端的响应来选择集成响应。对于非代理 HTTP 集成，这是一个正则表达式。例如，要将来自 HTTP 端点的所有 2xx HTTP 响应状态代码映射到此输出映射，请使用 `2\d{2}`。

**注意**  
API Gateway 使用 Java 模式的正则表达式来响应映射。有关更多信息，请参阅 Oracle 文档中的[模式](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html)。

然后，作为集成响应设置的一部分，在相应的 [IntegrationResponse](https://docs.aws.amazon.com/apigateway/latest/api/API_IntegrationResponse.html) 资源上设置 [responseParameters](https://docs.aws.amazon.com/apigateway/latest/api/API_IntegrationResponse.html#responseParameters) 属性，以指定参数到参数的映射。您还要设置 [responseTemplates](https://docs.aws.amazon.com/apigateway/latest/api/API_IntegrationResponse.html#responseTemplates) 映射，以指定映射模板，为每个支持的内容类型设置一个映射模板。映射模板将集成响应参数或集成响应正文属性映射到方法响应正文。

 有关设置映射模板的更多信息，请参阅[针对 API Gateway 中 REST API 的数据转换](rest-api-data-transformations.md)。