

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

# API Gateway 中的 REST API 的請求驗證
<a name="api-gateway-method-request-validation"></a>

 您可以先設定 API Gateway 執行 API 請求的基本驗證，再繼續進行整合請求。驗證失敗時，API Gateway 會立即讓請求失敗、將 400 錯誤回應傳回給發起人，並在 CloudWatch Logs 中發布驗證結果。這樣可減少不必要的後端呼叫。更重要的是，它可讓您專注於應用程式特定的驗證努力。您可以驗證請求內文，方法為驗證必要的請求參數是否有效且為非 null 值，或指定模型結構描述進行更複雜的資料驗證。

**Topics**
+ [API Gateway 中的基本請求驗證概觀](#api-gateway-request-validation-basic-definitions)
+ [REST API 的資料模型](models-mappings-models.md)
+ [在 API Gateway 中設定基本請求驗證](api-gateway-request-validation-set-up.md)
+ [AWS CloudFormation 具有基本請求驗證的範例 API 範本](api-gateway-request-validation-sample-cloudformation.md)

## API Gateway 中的基本請求驗證概觀
<a name="api-gateway-request-validation-basic-definitions"></a>

 API Gateway 可以執行基本請求驗證，以便您可以專注於後端的應用程式特定驗證。針對驗證，API Gateway 會驗證下列任一或兩個條件：
+ 是否包含 URI 中的必要請求參數、查詢字串以及傳入請求的標頭，而且不是空白。API Gateway 只會檢查參數是否存在，而不會檢查類型或格式。
+  適用的請求承載會遵守方法中，針對所指內容類型設定的 [JSON 結構描述](https://datatracker.ietf.org/doc/html/draft-zyp-json-schema-04)請求。如果找不到相符的內容類型，則不會執行請求驗證。若無論內容類型為何都要使用相同的模型，請將資料模型的內容類型設定為 `$default`。

若要開啟驗證，您必須在[請求驗證程式](https://docs.aws.amazon.com/apigateway/latest/api/API_RequestValidator.html)中指定驗證規則、將驗證程式新增至 API 的[請求驗證程式對應](https://docs.aws.amazon.com/apigateway/latest/api/API_RequestValidator.html)，並將驗證程式指派給個別 API 方法。

**注意**  
請求內文驗證和 [API Gateway 中 REST API 沒有映射範本時，承載的方法請求行為](integration-passthrough-behaviors.md) 是兩個獨立的主題。當請求承載沒有相符的模型結構描述時，您可以選擇傳遞或封鎖原始承載。如需詳細資訊，請參閱[API Gateway 中 REST API 沒有映射範本時，承載的方法請求行為](integration-passthrough-behaviors.md)。

# REST API 的資料模型
<a name="models-mappings-models"></a>

在 API Gateway 中，模型會定義承載的資料結構。在 API Gateway 中，模型以 [JSON 結構描述草稿第 4 版](https://tools.ietf.org/html/draft-zyp-json-schema-04)定義。下列 JSON 物件是 Pet Store 範例中的範例資料。

```
{
    "id": 1,
    "type": "dog",
    "price": 249.99
}
```

資料包含寵物的 `id`、`type` 和 `price`。此資料的模型可讓您：
+ 使用基本請求驗證。
+ 建立對應範本進行資料轉換。
+ 產生 SDK 時，建立使用者定義的資料類型 (UDT)。

![\[PetStore API 的範例 JSON 資料模型。\]](http://docs.aws.amazon.com/zh_tw/apigateway/latest/developerguide/images/how-to-validate-requests.png)


在這個模型中：

1. `$schema` 物件代表有效的 JSON 結構描述版本識別符。此結構描述為 JSON 結構描述草稿第 4 版。

1. `title` 物件是人類看得懂的模型識別符。這個標題是 `PetStoreModel`。

1.  `required` 驗證關鍵字需要 `type` 和 `price`，才能進行基本請求驗證。

1. 模型的 `properties` 是 `id`、`type` 和 `price`。每個物件都有模型中描述的屬性。

1. 物件 `type` 只能具有值 `dog`、`cat` 或 `fish`。

1. 物件 `price` 是一個數字，且受到 `minimum` 為 25 且 `maximum` 為 500 的限制。

## PetStore 模型
<a name="PetStore-model-text"></a>

```
1 {
2 "$schema": "http://json-schema.org/draft-04/schema#",
3  "title": "PetStoreModel",
4  "type" : "object",
5  "required" : [ "price", "type" ],
6  "properties" : {
7    "id" : {
8      "type" : "integer"
9    },
10    "type" : {
11      "type" : "string",
12      "enum" : [ "dog", "cat", "fish" ]
13    },
14    "price" : {
15      "type" : "number",
16      "minimum" : 25.0,
17      "maximum" : 500.0
18    }
19  }
20 }
```

在這個模型中：

1. 在第 2 行，`$schema` 物件代表有效的 JSON 結構描述版本識別符。此結構描述為 JSON 結構描述草稿第 4 版。

1. 在第 3 行，`title` 物件是人類看得懂的模型識別符。這個標題是 `PetStoreModel`。

1.  在第 5 行，`required` 驗證關鍵字需要 `type` 和 `price`，才能進行基本請求驗證。

1.  在第 6 至 17 行，模型的 `properties` 是 `id`、`type` 和 `price`。每個物件都有模型中描述的屬性。

1. 在第 12 行，物件 `type` 只能具有值 `dog`、`cat` 或 `fish`。

1. 在第 14 至 17 行，物件 `price` 是一個數字，且受到 `minimum` 為 25 且 `maximum` 為 500 的限制。

## 建立更複雜的模型
<a name="api-gateway-request-validation-model-more-complex"></a>

 您可以使用 `$ref` 基本值，為較長的模型建立可重複使用的定義。例如，您可以在描述 `price` 物件的 `definitions` 區段中建立稱為 `Price` 的定義。`$ref` 的值是 `Price` 定義。

```
{
  "$schema" : "http://json-schema.org/draft-04/schema#",
  "title" : "PetStoreModelReUsableRef",
  "required" : ["price", "type" ],
  "type" : "object",
  "properties" : {
    "id" : {
      "type" : "integer"
    },
    "type" : {
      "type" : "string",
      "enum" : [ "dog", "cat", "fish" ]
    },
    "price" : {
        "$ref": "#/definitions/Price"
    }
  },
  "definitions" : {
      "Price": {
        "type" : "number",
        "minimum" : 25.0,
        "maximum" : 500.0
            }
      }
}
```

您也可以參考外部模型檔案中定義的另一個模型結構描述。將 `$ref` 屬性的值設定為模型的位置。在下列範例中，`Price` 模型是在 API `a1234` 的 `PetStorePrice` 模型中定義的。

```
{
  "$schema" : "http://json-schema.org/draft-04/schema#",
  "title" : "PetStorePrice",
  "type": "number",
  "minimum": 25,
  "maximum": 500
}
```

較長的模型可以參考 `PetStorePrice` 模型。

```
{
  "$schema" : "http://json-schema.org/draft-04/schema#",
  "title" : "PetStoreModelReusableRefAPI",
  "required" : [ "price", "type" ],
  "type" : "object",
  "properties" : {
    "id" : {
      "type" : "integer"
    },
    "type" : {
      "type" : "string",
      "enum" : [ "dog", "cat", "fish" ]
    },
    "price" : {
        "$ref": "https://apigateway.amazonaws.com/restapis/a1234/models/PetStorePrice"
    }
  }
}
```

## 使用輸出資料模型
<a name="api-gateway-request-validation-output-model"></a>

如果轉換您的資料，您可以在整合回應中定義承載模型。產生 SDK 時，可以使用承載模型。針對強型別語言 (例如 Java、Objective-C 或 Swift)，物件會對應到使用者定義的資料類型 (UDT)。如果您在產生 SDK 時透過資料模型提供 UDT，則 API Gateway 會建立該 UDT。如需資料轉型的詳細資訊，請參閱 [API Gateway 中 REST API 的映射範本轉換](models-mappings.md)。

下列範例是整合回應的輸出資料。

```
{
[
  {
    "description" : "Item 1 is a dog.",
    "askingPrice" : 249.99
  },
  {
    "description" : "Item 2 is a cat.",
    "askingPrice" : 124.99
  },
  {
    "description" : "Item 3 is a fish.",
    "askingPrice" : 0.99
  }
]
}
```

下列範例是描述輸出資料的承載模型。

```
{
"$schema": "http://json-schema.org/draft-04/schema#",
  "title": "PetStoreOutputModel",
  "type" : "object",
  "required" : [ "description", "askingPrice" ],
  "properties" : {
    "description" : {
      "type" : "string"
    },
    "askingPrice" : {
      "type" : "number",
      "minimum" : 25.0,
      "maximum" : 500.0
    }
  }
}
```

有了此模型，您可以呼叫 SDK，透過讀取 `PetStoreOutputModel[i].description` 和 `PetStoreOutputModel[i].askingPrice` 屬性，來擷取 `description` 和 `askingPrice` 屬性值。如果未提供模型，API Gateway 會使用空白模型來建立預設 UDT。

## 後續步驟
<a name="api-gateway-request-validation-model-next-steps"></a>
+ 本節提供的資源可讓您深入了解本主題中呈現的概念。

  您可以遵循請求驗證教學課程：
  + [使用 API Gateway 主控台設定請求驗證](api-gateway-request-validation-set-up.md#api-gateway-request-validation-setup-in-console)
  +  [使用 設定基本請求驗證 AWS CLI](api-gateway-request-validation-set-up.md#api-gateway-request-validation-setup-cli)
  +  [使用 OpenAPI 定義來設定基本請求驗證](api-gateway-request-validation-set-up.md#api-gateway-request-validation-setup-importing-swagger)
+  如需資料轉換和映射範本的詳細資訊，請參閱 [API Gateway 中 REST API 的映射範本轉換](models-mappings.md)。

# 在 API Gateway 中設定基本請求驗證
<a name="api-gateway-request-validation-set-up"></a>

 本節說明如何使用 主控台 AWS CLI和 OpenAPI 定義來設定 API Gateway 的請求驗證。

**Topics**
+ [使用 API Gateway 主控台設定請求驗證](#api-gateway-request-validation-setup-in-console)
+ [使用 設定基本請求驗證 AWS CLI](#api-gateway-request-validation-setup-cli)
+ [使用 OpenAPI 定義來設定基本請求驗證](#api-gateway-request-validation-setup-importing-swagger)

## 使用 API Gateway 主控台設定請求驗證
<a name="api-gateway-request-validation-setup-in-console"></a>

 您可以使用 API Gateway 主控台來驗證請求，方法是為 API 請求選取三個驗證程式之一：
+ **驗證內文**。
+ **驗證查詢字串參數和標頭**。
+ **驗證內文、查詢字串參數和標頭**。

 當您在 API 方法上套用其中一個驗證程式時，API Gateway 主控台會將驗證程式新增至 API 的 [RequestValidators](https://docs.aws.amazon.com/apigateway/latest/api/API_RequestValidator.html) 對應。

若要遵循本教學課程，您將使用 CloudFormation 範本來建立不完整的 API Gateway API。此 API 具有 `/validator` 資源，其中含有 `GET` 和 `POST` 方法。這兩種方法會與 `http://petstore-demo-endpoint.execute-api.com/petstore/pets` HTTP 端點整合。您將設定兩種請求驗證：
+ 在 `GET` 方法中，您將設定 URL 查詢字串參數的請求驗證。
+ 在 `POST` 方法中，您將設定請求內文的請求驗證。

 這將只允許某些 API 呼叫傳遞至 API。

下載並解壓縮 [的應用程式建立範本 CloudFormation](samples/request-validation-tutorial-console.zip)。您將使用此範本建立不完整的 API。您將完成 API Gateway 主控台中的其餘步驟。

**建立 CloudFormation 堆疊**

1. 在 https：//[https://console.aws.amazon.com/cloudformation](https://console.aws.amazon.com/cloudformation/) 開啟 CloudFormation 主控台。

1. 選擇 **Create stack (建立堆疊)**，然後選擇 **With new resources (standard) (使用新資源 (標準))**。

1. 對於 **Specify template (指定範本)**，選擇 **Upload a template file (上傳範本檔案)**。

1. 選取您下載的範本。

1. 選擇 **Next** (下一步)。

1. 針對 **Stack name (堆疊名稱)**，輸入 **request-validation-tutorial-console**，然後選擇 **Next (下一步)**。

1. 針對 **Configure stack options (設定堆疊選項)**，選擇 **Next (下一步)**。

1. 針對 **功能**，確認 CloudFormation 可以在您的帳戶中建立 IAM 資源。

1. 選擇**下一步**，然後選擇**提交**。

CloudFormation 會佈建範本中指定的資源。完成資源佈建可能需要幾分鐘的時間。當您的 CloudFormation 堆疊狀態為 **CREATE\$1COMPLETE** 時，您就可以繼續進行下一個步驟。

**選取新建立的 API**

1. 選取新建立的 **request-validation-tutorial-console** 堆疊。

1. 選擇**資源**。

1. 在**實體 ID** 下，選擇您的 API。此連結會將您導向至 API Gateway 主控台。

在修改 `GET` 和 `POST` 方法之前，您必須建立模型。

**建立裝置**

1. 需有模型才能在傳入請求的內文上使用請求驗證。若要建立模型，請在主導覽窗格中選擇**模型**。

1. 選擇**建立模型**。

1. 對於**名稱**，輸入 **PetStoreModel**。

1. 針對**內容類型**，輸入 **application/json**。如果找不到相符的內容類型，則不會執行請求驗證。若要使用相同的模型，而不論內容類型為何，請輸入 **\$1default**。

1. 對於**描述**，輸入 **My PetStore Model** 作為模型描述。

1. 對於**模型結構描述**，將下列模型貼入程式碼編輯器中，然後選擇**建立**。

   ```
   {
     "type" : "object",
     "required" : [ "name", "price", "type" ],
     "properties" : {
       "id" : {
         "type" : "integer"
       },
       "type" : {
         "type" : "string",
         "enum" : [ "dog", "cat", "fish" ]
       },
       "name" : {
         "type" : "string"
       },
       "price" : {
         "type" : "number",
         "minimum" : 25.0,
         "maximum" : 500.0
       }
     }
   }
   ```

如需關於模型的詳細資訊，請參閱[REST API 的資料模型](models-mappings-models.md)。

**設定 `GET` 方法的請求驗證**

1. 在主導覽窗格中，選擇**資源**，然後選取 **GET** 方法。

1. 在**方法請求**索引標籤的**方法請求設定**下，選擇**編輯**。

1. 對於**請求驗證程式**，選取**驗證查詢字串參數與標頭**。

1. 在 **URL 查詢字串參數**下，執行下列動作：

   1. 選擇**新增查詢字串**。

   1. 對於**名稱**，輸入 **petType**。

   1. 開啟**必要**。

   1. 讓**快取**保持關閉。

1. 選擇**儲存**。

1. 在**整合請求**索引標籤上，於**整合請求設定**下，選擇**編輯**。

1. 在 **URL 查詢字串參數**下，執行下列動作：

   1. 選擇**新增查詢字串**。

   1. 對於**名稱**，輸入 **petType**。

   1. 對於**映射自**，輸入 **method.request.querystring.petType**。這會將 **petType** 對應到寵物的類型。

      如需資料對應的詳細資訊，請參閱[資料對應教學課程](set-up-data-transformations-in-api-gateway.md#mapping-example-console)。

   1. 讓**快取**保持關閉。

1. 選擇**儲存**。

**測試 `GET` 方法的請求驗證**

1. 選擇**測試**標籤。您可能需要選擇向右箭頭按鈕才能顯示此索引標籤。

1. 對於**查詢字串**，輸入 **petType=dog**，然後選擇**測試**。

1. 方法測試會傳回 `200 OK` 及狗的清單。

   如需如何轉換此輸出資料的相關資訊，請參閱[資料對應教學課程](set-up-data-transformations-in-api-gateway.md#mapping-example-console)。

1. 移除 **petType=dog** 並選擇**測試**。

1.  方法測試會傳回 `400` 錯誤，並顯示下列錯誤訊息：

   ```
   {
     "message": "Missing required request parameters: [petType]"
   }
   ```

**設定 `POST` 方法的請求驗證**

1. 在主導覽窗格中，選擇**資源**，然後選取 **POST** 方法。

1. 在**方法請求**索引標籤的**方法請求設定**下，選擇**編輯**。

1. 對於**請求驗證程式**，選取**驗證內文**。

1. 在**請求內文**下，選擇**新增模型**。

1. 針對**內容類型**，輸入 **application/json**。如果找不到相符的內容類型，則不會執行請求驗證。若要使用相同的模型，而不論內容類型為何，請輸入 `$default`。

    對於**模型**，選取 **PetStoreModel**。

1. 選擇**儲存**。

**測試 `POST` 方法的請求驗證**

1. 選擇**測試**標籤。您可能需要選擇向右箭頭按鈕才能顯示此索引標籤。

1. 對於**請求內文**，將下列內容貼入程式碼編輯器中：

   ```
   {
     "id": 2,
     "name": "Bella",
     "type": "dog",
     "price": 400
   }
   ```

    選擇**測試**。

1. 方法測試會傳回 `200 OK` 和成功訊息。

1. 對於**請求內文**，將下列內容貼入程式碼編輯器中：

   ```
   {
     "id": 2,
     "name": "Bella",
     "type": "dog",
     "price": 4000
   }
   ```

    選擇**測試**。

1.  方法測試會傳回 `400` 錯誤，並顯示下列錯誤訊息：

   ```
   {
    "message": "Invalid request body"
   }
   ```

    測試日誌底部會傳回請求內文無效的原因。在此案例中，寵物的價格超出了模型中指定的最高價格。

**刪除 CloudFormation 堆疊**

1. 在 https：//[https://console.aws.amazon.com/cloudformation](https://console.aws.amazon.com/cloudformation/) 開啟 CloudFormation 主控台。

1. 選取您的 CloudFormation 堆疊。

1. 選擇**刪除**，然後確認您的選擇。

### 後續步驟
<a name="next-steps-request-validation-tutorial"></a>
+ 如需如何轉換輸出資料並執行其他資料對應的相關資訊，請參閱[資料對應教學課程](set-up-data-transformations-in-api-gateway.md#mapping-example-console)。
+ 遵循[使用 AWS CLI設定基本請求驗證](#api-gateway-request-validation-setup-cli)教學課程，以使用 AWS CLI執行類似的步驟。

## 使用 設定基本請求驗證 AWS CLI
<a name="api-gateway-request-validation-setup-cli"></a>

您可以使用 AWS CLI建立驗證程式來設定請求驗證。若要遵循本教學課程，您將使用 CloudFormation 範本來建立不完整的 API Gateway API。

**注意**  
這與主控台教學課程的 CloudFormation 範本不同。

 使用預先公開的 `/validator` 資源，您將建立 `GET` 和 `POST` 方法。這兩種方法會與 `http://petstore-demo-endpoint.execute-api.com/petstore/pets` HTTP 端點整合。您將設定下列兩個請求驗證：
+ 在 `GET` 方法上，您將建立 `params-only` 驗證程式來驗證 URL 查詢字串參數。
+ 在 `POST` 方法上，您將建立 `body-only` 驗證程式來驗證請求內文。

 這將只允許某些 API 呼叫傳遞至 API。

**建立 CloudFormation 堆疊**

下載並解壓縮 [的應用程式建立範本 CloudFormation](samples/request-validation-tutorial-cli.zip)。

若要完成下列教學課程，您需要 [AWS Command Line Interface (AWS CLI) 第 2 版](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)。

對於長命令，逸出字元 (`\`) 用於將命令分割為多行。
**注意**  
在 Windows 中，作業系統的內建終端機不支援您常用的某些 Bash CLI 命令 (例如 `zip`)。若要取得 Ubuntu 和 Bash 的 Windows 整合版本，請[安裝適用於 Linux 的 Windows 子系統](https://learn.microsoft.com/en-us/windows/wsl/install)。本指南中的 CLI 命令範例使用 Linux 格式。如果您使用的是 Windows CLI，必須重新格式化包含內嵌 JSON 文件的命令。

1.  使用下列命令來建立 CloudFormation 堆疊。

   ```
   aws cloudformation create-stack --stack-name request-validation-tutorial-cli --template-body file://request-validation-tutorial-cli.zip --capabilities CAPABILITY_NAMED_IAM 
   ```

1. CloudFormation 會佈建範本中指定的資源。完成資源佈建可能需要幾分鐘的時間。使用下列命令來查看 CloudFormation 堆疊的狀態。

   ```
   aws cloudformation describe-stacks --stack-name request-validation-tutorial-cli
   ```

1. 當您的 CloudFormation 堆疊狀態為 時`StackStatus: "CREATE_COMPLETE"`，請使用下列命令來擷取未來步驟的相關輸出值。

   ```
    aws cloudformation describe-stacks --stack-name request-validation-tutorial-cli --query "Stacks[*].Outputs[*].{OutputKey: OutputKey, OutputValue: OutputValue, Description: Description}"
   ```

   輸出值如下：
   + ApiId，這是 API 的 ID。對於本教學課程，API ID 為 `abc123`。
   + ResourceId，這是 `GET` 和 `POST` 方法公開所在驗證程式資源的 ID。對於本教學課程，資源 ID 為 `efg456`

**建立請求驗證程式並匯入模型**

1. 需有驗證程式才能搭配 AWS CLI使用請求驗證。使用下列命令建立僅驗證請求參數的驗證程式。

   ```
   aws apigateway create-request-validator --rest-api-id abc123 \
         --no-validate-request-body \
         --validate-request-parameters \
         --name params-only
   ```

   請記下 `params-only` 驗證程式的 ID。

1.  使用下列命令建立僅驗證請求內文的驗證程式。

   ```
   aws apigateway create-request-validator --rest-api-id abc123 \
         --validate-request-body \
         --no-validate-request-parameters \
         --name body-only
   ```

   請記下 `body-only` 驗證程式的 ID。

1.  需有模型才能在傳入請求的內文上使用請求驗證。使用下列命令匯入模型。

   ```
   aws apigateway create-model --rest-api-id abc123 --name PetStoreModel --description 'My PetStore Model' --content-type 'application/json' --schema '{"type": "object", "required" : [ "name", "price", "type" ], "properties" : { "id" : {"type" : "integer"},"type" : {"type" : "string", "enum" : [ "dog", "cat", "fish" ]},"name" : { "type" : "string"},"price" : {"type" : "number","minimum" : 25.0, "maximum" : 500.0}}}}' 
   ```

   如果找不到相符的內容類型，則不會執行請求驗證。若要使用相同的模型，而不論內容類型為何，請指定 `$default` 為索引鍵。

**建立 `GET` 和 `POST` 方法**

1. 使用下列命令，在 `/validate` 資源上新增 `GET` HTTP 方法。此命令會建立 `GET` 方法、新增 `params-only` 驗證程式，並視需要設定查詢字串 `petType`。

   ```
   aws apigateway put-method --rest-api-id abc123 \
          --resource-id efg456 \
          --http-method GET \
          --authorization-type "NONE" \
          --request-validator-id aaa111 \
          --request-parameters "method.request.querystring.petType=true"
   ```

   使用下列命令，在 `/validate` 資源上新增 `POST` HTTP 方法。此命令會建立 `POST` 方法、新增 `body-only` 驗證程式，並將模型附加至僅內文驗證程式。

   ```
   aws apigateway put-method --rest-api-id abc123 \
          --resource-id efg456 \
          --http-method POST \
          --authorization-type "NONE" \
          --request-validator-id bbb222 \
          --request-models 'application/json'=PetStoreModel
   ```

1.  使用下列命令設定 `GET /validate` 方法的 `200 OK` 回應。

   ```
   aws apigateway put-method-response --rest-api-id abc123  \
               --resource-id efg456 \
               --http-method GET \
               --status-code 200
   ```

    使用下列命令設定 `POST /validate` 方法的 `200 OK` 回應。

   ```
   aws apigateway put-method-response --rest-api-id abc123  \
               --resource-id efg456 \
               --http-method POST \
               --status-code 200
   ```

1.  使用下列命令，為 `GET /validation` 方法設定具有所指定 HTTP 端點的 `Integration`。

   ```
   aws apigateway put-integration --rest-api-id abc123  \
               --resource-id efg456 \
               --http-method GET \
               --type HTTP \
               --integration-http-method GET \
               --request-parameters '{"integration.request.querystring.type" : "method.request.querystring.petType"}' \
               --uri 'http://petstore-demo-endpoint.execute-api.com/petstore/pets'
   ```

    使用下列命令，為 `POST /validation` 方法設定具有所指定 HTTP 端點的 `Integration`。

   ```
   aws apigateway put-integration --rest-api-id abc123  \
                 --resource-id efg456 \
                 --http-method POST \
                 --type HTTP \
                 --integration-http-method GET \
                 --uri 'http://petstore-demo-endpoint.execute-api.com/petstore/pets'
   ```

1.  使用下列命令設定 `GET /validation` 方法的整合回應。

   ```
   aws apigateway put-integration-response --rest-api-id abc123 \
                 --resource-id efg456\
                 --http-method GET \
                 --status-code 200 \
                 --selection-pattern ""
   ```

    使用下列命令設定 `POST /validation` 方法的整合回應。

   ```
   aws apigateway put-integration-response --rest-api-id abc123 \
               --resource-id efg456 \
               --http-method POST \
               --status-code 200 \
               --selection-pattern ""
   ```

**若要測試 API**

1. 若要測試將為查詢字串執行請求驗證的 `GET` 方法，請使用下列命令：

   ```
   aws apigateway test-invoke-method --rest-api-id abc123 \
               --resource-id efg456 \
               --http-method GET \
               --path-with-query-string '/validate?petType=dog'
   ```

   結果將傳回 `200 OK` 和狗清單。

1. 在不包括查詢字串 `petType` 的情況下，使用下列命令進行測試，

   ```
   aws apigateway test-invoke-method --rest-api-id abc123 \
               --resource-id efg456 \
               --http-method GET
   ```

   結果將傳回 `400` 錯誤。

1. 若要測試將為請求內文執行請求驗證的 `POST` 方法，請使用下列命令：

   ```
    aws apigateway test-invoke-method --rest-api-id abc123 \
               --resource-id efg456 \
               --http-method POST \
               --body '{"id": 1, "name": "bella", "type": "dog", "price" : 400 }'
   ```

   結果將傳回 `200 OK` 和成功訊息。

1. 使用下列命令，以利用無效內文進行測試。

   ```
    aws apigateway test-invoke-method --rest-api-id abc123 \
                 --resource-id efg456 \
                 --http-method POST \
                 --body '{"id": 1, "name": "bella", "type": "dog", "price" : 1000 }'
   ```

   結果將傳回 `400` 錯誤，因為狗的價格超過了模型定義的最高價格。

**刪除 CloudFormation 堆疊**
+ 使用下列命令來刪除您的 CloudFormation 資源。

  ```
  aws cloudformation delete-stack  --stack-name request-validation-tutorial-cli
  ```

## 使用 OpenAPI 定義來設定基本請求驗證
<a name="api-gateway-request-validation-setup-importing-swagger"></a>

 您可以在 API 層級宣告請求驗證程式，方法是在 [x-amazon-apigateway-request-validators 物件](api-gateway-swagger-extensions-request-validators.md) 對應中指定一組 [x-amazon-apigateway-request-validators.requestValidator 物件](api-gateway-swagger-extensions-request-validators.requestValidator.md) 物件，以選取要驗證請求的哪一部分。在範例 OpenAPI 定義中，有兩個驗證程式：
+ `all` 驗證程式，其會同時驗證內文 (使用 `RequestBodyModel` 資料模型) 和參數。

  此 `RequestBodyModel` 資料模型要求輸入 JSON 物件包含 `name`、`type` 和 `price` 屬性。`name` 屬性可以是任意字串、`type` 必須是其中一個指定的列舉欄位 (`["dog", "cat", "fish"]`)，而 `price` 的範圍必須是 25 到 500。`id` 不是必要參數。
+ `param-only`，其僅會驗證參數。

 若要在 API 的所有方法上開啟請求驗證程式，請在 OpenAPI 定義的 API 層級指定 [x-amazon-apigateway-request-validator 屬性](api-gateway-swagger-extensions-request-validator.md) 屬性。在範例 OpenAPI 定義中，除非特別覆寫，否則會在所有 API 方法上使用 `all` 驗證程式。使用模型驗證主體時，如果找不到相符的內容類型，則不會執行請求驗證。若要使用相同的模型，而不論內容類型為何，請指定 `$default` 為索引鍵。

若要在個別方法上開啟請求驗證程式，請在方法層級指定 `x-amazon-apigateway-request-validator` 屬性。在範例 (OpenAPI 定義) 中，`param-only` 驗證程式會覆寫 `GET` 方法上的 `all` 驗證程式。



若要將 OpenAPI 範例匯入至 API Gateway，請參閱下列指示，[將區域 API 匯入至 API Gateway](import-export-api-endpoints.md) 或 [將邊緣最佳化 API 匯入至 API Gateway](import-edge-optimized-api.md)。

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

```
{
  "openapi" : "3.0.1",
  "info" : {
    "title" : "ReqValidators Sample",
    "version" : "1.0.0"
  },
  "servers" : [ {
    "url" : "/{basePath}",
    "variables" : {
      "basePath" : {
        "default" : "/v1"
      }
    }
  } ],
  "paths" : {
    "/validation" : {
      "get" : {
        "parameters" : [ {
          "name" : "q1",
          "in" : "query",
          "required" : true,
          "schema" : {
            "type" : "string"
          }
        } ],
        "responses" : {
          "200" : {
            "description" : "200 response",
            "headers" : {
              "test-method-response-header" : {
                "schema" : {
                  "type" : "string"
                }
              }
            },
            "content" : {
              "application/json" : {
                "schema" : {
                  "$ref" : "#/components/schemas/ArrayOfError"
                }
              }
            }
          }
        },
        "x-amazon-apigateway-request-validator" : "params-only",
        "x-amazon-apigateway-integration" : {
          "httpMethod" : "GET",
          "uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets",
          "responses" : {
            "default" : {
              "statusCode" : "400",
              "responseParameters" : {
                "method.response.header.test-method-response-header" : "'static value'"
              },
              "responseTemplates" : {
                "application/xml" : "xml 400 response template",
                "application/json" : "json 400 response template"
              }
            },
            "2\\d{2}" : {
              "statusCode" : "200"
            }
          },
          "requestParameters" : {
            "integration.request.querystring.type" : "method.request.querystring.q1"
          },
          "passthroughBehavior" : "when_no_match",
          "type" : "http"
        }
      },
      "post" : {
        "parameters" : [ {
          "name" : "h1",
          "in" : "header",
          "required" : true,
          "schema" : {
            "type" : "string"
          }
        } ],
        "requestBody" : {
          "content" : {
            "application/json" : {
              "schema" : {
                "$ref" : "#/components/schemas/RequestBodyModel"
              }
            }
          },
          "required" : true
        },
        "responses" : {
          "200" : {
            "description" : "200 response",
            "headers" : {
              "test-method-response-header" : {
                "schema" : {
                  "type" : "string"
                }
              }
            },
            "content" : {
              "application/json" : {
                "schema" : {
                  "$ref" : "#/components/schemas/ArrayOfError"
                }
              }
            }
          }
        },
        "x-amazon-apigateway-request-validator" : "all",
        "x-amazon-apigateway-integration" : {
          "httpMethod" : "POST",
          "uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets",
          "responses" : {
            "default" : {
              "statusCode" : "400",
              "responseParameters" : {
                "method.response.header.test-method-response-header" : "'static value'"
              },
              "responseTemplates" : {
                "application/xml" : "xml 400 response template",
                "application/json" : "json 400 response template"
              }
            },
            "2\\d{2}" : {
              "statusCode" : "200"
            }
          },
          "requestParameters" : {
            "integration.request.header.custom_h1" : "method.request.header.h1"
          },
          "passthroughBehavior" : "when_no_match",
          "type" : "http"
        }
      }
    }
  },
  "components" : {
    "schemas" : {
      "RequestBodyModel" : {
        "required" : [ "name", "price", "type" ],
        "type" : "object",
        "properties" : {
          "id" : {
            "type" : "integer"
          },
          "type" : {
            "type" : "string",
            "enum" : [ "dog", "cat", "fish" ]
          },
          "name" : {
            "type" : "string"
          },
          "price" : {
            "maximum" : 500.0,
            "minimum" : 25.0,
            "type" : "number"
          }
        }
      },
      "ArrayOfError" : {
        "type" : "array",
        "items" : {
          "$ref" : "#/components/schemas/Error"
        }
      },
      "Error" : {
        "type" : "object"
      }
    }
  },
  "x-amazon-apigateway-request-validators" : {
    "all" : {
      "validateRequestParameters" : true,
      "validateRequestBody" : true
    },
    "params-only" : {
      "validateRequestParameters" : true,
      "validateRequestBody" : false
    }
  }
}
```

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

```
{
  "swagger" : "2.0",
  "info" : {
    "version" : "1.0.0",
    "title" : "ReqValidators Sample"
  },
  "basePath" : "/v1",
  "schemes" : [ "https" ],
  "paths" : {
    "/validation" : {
      "get" : {
        "produces" : [ "application/json", "application/xml" ],
        "parameters" : [ {
          "name" : "q1",
          "in" : "query",
          "required" : true,
          "type" : "string"
        } ],
        "responses" : {
          "200" : {
            "description" : "200 response",
            "schema" : {
              "$ref" : "#/definitions/ArrayOfError"
            },
            "headers" : {
              "test-method-response-header" : {
                "type" : "string"
              }
            }
          }
        },
        "x-amazon-apigateway-request-validator" : "params-only",
        "x-amazon-apigateway-integration" : {
          "httpMethod" : "GET",
          "uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets",
          "responses" : {
            "default" : {
              "statusCode" : "400",
              "responseParameters" : {
                "method.response.header.test-method-response-header" : "'static value'"
              },
              "responseTemplates" : {
                "application/xml" : "xml 400 response template",
                "application/json" : "json 400 response template"
              }
            },
            "2\\d{2}" : {
              "statusCode" : "200"
            }
          },
          "requestParameters" : {
            "integration.request.querystring.type" : "method.request.querystring.q1"
          },
          "passthroughBehavior" : "when_no_match",
          "type" : "http"
        }
      },
      "post" : {
        "consumes" : [ "application/json" ],
        "produces" : [ "application/json", "application/xml" ],
        "parameters" : [ {
          "name" : "h1",
          "in" : "header",
          "required" : true,
          "type" : "string"
        }, {
          "in" : "body",
          "name" : "RequestBodyModel",
          "required" : true,
          "schema" : {
            "$ref" : "#/definitions/RequestBodyModel"
          }
        } ],
        "responses" : {
          "200" : {
            "description" : "200 response",
            "schema" : {
              "$ref" : "#/definitions/ArrayOfError"
            },
            "headers" : {
              "test-method-response-header" : {
                "type" : "string"
              }
            }
          }
        },
        "x-amazon-apigateway-request-validator" : "all",
        "x-amazon-apigateway-integration" : {
          "httpMethod" : "POST",
          "uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets",
          "responses" : {
            "default" : {
              "statusCode" : "400",
              "responseParameters" : {
                "method.response.header.test-method-response-header" : "'static value'"
              },
              "responseTemplates" : {
                "application/xml" : "xml 400 response template",
                "application/json" : "json 400 response template"
              }
            },
            "2\\d{2}" : {
              "statusCode" : "200"
            }
          },
          "requestParameters" : {
            "integration.request.header.custom_h1" : "method.request.header.h1"
          },
          "passthroughBehavior" : "when_no_match",
          "type" : "http"
        }
      }
    }
  },
  "definitions" : {
    "RequestBodyModel" : {
      "type" : "object",
      "required" : [ "name", "price", "type" ],
      "properties" : {
        "id" : {
          "type" : "integer"
        },
        "type" : {
          "type" : "string",
          "enum" : [ "dog", "cat", "fish" ]
        },
        "name" : {
          "type" : "string"
        },
        "price" : {
          "type" : "number",
          "minimum" : 25.0,
          "maximum" : 500.0
        }
      }
    },
    "ArrayOfError" : {
      "type" : "array",
      "items" : {
        "$ref" : "#/definitions/Error"
      }
    },
    "Error" : {
      "type" : "object"
    }
  },
  "x-amazon-apigateway-request-validators" : {
    "all" : {
      "validateRequestParameters" : true,
      "validateRequestBody" : true
    },
    "params-only" : {
      "validateRequestParameters" : true,
      "validateRequestBody" : false
    }
  }
}
```

------

# AWS CloudFormation 具有基本請求驗證的範例 API 範本
<a name="api-gateway-request-validation-sample-cloudformation"></a>

 下列 CloudFormation 範例範本定義會定義已啟用請求驗證的範例 API。API 是 [PetStore API](http://petstore-demo-endpoint.execute-api.com/petstore/pets) 的子集。它會公開 `POST` 方法以將寵物新增至 `pets` 集合，並公開 `GET` 方法以依指定的類型來查詢寵物。

 這裡會宣告兩種請求驗證程式：

**`GETValidator`**  
此驗證程式會在 `GET` 方法上啟用。它可讓 API Gateway 驗證傳入請求中已包含不是空白的必要查詢參數 (`q1`)。

**`POSTValidator`**  
此驗證程式會在 `POST` 方法上啟用。它可讓 API Gateway 驗證，當內容類型為 `application/json` 時，承載請求格式是否遵循指定的 `RequestBodyModel`，如果找不到相符的內容類型，則不會執行請求驗證。若無論內容類型為何都要使用相同的模型，可指定 `$default`。`RequestBodyModel` 包含一個額外的模型 `RequestBodyModelId`，用於定義寵物 ID。

```
AWSTemplateFormatVersion: 2010-09-09
Parameters:
  StageName:
    Type: String
    Default: v1
    Description: Name of API stage.
Resources:
  Api:
    Type: 'AWS::ApiGateway::RestApi'
    Properties:
      Name: ReqValidatorsSample
  RequestBodyModelId:
    Type: 'AWS::ApiGateway::Model'
    Properties:
      RestApiId: !Ref Api
      ContentType: application/json
      Description: Request body model for Pet ID.
      Schema:
        $schema: 'http://json-schema.org/draft-04/schema#'
        title: RequestBodyModelId
        properties:
            id:
              type: integer
  RequestBodyModel: 
    Type: 'AWS::ApiGateway::Model'
    Properties:
      RestApiId: !Ref Api
      ContentType: application/json
      Description: Request body model for Pet type, name, price, and ID.
      Schema:
        $schema: 'http://json-schema.org/draft-04/schema#'
        title: RequestBodyModel
        required:
          - price
          - name
          - type
        type: object
        properties:
            id:
              "$ref": !Sub 
                - 'https://apigateway.amazonaws.com/restapis/${Api}/models/${RequestBodyModelId}'
                - Api: !Ref Api
                  RequestBodyModelId: !Ref RequestBodyModelId
            price: 
              type: number
              minimum: 25
              maximum: 500
            name:
              type: string
            type:
              type: string
              enum:
                - "dog"
                - "cat"
                - "fish"
  GETValidator:
    Type: AWS::ApiGateway::RequestValidator
    Properties:
      Name: params-only
      RestApiId: !Ref Api
      ValidateRequestBody: False
      ValidateRequestParameters: True 
  POSTValidator:
    Type: AWS::ApiGateway::RequestValidator
    Properties:
      Name: body-only
      RestApiId: !Ref Api
      ValidateRequestBody: True
      ValidateRequestParameters: False
  ValidationResource:
    Type: 'AWS::ApiGateway::Resource'
    Properties:
      RestApiId: !Ref Api
      ParentId: !GetAtt Api.RootResourceId
      PathPart: 'validation'
  ValidationMethodGet:
    Type: 'AWS::ApiGateway::Method'
    Properties:
      RestApiId: !Ref Api
      ResourceId: !Ref ValidationResource
      HttpMethod: GET
      AuthorizationType: NONE
      RequestValidatorId: !Ref GETValidator
      RequestParameters:
        method.request.querystring.q1: true
      Integration:
        Type: HTTP_PROXY
        IntegrationHttpMethod: GET
        Uri: http://petstore-demo-endpoint.execute-api.com/petstore/pets/
  ValidationMethodPost:
    Type: 'AWS::ApiGateway::Method'
    Properties:
      RestApiId: !Ref Api
      ResourceId: !Ref ValidationResource
      HttpMethod: POST
      AuthorizationType: NONE
      RequestValidatorId: !Ref POSTValidator
      RequestModels:
        application/json : !Ref RequestBodyModel 
      Integration:
        Type: HTTP_PROXY
        IntegrationHttpMethod: POST
        Uri: http://petstore-demo-endpoint.execute-api.com/petstore/pets/
  ApiDeployment:
    Type: 'AWS::ApiGateway::Deployment'
    DependsOn:
      - ValidationMethodGet
      - RequestBodyModel 
    Properties:
      RestApiId: !Ref Api
      StageName: !Sub '${StageName}'
Outputs:
  ApiRootUrl:
    Description: Root Url of the API
    Value: !Sub 'https://${Api}.execute-api.${AWS::Region}.amazonaws.com/${StageName}'
```