

# 在 API Gateway 中为 REST API 维护使用计划
<a name="api-gateway-usage-plan-manage-usage"></a>

维护使用计划涉及监控给定时间段内的已用配额和剩余配额，并（如果需要）将剩余配额扩展指定的量。以下过程介绍如何监控配额。

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

**监控已用配额和剩余配额**

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

1. 在 API Gateway 主导航窗格中，选择**使用计划**。

1. 选择一个使用计划。

1. 选择**关联的 API 密钥**选项卡，查看每个密钥在时间段内剩余的请求数。

1. （可选）选择**导出使用数据**，然后选择**开始日期**和**结束日期**。接下来，为导出的数据选择 **JSON** 或 **CSV** 格式，然后选择**导出**。

   以下示例显示了一个导出的文件。

   ```
   {
       "px1KW6...qBazOJH": [
         [
           0,
           5000
         ],
         [
           0,
           5000
         ],
         [
           0,
           10
         ]
       ]
     }
   ```

   示例中的使用率数据显示了某 API 客户端在 2016 年 8 月 1 日至 2016 年 8 月 3 日期间的每日使用率数据，由 API 密钥 (`px1KW6...qBazOJH`) 标识。每个每日使用率数据均显示已用配额和剩余配额。在本例中，订阅者尚未使用任何分配的配额，并且 API 所有者或管理员已在第三天将剩余配额从 5000 减至 10。

以下过程介绍如何修改配额。

**扩展剩余配额**

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

1. 在 API Gateway 主导航窗格中，选择**使用计划**。

1. 选择一个使用计划。

1. 选择**关联的 API 密钥**选项卡，查看每个密钥在时间段内剩余的请求数。

1. 选择 API 密钥，然后选择**授予使用延期**。

1. 为**剩余请求**配额输入一个数字。对于使用计划中的时间段，您可以增加剩余的请求数或减少剩余的请求数。

1. 选择**更新配额**。

------
#### [ Amazon CLI ]

以下 [update-usage-plan](https://docs.amazonaws.cn/cli/latest/reference/apigateway/update-usage-plan.html) 命令示例在使用计划中，添加、删除或修改方法级别的节流设置。

**注意**  
确保为您的 API 将 `us-east-1` 更改为相应的区域值。

要添加或替换用于限制单个资源和方法的速率限制，请执行以下操作：

```
aws apigateway --region us-east-1 update-usage-plan --usage-plan-id {{planId}} --patch-operations op="replace",path="/apiStages/{{apiId}}:{{stage}}/throttle/{{resourcePath}}/{{httpMethod}}/rateLimit",value="0.1"
```

要添加或替换用于限制单个资源和方法的突增限制，请执行以下操作：

```
aws apigateway --region us-east-1 update-usage-plan --usage-plan-id {{planId}} --patch-operations op="replace",path="/apiStages/{{apiId}}:{{stage}}/throttle/{{resourcePath}}/{{httpMethod}}/burstLimit",value="1"
```

要删除单个资源和方法的方法级别限制设置，请执行以下操作：

```
aws apigateway --region us-east-1 update-usage-plan --usage-plan-id {{planId}} --patch-operations op="remove",path="/apiStages/{{apiId}}:{{stage}}/throttle/{{resourcePath}}/{{httpMethod}}",value=""
```

要删除 API 的所有方法级别限制设置，请执行以下操作：

```
aws apigateway --region us-east-1 update-usage-plan --usage-plan-id {{planId}} --patch-operations op="remove",path="/apiStages/{{apiId}}:{{stage}}/throttle ",value=""
```

下面是使用 Pet Store 示例 API 的示例：

```
aws apigateway --region us-east-1 update-usage-plan --usage-plan-id {{planId}} --patch-operations op="replace",path="/apiStages/{{apiId}}:{{stage}}/throttle",value='"{\"/pets/GET\":{\"rateLimit\":1.0,\"burstLimit\":1},\"//GET\":{\"rateLimit\":1.0,\"burstLimit\":1}}"'
```

------
#### [ REST API ]

调用 [https://docs.amazonaws.cn/apigateway/latest/api/API_UpdateUsagePlan.html](https://docs.amazonaws.cn/apigateway/latest/api/API_UpdateUsagePlan.html) 以维护使用计划。

------