

# 创建针对 API Gateway 中 HTTP API 的路由
<a name="http-api-develop-routes"></a>

将直接传入 API 请求路由到后端资源。路由包含两部分：HTTP 方法和资源路径，例如，`GET /pets`。您可以为路由定义特定的 HTTP 方法。或者，您可以使用 `ANY` 方法匹配尚未为资源定义的所有方法。您可以创建一个 `$default` 路由，用作与任何其他路由不匹配的请求的“捕获全部”方法。

**注意**  
API Gateway 在将 URL 编码的请求参数传递给后端集成之前对其进行解码。

## 使用路径变量
<a name="http-api-routes-path-variables"></a>

您可以在 HTTP API 路由中使用路径变量。

例如，`GET /pets/{petID}` 路由捕获客户端提交给 `GET` 的 `https://api-id.execute-api.us-east-2.amazonaws.com/pets/6` 请求。

*贪婪的路径变量* 捕获路由的所有子资源。要创建“贪婪”路径变量，请将 `+` 添加到变量名称，例如 `{proxy+}`。“贪婪”路径变量必须位于资源路径的末尾。

## 使用查询字符串参数
<a name="http-api-routes-query-string-parameters"></a>

默认情况下，如果查询字符串参数包含在对 HTTP API 的请求中，则 API Gateway 会将查询字符串参数发送到您的后端集成。

例如，当客户端向 `https://api-id.execute-api.us-east-2.amazonaws.com/pets?id=4&type=dog` 发送请求时，查询字符串参数 `?id=4&type=dog` 将发送到您的集成。

## 使用 `$default` 路由
<a name="http-api-develop-routes.default"></a>

`$default` 路由捕获与 API 中的其他路由未显式匹配的请求。

当 `$default` 路由收到请求时，API Gateway 将完整的请求路径发送到集成。例如，您可以创建仅包含 `$default` 路由的 API，并将其与 `ANY` HTTP 终端节点集成到 `https://petstore-demo-endpoint.execute-api.com` 方法上。当您向 `https://api-id.execute-api.us-east-2.amazonaws.com/store/checkout` 发送请求时，API Gateway 会向 `https://petstore-demo-endpoint.execute-api.com/store/checkout` 发送请求。

要了解有关 HTTP 集成的更多信息，请参阅 [为 HTTP API 创建 HTTP 代理集成](http-api-develop-integrations-http.md)。

## 路由 API 请求
<a name="http-api-develop-routes.evaluation"></a>

当客户端发送 API 请求时，API Gateway 首先确定要将请求路由到哪个[阶段](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-stages.html) 。如果请求显式匹配某个阶段，则 API Gateway 将请求发送到该阶段。如果没有阶段与请求完全匹配，API Gateway 将请求发送到 `$default` 阶段。如果没有 `$default` 阶段，则 API 返回 `{"message":"Not Found"}` 并且不生成 CloudWatch 日志。

选择阶段后，API Gateway 将选择路由。API Gateway 使用以下优先级选择具有最佳匹配项的路由：

1. 路由和方法的完全匹配。

1. 匹配具有贪婪路径变量 (`{proxy+}`) 的路由和方法。

1. `$default` 路由。

如果没有与请求匹配的路由，API Gateway 将 `{"message":"Not Found"}` 返回到客户端。

例如，考虑一个具有 `$default` 阶段和以下示例路由的 API：

1. `GET /pets/dog/1`

1. `GET /pets/dog/{id}`

1. `GET /pets/{proxy+}`

1. `ANY /{proxy+}`

1. `$default`

   下表汇总了 API Gateway 如何将请求路由到示例路由。


| 请求 | 选定的路由 | 说明 | 
| --- | --- | --- | 
|  `GET https://api-id.execute-api.region.amazonaws.com/pets/dog/1`  |  `GET /pets/dog/1`  |  请求与此静态路由完全匹配。  | 
|  `GET https://api-id.execute-api.region.amazonaws.com/pets/dog/2`  |  `GET /pets/dog/{id}`  |  请求与此路由完全匹配。  | 
|  `GET https://api-id.execute-api.region.amazonaws.com/pets/cat/1`  |  `GET /pets/{proxy+}`  |  请求与路由不完全匹配。具有 `GET` 方法和贪婪路径变量的路由捕获此请求。  | 
| `POST https://api-id.execute-api.region.amazonaws.com/test/5` | `ANY /{proxy+}` |  `ANY` 方法匹配尚未为路由定义的所有方法。具有贪婪路径变量的路由比 `$default` 路由的优先级更高。  | 