

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# API Gateway 中 REST API 的用量計畫和 API 金鑰
<a name="api-gateway-api-usage-plans"></a>

在您建立、測試和部署 API 之後，您可以使用 API Gateway 用量計劃讓它們可做為產品優惠供給客戶使用。您可以設定用量計劃和 API 金鑰，以便客戶存取選取的 API，並根據定義的限制和配額來調節傳送給這些 API 的請求量。您可在 API 或 API 方法層級進行設定這些內容。

## 什麼是用量計劃和 API 金鑰？
<a name="api-gateway-api-usage-plans-overview"></a>

*用量計劃*會指定誰能存取一個或多個已部署 API 階段和方法，也可以設定目標請求率來開始調節請求量。計劃會使用 API 金鑰來識別 API 用戶端，以及每個金鑰的相關 API 階段可存取者。

*API 金鑰*是英數字串值，您會將其發布到應用程式開發人員客戶，以授與您 API 的存取權。您可以將 [Lambda 授權方](apigateway-use-lambda-authorizer.md)、[IAM 角色](permissions.md)或 [Amazon Cognito](apigateway-integrate-with-cognito.md) 與 API 金鑰搭配使用，來控制對 API 的存取。API Gateway 可以代表您產生 API 金鑰，或從 [CSV 檔案](api-key-file-format.md)匯入它們。您可以在 API Gateway 中產生 API 金鑰，或從外部來源將它匯入 API Gateway。如需詳細資訊，請參閱[在 API Gateway 中設定 REST API 的 API 金鑰](api-gateway-setup-api-keys.md)。

API 金鑰具有名稱和數值。(術語「API 金鑰」與「API 金鑰值」經常可以交換使用。) 名稱不能超過 1024 個字元。金鑰值是介於 20 與 128 個字元之間的英數字串，例如，`apikey1234abcdefghij0123456789`。

**重要**  
API 金鑰值必須是唯一的。如果您嘗試建立兩個名稱不同但數值相同的 API 金鑰，API Gateway 會將它們視為相同的 API 金鑰。  
API 金鑰可以關聯到多個用量計劃。用量計劃可以關聯到多個階段。不過，特定 API 金鑰只能與每個 API 階段的一個用量計劃相關聯。

*調節限制*即為開始進行請求調節應的目標點。您可在 API 或 API 方法層級進行設定。

*配額限制*即為使用特定 API 金鑰在指定時間間隔內可以提交的目標請求量上限。您可以設定個別的 API 方法根據用量計劃組態來要求 API 金鑰授權。

調節和配額限制適用於在用量計劃中跨所有 API 階段彙總之個別 API 金鑰的請求。

**注意**  
用量計劃調節和配額並非硬性限制，會依最佳作法來套用。在某些情況下，用戶端可能超出設定的配額。請勿依靠用量計劃配額或調節來控制成本或封鎖對 API 的存取。請考慮使用 [AWS Budgets](https://docs.aws.amazon.com/cost-management/latest/userguide/budgets-managing-costs.html) 來監控成本，使用 [AWS WAF](https://docs.aws.amazon.com/waf/latest/developerguide/waf-chapter.html) 來管理 API 請求量。

## API 金鑰和用量計劃的最佳實務
<a name="apigateway-usage-plans-best-practices"></a>

以下是使用 API 金鑰和用量計劃時建議遵循的最佳實務。

**重要**  
不要使用 API 金鑰進行身分驗證或授權來控制 API 的存取權。然而，若用量計劃中具有多個 API，則持有該用量計劃中某 API 有效 API 金鑰的使用者便可存取該用量計劃中的*所有* API。請改用 IAM 角色、[Lambda 授權方](apigateway-use-lambda-authorizer.md)或 [Amazon Cognito 使用者集區](apigateway-integrate-with-cognito.md)來控制 API 的存取權。
使用 API Gateway 產生的 API 金鑰。API 金鑰不應包含機密資訊；用戶端通常會在可被記錄的標頭中傳輸這些資訊。
+ 如果您是使用開發人員入口網站來發布 API，請注意，特定用量計畫中的所有 API 都是可訂閱的，即使您尚未讓客戶可以看到它們也一樣。
+ 在某些情況下，用戶端可能超出設定的配額。請勿依靠用量計劃來控制成本。請考慮使用 [AWS Budgets](https://docs.aws.amazon.com/cost-management/latest/userguide/budgets-managing-costs.html) 來監控成本，使用 [AWS WAF](https://docs.aws.amazon.com/waf/latest/developerguide/waf-chapter.html) 來管理 API 請求量。
+ 將 API 金鑰新增至用量計畫後，更新作業可能需要幾分鐘時間才能完成。

# 在 API Gateway 中選擇 API 金鑰來源
<a name="api-gateway-api-key-source"></a>

當您將 API 與用量計劃建立關聯並在 API 方法上啟用 API 金鑰時，每個對 API 傳入的請求必須包含 [API 金鑰](api-gateway-basic-concept.md#apigateway-definition-api-key)。API Gateway 會讀取金鑰，並將其與在用量計劃中的金鑰進行比對。如果有相符項目，則 API Gateway 會根據計劃的請求限制和配額來調節請求量。否則，它會擲出 `InvalidKeyParameter` 例外狀況。因此，發起人收到 `403 Forbidden` 回應。

API Gateway API 可接收來自以下兩種來源之一的 API 金鑰：

**`HEADER`**  
您將 API 金鑰發布至客戶，並要求他們傳遞 API 金鑰，做為每個傳入請求的 `X-API-Key` 標頭。

**`AUTHORIZER`**  
您可以讓 Lambda 授權方傳回 API 金鑰，當做授權回應的一部分。如需授權回應的詳細資訊，請參閱[來自 API Gateway Lambda 授權方的輸出](api-gateway-lambda-authorizer-output.md)。

**注意**  
如需考量最佳實務，請參閱 [API 金鑰和用量計劃的最佳實務](api-gateway-api-usage-plans.md#apigateway-usage-plans-best-practices)。

下列程序說明如何選擇 API 的 API 金鑰來源。

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

**選擇 API 的 API 金鑰來源**

1. 登入 API Gateway 主控台。

1. 選擇現有的 API 或建立新的 API。

1. 在主導覽窗格中，選擇 **API 設定**。

1. 在 **API 詳細資訊**區段中，選擇**編輯**。

1.  在 **API 金鑰來源**下，從下拉式清單選取 `Header` 或 `Authorizer`。

1. 選擇**儲存變更**。

------
#### [ AWS CLI ]

以下 [update-rest-api](https://docs.aws.amazon.com/cli/latest/reference/apigateway/update-rest-api.html) 命令會更新 API，以將 API 金鑰來源設定為 `AUTHORIZER`：

```
aws apigateway update-rest-api --rest-api-id 1234123412 --patch-operations op=replace,path=/apiKeySource,value=AUTHORIZER
```

若要讓用戶端提交 API 金鑰，請在上述命令中將 `value` 設為 `HEADER`。

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

若要使用 API Gateway REST API 選擇 API 的 API 金鑰來源，請呼叫 [https://docs.aws.amazon.com/apigateway/latest/api/API_UpdateRestApi.html](https://docs.aws.amazon.com/apigateway/latest/api/API_UpdateRestApi.html)，如下所示：

```
PATCH /restapis/fugvjdxtri/ HTTP/1.1
Content-Type: application/json
Host: apigateway.us-east-1.amazonaws.com
X-Amz-Date: 20160603T205348Z
Authorization: AWS4-HMAC-SHA256 Credential={access_key_ID}/20160603/us-east-1/apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature={sig4_hash}

{
  "patchOperations" : [
    {
        "op" : "replace",
        "path" : "/apiKeySource",
        "value" : "HEADER"
    }
  ]
}
```

若要讓授權方傳回 API 金鑰，請在之前的 `value` 輸入中將 `AUTHORIZER` 設為 `patchOperations`。

------

# API Gateway API 金鑰檔案格式
<a name="api-key-file-format"></a>

API Gateway 可以從逗號分隔值 (CSV) 格式的外部檔案匯入 API 金鑰，然後建立已匯入金鑰與一或多個用量計劃的關聯性。匯入的檔案必須包含 `Name` 與 `Key` 欄位。欄標頭名稱不區分大小寫，各欄順序任意排列，如以下範例所示：

```
Key,name
apikey1234abcdefghij0123456789,MyFirstApiKey
```

`Key` 值必須介於 20 到 128 個字元之間。`Name` 值不能超過 1024 個字元。

API 金鑰檔案也可以有 `Description`、`Enabled` 或 `UsagePlanIds` 欄位，如下例所示：

```
Name,key,description,Enabled,usageplanIds
MyFirstApiKey,apikey1234abcdefghij0123456789,An imported key,TRUE,c7y23b
```

當金鑰與多個用量計劃相關聯時，`UsagePlanIds` 值是用量計劃 ID 的逗號分隔字串，以一對雙引號或單引號括住，如下例所示：

```
Enabled,Name,key,UsageplanIds
true,MyFirstApiKey,apikey1234abcdefghij0123456789,"c7y23b,glvrsr"
```

允許無法識別的欄位，但會被忽略。預設值為空白字串或 `true` 布林值。

相同的 API 金鑰可以匯入多次，以最新的版本覆寫前一個。兩個 API 金鑰如有相同的 `key` 值，則它們即完全相同。

**注意**  
如需考量最佳實務，請參閱 [API 金鑰和用量計劃的最佳實務](api-gateway-api-usage-plans.md#apigateway-usage-plans-best-practices)。

# 在 API Gateway 中設定 REST API 的 API 金鑰
<a name="api-gateway-setup-api-keys"></a>

若要設定 API 金鑰，請執行下列步驟：
+ 設定 API 方法以要求 API 金鑰。
+ 為區域中的 API 建立或匯入 API 金鑰。

在設定 API 金鑰之前，您必須已建立 API 並將它部署至階段。在您建立 API 金鑰值之後便無法變更。

如需如何使用 API Gateway 主控台建立和部署 API 的說明，請參閱[在 APIs Gateway 中開發 REST API](rest-api-develop.md) 和[在 API Gateway 中部署 REST API](how-to-deploy-api.md)。

建立 API 金鑰後，您必須為該金鑰與用量計畫建立關聯。如需詳細資訊，請參閱[在 API Gateway 中設定 REST API 的用量計畫](api-gateway-create-usage-plans.md)。

**注意**  
如需考量最佳實務，請參閱 [API 金鑰和用量計劃的最佳實務](api-gateway-api-usage-plans.md#apigateway-usage-plans-best-practices)。

**Topics**
+ [方法中需要 API 金鑰](#api-gateway-usage-plan-configure-apikey-on-method)
+ [建立 API 金鑰](#api-gateway-usage-plan-create-apikey)
+ [匯入 API 金鑰](#api-gateway-usage-pan-import-apikey)

## 方法中需要 API 金鑰
<a name="api-gateway-usage-plan-configure-apikey-on-method"></a>

下列程序說明如何設定 API 方法要求 API 金鑰。

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

**設定 API 方法要求 API 金鑰**

1. 在以下網址登入 API Gateway 主控台：[https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway)。

1. 選擇 REST API。

1. 在 API Gateway 主導覽窗格中，選擇 **Resources** (資源)。

1. 在 **Resources** (資源) 下，建立新的方法或選擇現有的方法。

1. 在**方法請求**索引標籤的**方法請求設定**下，選擇**編輯**。  
![\[將 API 金鑰新增至方法\]](http://docs.aws.amazon.com/zh_tw/apigateway/latest/developerguide/images/api-gateway-new-console-add-key-to-method.png)

1. 選取**需要 API 金鑰**。

1. 選擇**儲存**。

1. 部署或重新部署 API 以使要求生效。

如果**需要 API 金鑰**選項設為 `false`，而且您不執行之前的各項步驟，則方法不會使用任何與 API 階段相關聯的 API 金鑰。

------
#### [ AWS CLI ]

以下 [put-method](https://docs.aws.amazon.com/cli/latest/reference/apigateway/put-method.html) 命令會建立需要 API 金鑰的 `PUT` 方法：

```
aws apigateway put-method \
    --rest-api-id 1234123412 \
    --resource-id a1b2c3 \
    --http-method PUT \
    --authorization-type "NONE" \
    --api-key-required
```

以下 [update-method](https://docs.aws.amazon.com/cli/latest/reference/apigateway/update-method.html) 命令會更新現有方法，以要求 API 金鑰：

```
aws apigateway update-method \
    --rest-api-id 1234123412 \
    --resource-id a1b2c3 \
    --http-method PUT \
    --patch-operations op="replace",path="/apiKeyRequired",value="true"
```

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

方法中如需要 API 金鑰，請執行下列其中一項操作：
+ 呼叫 [https://docs.aws.amazon.com/apigateway/latest/api/API_PutMethod.html](https://docs.aws.amazon.com/apigateway/latest/api/API_PutMethod.html) 來建立方法。在請求承載中將 `apiKeyRequired` 設為 `true`。
+ 呼叫 [https://docs.aws.amazon.com/apigateway/latest/api/API_UpdateMethod.html](https://docs.aws.amazon.com/apigateway/latest/api/API_UpdateMethod.html)，將 `apiKeyRequired` 設定為 `true`。

------

## 建立 API 金鑰
<a name="api-gateway-usage-plan-create-apikey"></a>

下列程序說明如何建立 API 金鑰。如果您想要匯入自己的 API 金鑰，請略過此步驟。

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

**建立 API 金鑰**

1. 在以下網址登入 API Gateway 主控台：[https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway)。

1. 選擇 REST API。

1. 在 API Gateway 主導覽窗格中，選擇 **API 金鑰**。

1. 選擇**建立 API 金鑰**。  
![\[建立用量計劃的 API 金鑰\]](http://docs.aws.amazon.com/zh_tw/apigateway/latest/developerguide/images/api-gateway-new-console-usage-plan-keys-choose-create-api-key-from-actions-menu.png)

1. 針對**名稱**，輸入名稱。

1. 在**描述**，請輸入描述。

1. 針對 **API 金鑰**，選擇**自動產生**讓 API Gateway 產生金鑰值，或選擇**自訂**建立您自己的金鑰值。

1. 選擇**儲存**。

------
#### [ AWS CLI ]

以下 [create-api-key](https://docs.aws.amazon.com/cli/latest/reference/apigateway/create-api-key.html) 命令會建立 API 金鑰：

```
 aws apigateway create-api-key \
    --name 'Dev API key' \
    --description 'API key for Devs' \
    --enabled
```

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

呼叫 [https://docs.aws.amazon.com/apigateway/latest/api/API_CreateApiKey.html](https://docs.aws.amazon.com/apigateway/latest/api/API_CreateApiKey.html) 來建立 API 金鑰。

------

## 匯入 API 金鑰
<a name="api-gateway-usage-pan-import-apikey"></a>

下列程序說明如何匯入 API 金鑰。如果您已建立 API 金鑰，請略過此步驟。

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

**匯入 API 金鑰**

1. 在以下網址登入 API Gateway 主控台：[https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway)。

1. 選擇 REST API。

1. 在主導覽窗格中，選擇 **API 金鑰**。

1. 選擇**動作**下拉式選單，然後選擇**匯入 API 金鑰**。

1. 若要載入逗號分隔的金鑰檔案，請選擇**選取檔案**。您也可以在文字編輯器中輸入金鑰。如需檔案格式的資訊，請參閱 [API Gateway API 金鑰檔案格式](api-key-file-format.md)。

1. 選擇**發出警告時失敗**，在發生錯誤時停止匯入，或選擇**忽略警告**，在出現警告時繼續匯入有效的金鑰項目。

1. 選擇**匯入**以匯入您的 API 金鑰。

------
#### [ AWS CLI ]

以下 [import-api-keys](https://docs.aws.amazon.com/cli/latest/reference/apigateway/import-api-keys.html) 命令會匯入 API 金鑰：

```
aws apigateway import-api-key \
    a--body fileb://keys.csv \
    --format csv
```

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

呼叫 [https://docs.aws.amazon.com/apigateway/latest/api/API_ImportApiKeys.html](https://docs.aws.amazon.com/apigateway/latest/api/API_ImportApiKeys.html) 以從檔案匯入 API 金鑰。如需檔案格式，請參閱 [API Gateway API 金鑰檔案格式](api-key-file-format.md)。

------

您無法變更新 API 金鑰的值。在您建立 API 之後，請設定用量計畫。如需詳細資訊，請參閱[在 API Gateway 中設定 REST API 的用量計畫](api-gateway-create-usage-plans.md)。

# 在 API Gateway 中設定 REST API 的用量計畫
<a name="api-gateway-create-usage-plans"></a>

建立用量計畫之前，請確認您已設定 API 金鑰。如需詳細資訊，請參閱[在 API Gateway 中設定 REST API 的 API 金鑰](api-gateway-setup-api-keys.md)。

**Topics**
+ [遷移您的 API 到預設用量計劃 (如需要)](#api-gateway-usage-plan-migrate-to-default)
+ [建立用量計劃](#api-gateway-usage-plan-create)
+ [將階段新增至用量計畫](#api-gateway-usage-plan-add-stage)
+ [將 API 階段新增至用量計畫](#api-gateway-usage-plan-add-key)

## 遷移您的 API 到預設用量計劃 (如需要)
<a name="api-gateway-usage-plan-migrate-to-default"></a>

如果您在 2016 年 8 月 11 日推出用量計劃功能「之後」**開始使用 API Gateway，就可以自動在所有支援的區域中啟用用量計劃。

如果您是在該日期之前開始使用 API Gateway，則可能需要遷移到預設用量計劃。在所選區域第一次使用用量計劃之前，系統會提示您 **Enable Usage Plans** (啟用用量計劃) 選項。當您啟用此選項時，您已為與現有 API 金鑰相關聯的每個唯一 API 階段，建立預設的用量計劃。在預設的用量計劃中，一開始並無設定調節和配額限制，而 API 金鑰和 API 階段之間的關聯會複製到用量計劃。API 的行為和以前一樣。不過，您必須使用 [https://docs.aws.amazon.com/apigateway/latest/api/API_UsagePlan.html](https://docs.aws.amazon.com/apigateway/latest/api/API_UsagePlan.html) `apiStages` 屬性建立指定 API 階段值 (`apiId` 和 `stage`) 與內含 API 金鑰 (透過 [https://docs.aws.amazon.com/apigateway/latest/api/API_UsagePlanKey.html](https://docs.aws.amazon.com/apigateway/latest/api/API_UsagePlanKey.html)) 的關聯，而非使用 [ApiKey](https://docs.aws.amazon.com/apigateway/latest/api/API_ApiKey.html) `stageKeys` 屬性。

若要查看您是否已遷移到預設用量計劃，請使用 [https://docs.aws.amazon.com/cli/latest/reference/apigateway/get-account.html](https://docs.aws.amazon.com/cli/latest/reference/apigateway/get-account.html) CLI 命令。在命令輸出之中，當用量計劃已啟用，`features` 清單就會包含 `"UsagePlans"` 項目。

您也可以使用 將 APIs遷移至預設用量計劃 AWS CLI ，如下所示：

**使用 遷移至預設用量計劃 AWS CLI**

1. 呼叫 CLI 命令：[https://docs.aws.amazon.com/cli/latest/reference/apigateway/update-account.html](https://docs.aws.amazon.com/cli/latest/reference/apigateway/update-account.html)。

1. 針對 `cli-input-json` 參數，請使用下列 JSON：

   ```
   [
       {
           "op": "add",
           "path": "/features",
           "value": "UsagePlans"
       }
   ]
   ```

## 建立用量計劃
<a name="api-gateway-usage-plan-create"></a>

下列程序說明如何建立用量計劃。

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

**建立用量計劃**

1. 在以下網址登入 API Gateway 主控台：[https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway)。

1. 在 API Gateway 主導覽窗格中，選擇**用量計劃**，然後選擇**建立用量計劃**。  
![\[API 用量計劃實體\]](http://docs.aws.amazon.com/zh_tw/apigateway/latest/developerguide/images/api-gateway-new-console-usage-plan-keys-create-setup.png)

1. 針對**名稱**，輸入名稱。

1.  在**描述**，請輸入描述。

1. 根據預設，用量計劃會啟用限流。輸入用量計劃的**費率**和**暴增**。選擇**限流**以關閉限流。

1. 根據預設，用量計劃會針對一段時間啟用一個配額。針對**請求**，輸入使用者在您的用量計劃期間內可提出的請求總數。選擇**配額**以關閉配額。

1. 選擇**建立用量計劃**。

------
#### [ AWS CLI ]

以下 [create-usage-plan](https://docs.aws.amazon.com/cli/latest/reference/apigateway/create-usage-plan.html) 命令會建立用量計畫，此計畫會在月初重設：

```
aws apigateway create-usage-plan \
    --name "New Usage Plan" \
    --description "A new usage plan" \
    --throttle burstLimit=10,rateLimit=5 \
    --quota limit=500,offset=0,period=MONTH
```

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

呼叫 [https://docs.aws.amazon.com/apigateway/latest/api/API_CreateUsagePlan.html](https://docs.aws.amazon.com/apigateway/latest/api/API_CreateUsagePlan.html) 來建立用量計劃。

------

## 將階段新增至用量計畫
<a name="api-gateway-usage-plan-add-stage"></a>

下列程序說明如何將階段新增至用量計畫。

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

**將階段新增至用量計畫**

1. 選取您的用量計劃。

1.  在**關聯的階段**索引標籤下，選擇**新增階段**。  
![\[將 API 階段新增至用量計畫表。\]](http://docs.aws.amazon.com/zh_tw/apigateway/latest/developerguide/images/api-gateway-new-console-usage-plan-keys-create-add-stage.png)

1.  針對 **API**，選取 API。

1.  針對**階段**，選取階段。

1. (選用) 若要開啟方法層級限流，請執行下列操作：

   1. 選擇**方法層級限流**，然後選擇**新增方法**。

   1. 針對**資源**，從 API 中選取資源。

   1. 針對**方法**，從 API 中選取方法。

   1.  輸入用量計劃的**費率**和**暴增**。

1. 選擇**新增至用量計劃**。

------
#### [ AWS CLI ]

以下 [update-usage-plan](https://docs.aws.amazon.com/cli/latest/reference/apigateway/update-usage-plan.html) 命令會將 API 的 `Prod` 階段新增至用量計畫：

```
aws apigateway update-usage-plan \
    --usage-plan-id abc123 \
    --patch-operations op="add",path="/apiStages",value="a1b1c2:Prod"
```

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

呼叫 [https://docs.aws.amazon.com/apigateway/latest/api/API_UpdateUsagePlan.html](https://docs.aws.amazon.com/apigateway/latest/api/API_UpdateUsagePlan.html) 以更新用量計畫。

------

## 將 API 階段新增至用量計畫
<a name="api-gateway-usage-plan-add-key"></a>

下列程序說明如何將 API 金鑰新增至用量計畫。

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

**將金鑰新增至用量計畫**

1. 在**關聯的 API 金鑰**索引標籤下，選擇**新增 API 金鑰**。  
![\[API 用量計劃實體\]](http://docs.aws.amazon.com/zh_tw/apigateway/latest/developerguide/images/api-gateway-new-console-usage-plan-keys-create-add-key.png)

1. 

   1.  若要將現有金鑰與用量計劃建立關聯，請選取**新增現有金鑰**，然後從下拉式選單選取您現有的金鑰。

   1. 若要建立新的 API 金鑰，請選取**建立並新增新金鑰**，然後建立新金鑰。如需如何建立新金鑰的詳細資訊，請參閱 [建立 API 金鑰](api-gateway-setup-api-keys.md#api-gateway-usage-plan-create-apikey)。

1. 選擇**新增 API 金鑰**。

------
#### [ AWS CLI ]

以下 [create-usage-plan-key](https://docs.aws.amazon.com/cli/latest/reference/apigateway/create-usage-plan-key.html) 命令會將現有的 API 金鑰與用量計畫建立關聯：

```
aws apigateway create-usage-plan-key \
    --usage-plan-id a1b2c3 \
    --key-type "API_KEY" \
    --key-id aaa111bbb
```

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

呼叫 [https://docs.aws.amazon.com/apigateway/latest/api/API_CreateUsagePlanKey.html](https://docs.aws.amazon.com/apigateway/latest/api/API_CreateUsagePlanKey.html)，以將現有的 API 金鑰與用量計畫建立關聯。

您也可以在匯入 API 金鑰時，直接將金鑰與用量計畫建立關聯。呼叫 [https://docs.aws.amazon.com/apigateway/latest/api/API_ImportApiKeys.html](https://docs.aws.amazon.com/apigateway/latest/api/API_ImportApiKeys.html) 將一或多個 API 金鑰直接新增至指定的用量計劃。請求承載應該包含 API 金鑰值、相關聯的用量計劃識別符、指出用量計劃已啟用金鑰的布林值旗標，以及 API 金鑰名稱和說明 (如可能)。

以下 `apikey:import` 請求範例會將三個 API 金鑰 (識別為 `key`、`name` 和 `description`) 新增至一個用量計劃 (識別為 `usageplanIds`)：

```
POST /apikeys?mode=import&format=csv&failonwarnings=fase HTTP/1.1
Host: apigateway.us-east-1.amazonaws.com
Content-Type: text/csv
Authorization: ...

key,name, description, enabled, usageplanIds
abcdef1234ghijklmnop8901234567, importedKey_1, firstone,  tRuE, n371pt 
abcdef1234ghijklmnop0123456789, importedKey_2, secondone, TRUE, n371pt
abcdef1234ghijklmnop9012345678, importedKey_3,          , true, n371pt
```

因此，會在 `UsagePlanKey` 中建立和新增三項 `UsagePlan` 資源。

您也可以用這種方式將 API 金鑰新增至多個用量計劃。若要這樣做，請將每個 `usageplanIds` 欄值變更成包含所選用量計劃識別符的逗號分隔字串，以一對引號 (`"n371pt,m282qs"` 或 `'n371pt,m282qs'`) 括住。

------

**注意**  
API 金鑰可以關聯到多個用量計劃。用量計劃可以關聯到多個階段。不過，特定 API 金鑰只能與每個 API 階段的一個用量計劃相關聯。

# 在 API Gateway 中維護 REST API 的用量計畫
<a name="api-gateway-usage-plan-manage-usage"></a>

維護用量計劃涉及監控指定時段內已使用和剩餘的配額，以及如有需要，依指定的量擴充剩餘配額。下列程序說明如何監控配額。

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

**監控已使用及剩餘的配額**

1. 在以下網址登入 API Gateway 主控台：[https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/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. 在以下網址登入 API Gateway 主控台：[https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway)。

1. 在 API Gateway 主導覽窗格中，選擇**用量計劃**。

1. 選取用量計劃。

1. 選擇**關聯的 API 金鑰**索引標籤，以查看每個金鑰在期間內剩餘的請求數。

1. 選取 API 金鑰，然後選擇**授予用量延伸**。

1. 輸入**剩餘的請求**配額的數量。您可以針對您的用量計劃期間增加剩餘的請求數，也可以減少剩餘的請求數。

1. 選擇**更新配額**。

------
#### [ AWS CLI ]

以下 [update-usage-plan](https://docs.aws.amazon.com/cli/latest/reference/apigateway/update-usage-plan.html) 範例會新增、移除或修改用量計畫中的方法層級限流設定。

**注意**  
請務必將 `us-east-1` 變更為您 API 的適當區域值。

若要為調節個別的資源和方法新增或取代速率限制：

```
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.aws.amazon.com/apigateway/latest/api/API_UpdateUsagePlan.html](https://docs.aws.amazon.com/apigateway/latest/api/API_UpdateUsagePlan.html) 以維護用量計畫。

------

# 使用 建立和設定 API 金鑰和用量計劃 CloudFormation
<a name="api-key-usage-plan-cfn"></a>

 您可以使用 CloudFormation 在 API 方法上要求 API 金鑰，並為 API 建立用量計劃。範本範例 CloudFormation 會執行下列動作：
+ 使用 `GET` 與 `POST` 方法建立 API Gateway API。
+ `GET` 與 `POST` 方法需要 API 金鑰。此 API 會從每個傳入要求的 `X-API-KEY` 標頭接收金鑰。
+ 建立 API 金鑰
+ 建立用量計畫以指定每月 1,000 個要求的每月配額、每秒 100 個要求的限流速率限制，以及每秒 200 個要求的限流高載限制。
+ 指定每秒 50 個請求的方法層級限流速率限制，以及 `GET` 方法層級限流爆量限制 (每秒 100 個請求)。
+ 將 API 階段和 API 金鑰與用量計劃建立關聯。

```
AWSTemplateFormatVersion: 2010-09-09
Parameters:
  StageName:
    Type: String
    Default: v1
    Description: Name of API stage.
  KeyName:
    Type: String
    Default: MyKeyName
    Description: Name of an API key
Resources:
  Api:
    Type: 'AWS::ApiGateway::RestApi'
    Properties:
      Name: keys-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: true
      AuthorizationType: NONE
      Integration:
        Type: HTTP_PROXY
        IntegrationHttpMethod: GET
        Uri: http://petstore-demo-endpoint.execute-api.com/petstore/pets/
  PetsMethodPost:
    Type: 'AWS::ApiGateway::Method'
    Properties:
      RestApiId: !Ref Api
      ResourceId: !Ref PetsResource
      HttpMethod: POST
      ApiKeyRequired: true
      AuthorizationType: NONE
      Integration:
        Type: HTTP_PROXY
        IntegrationHttpMethod: GET
        Uri: http://petstore-demo-endpoint.execute-api.com/petstore/pets/
  ApiDeployment:
    Type: 'AWS::ApiGateway::Deployment'
    DependsOn:
      - PetsMethodGet
    Properties:
      RestApiId: !Ref Api
      StageName: !Sub '${StageName}'
  UsagePlan:
    Type: AWS::ApiGateway::UsagePlan
    DependsOn:
      - ApiDeployment
    Properties:
      Description: Example usage plan with a monthly quota of 1000 calls and method-level throttling for /pets GET 
      ApiStages:
        - ApiId: !Ref Api
          Stage: !Sub '${StageName}'
          Throttle:
            "/pets/GET": 
              RateLimit: 50.0
              BurstLimit: 100
      Quota:
        Limit: 1000
        Period: MONTH
      Throttle:
        RateLimit: 100.0
        BurstLimit: 200
      UsagePlanName: "My Usage Plan"
  ApiKey:
    Type: AWS::ApiGateway::ApiKey
    Properties: 
      Description: API Key
      Name: !Sub '${KeyName}'
      Enabled: True
  UsagePlanKey:
    Type: AWS::ApiGateway::UsagePlanKey
    Properties:
      KeyId: !Ref ApiKey
      KeyType: API_KEY
      UsagePlanId: !Ref UsagePlan
Outputs:
  ApiRootUrl:
    Description: Root Url of the API
    Value: !Sub 'https://${Api}.execute-api.${AWS::Region}.amazonaws.com/${StageName}'
```

# 設定使用具有 OpenAPI 定義的 API 金鑰方法
<a name="api-key-usage-plan-oas"></a>

您可以使用 OpenAPI 定義來要求方法上的 API 金鑰。

針對每個方法建立安全需求物件，要求 API 金鑰調用該方法。然後，在安全定義中定義 `api_key`。建立 API 之後，將新的 API 階段新增至您的用量計畫。

下列範例會建立 API，並且需要 `POST` 和 `GET` 方法的 API 金鑰：

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

```
{
  "swagger" : "2.0",
  "info" : {
    "version" : "2024-03-14T20:20:12Z",
    "title" : "keys-api"
  },
  "basePath" : "/v1",
  "schemes" : [ "https" ],
  "paths" : {
    "/pets" : {
      "get" : {
        "responses" : { },
        "security" : [ {
          "api_key" : [ ]
        } ],
        "x-amazon-apigateway-integration" : {
          "type" : "http_proxy",
          "httpMethod" : "GET",
          "uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets/",
          "passthroughBehavior" : "when_no_match"
        }
      },
      "post" : {
        "responses" : { },
        "security" : [ {
          "api_key" : [ ]
        } ],
        "x-amazon-apigateway-integration" : {
          "type" : "http_proxy",
          "httpMethod" : "GET",
          "uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets/",
          "passthroughBehavior" : "when_no_match"
        }
      }
    }
  },
  "securityDefinitions" : {
    "api_key" : {
      "type" : "apiKey",
      "name" : "x-api-key",
      "in" : "header"
    }
  }
}
```

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

```
{
  "openapi" : "3.0.1",
  "info" : {
    "title" : "keys-api",
    "version" : "2024-03-14T20:20:12Z"
  },
  "servers" : [ {
    "url" : "{basePath}",
    "variables" : {
      "basePath" : {
        "default" : "v1"
      }
    }
  } ],
  "paths" : {
    "/pets" : {
      "get" : {
        "security" : [ {
          "api_key" : [ ]
        } ],
        "x-amazon-apigateway-integration" : {
          "httpMethod" : "GET",
          "uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets/",
          "passthroughBehavior" : "when_no_match",
          "type" : "http_proxy"
        }
      },
      "post" : {
        "security" : [ {
          "api_key" : [ ]
        } ],
        "x-amazon-apigateway-integration" : {
          "httpMethod" : "GET",
          "uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets/",
          "passthroughBehavior" : "when_no_match",
          "type" : "http_proxy"
        }
      }
    }
  },
  "components" : {
    "securitySchemes" : {
      "api_key" : {
        "type" : "apiKey",
        "name" : "x-api-key",
        "in" : "header"
      }
    }
  }
}
```

------

# 在 API Gateway 中測試 REST API 的用量計畫
<a name="api-gateway-usage-plan-test-with-postman"></a>

以在 [教學課程：匯入範例來建立 REST API](api-gateway-create-api-from-example.md) 中建立的 PetStore API 為例。假設 API 設定使用 `Hiorr45VR...c4GJc` 的 API 金鑰。下列步驟說明如何測試用量計劃。

**測試您的用量計劃**
+ 在用量計劃中，對 API (例如 `GET`) 的 Pets 資源 (`/pets`) 提出 `?type=...&page=...` 請求，查詢參數為 `xbvxlpijch`：

  ```
  GET /testStage/pets?type=dog&page=1 HTTP/1.1
  x-api-key: Hiorr45VR...c4GJc
  Content-Type: application/x-www-form-urlencoded
  Host: xbvxlpijch.execute-api.ap-southeast-1.amazonaws.com
  X-Amz-Date: 20160803T001845Z
  Authorization: AWS4-HMAC-SHA256 Credential={access_key_ID}/20160803/ap-southeast-1/execute-api/aws4_request, SignedHeaders=content-type;host;x-amz-date;x-api-key, Signature={sigv4_hash}
  ```
**注意**  
您必須向 API Gateway 的 `execute-api` 元件提交此請求，並在所需的 `Hiorr45VR...c4GJc` 標頭中提供需要的 API 金鑰 (例如 `x-api-key`)。

  成功的回應會傳回 `200 OK` 狀態碼和包含後端請求結果的承載。如果您忘記設定 `x-api-key` 標頭或以錯誤的金鑰設定它，您會收到 `403 Forbidden` 回應。不過，如果您並未設定方法要求 API 金鑰，您可能會收得 `200 OK` 回應，無論您是否正確設定 `x-api-key` 標頭，而且會略過用量計劃的調節和配額限制。

  有時，當發生 API Gateway 無法強制用量計劃調節限制或請求配額的內部錯誤時，API Gateway 會提供請求，但不會套用用量計劃指定的調節限制或配額。但是，它會在您的 CloudWatch 中記錄 `Usage Plan check failed due to an internal error` 錯誤訊息。您可以忽略這類偶發的錯誤。

# 使用 API 金鑰呼叫方法
<a name="api-gateway-api-key-call"></a>

根據您選擇的 API 金鑰來源類型，使用以下程序的其中之一，在方法呼叫中使用來源於標頭的 API 金鑰或授權方傳回的 API 金鑰：

**若要使用標頭來源 API 金鑰：**

1.  使用所需的 API 方法建立 API，然後將 API 部署至階段。

1.  建立新的用量計劃或選擇現有的用量計劃。將已部署的 API 階段新增至用量計劃。將 API 金鑰連接到用量計劃，或在計劃中選擇現有的 API 金鑰。請記下所選的 API 金鑰值。

1.  設定 API 方法要求 API 金鑰。

1.  將 API 重新部署到同一個階段。如果您將 API 部署到新的階段，請務必更新用量計劃以連接新的 API 階段。

1. 使用 API 金鑰呼叫 API。下列範例 curl 命令會使用 API 金鑰，在 API `prod` 階段的 `getUsers` 資源上調用 `GET` 方法。

   ```
   curl -H "X-API-Key: abcd1234" 'https://b123abcde4.execute-api.us-west-2.amazonaws.com/prod/getUsers' 
   ```

用戶端現在可以在呼叫 API 方法的同時，提供以所選 API 金鑰為標頭值的 `x-api-key` 標頭。呼叫看起來與以下內容相似：

**若要使用授權方來源 API 金鑰：**

1.  使用所需的 API 方法建立 API，然後將 API 部署至階段。

1.  建立新的用量計劃或選擇現有的用量計劃。將已部署的 API 階段新增至用量計劃。將 API 金鑰連接到用量計劃，或在計劃中選擇現有的 API 金鑰。請記下所選的 API 金鑰值。

1.  建立權杖型 Lambda 授權方。納入 `usageIdentifierKey:{api-key}` 作為授權回應的根層級屬性。如需有關建立字符型授權方的說明，請參閱 [`TOKEN` 授權方 Lambda 函數範例](apigateway-use-lambda-authorizer.md#api-gateway-lambda-authorizer-token-lambda-function-create)。

1.  設定 API 方法請求 API 金鑰，也在方法中啟用 Lambda 授權方。

1.  將 API 重新部署到同一個階段。如果您將 API 部署到新的階段，請務必更新用量計劃以連接新的 API 階段。

用戶端現在可以不用明確提供任何 API 金鑰，呼叫需要 API 金鑰的方法。自動使用授權方傳回的 API 金鑰。