

# Request validation for REST APIs in API Gateway
<a name="api-gateway-method-request-validation"></a>

 You can configure API Gateway to perform basic validation of an API request before proceeding with the integration request. When the validation fails, API Gateway immediately fails the request, returns a 400 error response to the caller, and publishes the validation results in CloudWatch Logs. This reduces unnecessary calls to the backend. More importantly, it lets you focus on the validation efforts specific to your application. You can validate a request body by verifying that required request parameters are valid and non-null or by specifying a model schema for more complicated data validation.

**Topics**
+ [

## Overview of basic request validation in API Gateway
](#api-gateway-request-validation-basic-definitions)
+ [

# Data models for REST APIs
](models-mappings-models.md)
+ [

# Set up basic request validation in API Gateway
](api-gateway-request-validation-set-up.md)
+ [

# AWS CloudFormation template of a sample API with basic request validation
](api-gateway-request-validation-sample-cloudformation.md)

## Overview of basic request validation in API Gateway
<a name="api-gateway-request-validation-basic-definitions"></a>

 API Gateway can perform the basic request validation, so that you can focus on app-specific validation in the backend. For validation, API Gateway verifies either or both of the following conditions: 
+ The required request parameters in the URI, query string, and headers of an incoming request are included and not blank. API Gateway only checks the existence of a parameter and doesn't check the type or format.
+  The applicable request payload adheres to the configured [JSON schema](https://datatracker.ietf.org/doc/html/draft-zyp-json-schema-04) request of the method for a given content type. If no matching content type is found, request validation is not performed. To use the same model regardless of the content type, set the content type for your data model to `$default`.

To turn on validation, you specify validation rules in a [request validator](https://docs.aws.amazon.com/apigateway/latest/api/API_RequestValidator.html), add the validator to the API's [map of request validators](https://docs.aws.amazon.com/apigateway/latest/api/API_RequestValidator.html), and assign the validator to individual API methods. 

**Note**  
Request body validation and [Method request behavior for payloads without mapping templates for REST APIs in API Gateway](integration-passthrough-behaviors.md) are two separate topics. When a request payload does not have a matching model schema, you can choose to passthrough or block the original payload. For more information, see [Method request behavior for payloads without mapping templates for REST APIs in API Gateway](integration-passthrough-behaviors.md).

# Data models for REST APIs
<a name="models-mappings-models"></a>

In API Gateway, a model defines the data structure of a payload. In API Gateway, models are defined using the [JSON schema draft 4](https://tools.ietf.org/html/draft-zyp-json-schema-04). The following JSON object is sample data in the Pet Store example.

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

The data contains the `id`, `type`, and `price` of the pet. A model of this data allows you to:
+ Use basic request validation.
+ Create mapping templates for data transformation.
+ Create a user-defined data type (UDT) when you generate an SDK.

![\[Example JSON data model for PetStore API.\]](http://docs.aws.amazon.com/apigateway/latest/developerguide/images/how-to-validate-requests.png)


In this model:

1. The `$schema` object represents a valid JSON Schema version identifier. This schema is the JSON Schema draft v4.

1. The `title` object is a human-readable identifier for the model. This title is `PetStoreModel`.

1.  The `required` validation keyword requires `type`, and `price` for basic request validation.

1. The `properties` of the model are `id`, `type`, and `price`. Each object has properties that are described in the model.

1. The object `type` can have only the values `dog`, `cat`, or `fish`.

1. The object `price` is a number and is constrained with a `minimum` of 25 and a `maximum` of 500.

## PetStore model
<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 }
```

In this model:

1. On line 2, the `$schema` object represents a valid JSON Schema version identifier. This schema is the JSON Schema draft v4.

1. On line 3, the `title` object is a human-readable identifier for the model. This title is `PetStoreModel`.

1.  On line 5, the `required` validation keyword requires `type`, and `price` for basic request validation.

1.  On lines 6 -- 17, the `properties` of the model are `id`, `type`, and `price`. Each object has properties that are described in the model.

1. On line 12, the object `type` can have only the values `dog`, `cat`, or `fish`.

1. On lines 14 -- 17, the object `price` is a number and is constrained with a `minimum` of 25 and a `maximum` of 500.

## Creating more complex models
<a name="api-gateway-request-validation-model-more-complex"></a>

 You can use the `$ref` primitive to create reusable definitions for longer models. For example, you can create a definition called `Price` in the `definitions` section describing the `price` object. The value of `$ref` is the `Price` definition. 

```
{
  "$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
            }
      }
}
```

You can also reference another model schema defined in an external model file. Set the value of the `$ref` property to the location of the model. In the following example, the `Price` model is defined in the `PetStorePrice` model in API `a1234`.

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

The longer model can reference the `PetStorePrice` model.

```
{
  "$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"
    }
  }
}
```

## Using output data models
<a name="api-gateway-request-validation-output-model"></a>

If you transform your data, you can define a payload model in the integration response. A payload model can be used when you generate an SDK. For strongly typed languages, such as Java, Objective-C, or Swift, the object corresponds to a user-defined data type (UDT). API Gateway creates a UDT if you provide it with a data model when you generate an SDK. For more information about data transformations, see [Mapping template transformations for REST APIs in API Gateway](models-mappings.md).

The following example is output data from an integration response.

```
{
[
  {
    "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
  }
]
}
```

The following example is a payload model that describes the output data.

```
{
"$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
    }
  }
}
```

With this model, you can call an SDK to retrieve the `description` and `askingPrice` property values by reading the `PetStoreOutputModel[i].description` and `PetStoreOutputModel[i].askingPrice` properties. If no model is provided, API Gateway uses the empty model to create a default UDT. 

## Next steps
<a name="api-gateway-request-validation-model-next-steps"></a>
+ This section provides resources that you can use to gain more knowledge about the concepts presented in this topic.

  You can follow the request validation tutorials:
  + [Set up request validation using the API Gateway console](api-gateway-request-validation-set-up.md#api-gateway-request-validation-setup-in-console)
  +  [Set up basic request validation using the AWS CLI](api-gateway-request-validation-set-up.md#api-gateway-request-validation-setup-cli)
  +  [Set up basic request validation using an OpenAPI definition](api-gateway-request-validation-set-up.md#api-gateway-request-validation-setup-importing-swagger)
+  For more information about data transformation and mapping templates, [Mapping template transformations for REST APIs in API Gateway](models-mappings.md).

# Set up basic request validation in API Gateway
<a name="api-gateway-request-validation-set-up"></a>

 This section shows how to set up request validation for API Gateway using the console, AWS CLI, and an OpenAPI definition.

**Topics**
+ [

## Set up request validation using the API Gateway console
](#api-gateway-request-validation-setup-in-console)
+ [

## Set up basic request validation using the AWS CLI
](#api-gateway-request-validation-setup-cli)
+ [

## Set up basic request validation using an OpenAPI definition
](#api-gateway-request-validation-setup-importing-swagger)

## Set up request validation using the API Gateway console
<a name="api-gateway-request-validation-setup-in-console"></a>

 You can use the API Gateway console to validate a request by selecting one of three validators for an API request: 
+ **Validate body**.
+ **Validate query string parameters and headers**.
+ **Validate body, query string parameters, and headers**.

 When you apply one of the validators on an API method, the API Gateway console adds the validator to the API's [RequestValidators](https://docs.aws.amazon.com/apigateway/latest/api/API_RequestValidator.html) map.

To follow this tutorial, you'll use an CloudFormation template to create an incomplete API Gateway API. This API has a `/validator` resource with `GET` and `POST` methods. Both methods are integrated with the `http://petstore-demo-endpoint.execute-api.com/petstore/pets` HTTP endpoint. You will configure two kinds of request validation:
+ In the `GET` method, you will configure request validation for URL query string parameters.
+ In the `POST` method, you will configure request validation for the request body.

 This will allow only certain API calls to pass through to the API. 

Download and unzip [the app creation template for CloudFormation](samples/request-validation-tutorial-console.zip). You'll use this template to create an incomplete API. You will finish the rest of the steps in the API Gateway console. 

**To create an CloudFormation stack**

1. Open the CloudFormation console at [https://console.aws.amazon.com/cloudformation](https://console.aws.amazon.com/cloudformation/).

1. Choose **Create stack** and then choose **With new resources (standard)**.

1. For **Specify template**, choose **Upload a template file**.

1. Select the template that you downloaded.

1. Choose **Next**. 

1. For **Stack name**, enter **request-validation-tutorial-console** and then choose **Next**.

1. For **Configure stack options**, choose **Next**.

1. For **Capabilities**, acknowledge that CloudFormation can create IAM resources in your account.

1. Choose **Next**, and then choose **Submit**.

CloudFormation provisions the resources specified in the template. It can take a few minutes to finish provisioning your resources. When the status of your CloudFormation stack is **CREATE\$1COMPLETE**, you're ready to move on to the next step.

**To select your newly created API**

1. Select the newly created **request-validation-tutorial-console** stack.

1. Choose **Resources**.

1. Under **Physical ID**, choose your API. This link will direct you to the API Gateway console.

Before you modify the `GET` and `POST` methods, you must create a model.

**To create a model**

1. A model is required to use request validation on the body of an incoming request. To create a model, in the main navigation pane, choose **Models**.

1. Choose **Create model**.

1. For **Name**, enter **PetStoreModel**.

1. For **Content Type**, enter **application/json**. If no matching content type is found, request validation is not performed. To use the same model regardless of the content type, enter **\$1default**.

1. For **Description**, enter **My PetStore Model** as the model description.

1. For **Model schema**, paste the following model into the code editor, and choose **Create**. 

   ```
   {
     "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
       }
     }
   }
   ```

For more information about the model, see [Data models for REST APIs](models-mappings-models.md). 

**To configure request validation for a `GET` method**

1. In the main navigation pane, choose **Resources**, and then select the **GET** method. 

1. On the **Method request** tab, under **Method request settings**, choose **Edit**.

1. For **Request validator**, select **Validate query string parameters and headers**.

1. Under **URL query string parameters**, do the following: 

   1. Choose **Add query string**.

   1. For **Name**, enter **petType**.

   1. Turn on **Required**.

   1. Keep **Caching** turned off. 

1. Choose **Save**.

1. On the **Integration request** tab, under **Integration request settings**, choose **Edit**.

1. Under **URL query string parameters**, do the following: 

   1. Choose **Add query string**.

   1. For **Name**, enter **petType**.

   1. For **Mapped from**, enter **method.request.querystring.petType**. This maps the **petType** to the pet's type.

      For more information about data mapping, see [ the data mapping tutorial](set-up-data-transformations-in-api-gateway.md#mapping-example-console).

   1. Keep **Caching** turned off. 

1. Choose **Save**.

**To test request validation for the `GET` method**

1. Choose the **Test** tab. You might need to choose the right arrow button to show the tab.

1. For **Query strings**, enter **petType=dog**, and then choose **Test**.

1. The method test will return `200 OK` and a list of dogs.

   For information about how to transform this output data, see the [data mapping tutorial.](set-up-data-transformations-in-api-gateway.md#mapping-example-console)

1. Remove **petType=dog** and choose **Test**. 

1.  The method test will return a `400` error with the following error message: 

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

**To configure request validation for the `POST` method**

1. In the main navigation pane, choose **Resources**, and then select the **POST** method. 

1. On the **Method request** tab, under **Method request settings**, choose **Edit**.

1. For **Request validator**, select **Validate body**.

1. Under **Request body**, choose **Add model**.

1. For **Content type**, enter **application/json**. If no matching content type is found, request validation is not performed. To use the same model regardless of the content type, enter `$default`.

    For **Model**, select **PetStoreModel**.

1. Choose **Save**.

**To test request validation for a `POST` method**

1. Choose the **Test** tab. You might need to choose the right arrow button to show the tab.

1. For **Request body** paste the following into the code editor:

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

    Choose **Test**.

1. The method test will return `200 OK` and a success message. 

1. For **Request body** paste the following into the code editor:

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

    Choose **Test**. 

1.  The method test will return a `400` error with the following error message:

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

    At the bottom of the test logs, the reason for the invalid request body is returned. In this case, the price of the pet was outside the maximum specified in the model. 

**To delete an CloudFormation stack**

1. Open the CloudFormation console at [https://console.aws.amazon.com/cloudformation](https://console.aws.amazon.com/cloudformation/).

1. Select your CloudFormation stack.

1. Choose **Delete** and then confirm your choice.

### Next steps
<a name="next-steps-request-validation-tutorial"></a>
+ For information about how to transform output data and perform more data mapping, see the [data mapping tutorial](set-up-data-transformations-in-api-gateway.md#mapping-example-console).
+ Follow the [ Set up basic request validation using the AWS CLI](#api-gateway-request-validation-setup-cli) tutorial, to do similar steps using the AWS CLI. 

## Set up basic request validation using the AWS CLI
<a name="api-gateway-request-validation-setup-cli"></a>

You can create a validator to set up request validation using the AWS CLI. To follow this tutorial, you'll use an CloudFormation template to create an incomplete API Gateway API. 

**Note**  
This is not the same CloudFormation template as the console tutorial.

 Using a pre-exposed `/validator`resource, you will create `GET` and `POST` methods. Both methods will be integrated with the `http://petstore-demo-endpoint.execute-api.com/petstore/pets` HTTP endpoint. You will configure the following two request validations:
+ On the `GET` method, you will create a `params-only` validator to validate URL query string parameters.
+ On the `POST` method, you will create a `body-only` validator to validate the request body.

 This will allow only certain API calls to pass through to the API. 

**To create an CloudFormation stack**

Download and unzip [the app creation template for CloudFormation](samples/request-validation-tutorial-cli.zip). 

To complete the following tutorial, you need the [AWS Command Line Interface (AWS CLI) version 2](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html). 

For long commands, an escape character (`\`) is used to split a command over multiple lines.
**Note**  
In Windows, some Bash CLI commands that you commonly use (such as `zip`) are not supported by the operating system's built-in terminals. To get a Windows-integrated version of Ubuntu and Bash, [install the Windows Subsystem for Linux](https://learn.microsoft.com/en-us/windows/wsl/install). Example CLI commands in this guide use Linux formatting. Commands which include inline JSON documents must be reformatted if you are using the Windows CLI. 

1.  Use the following command to create the CloudFormation stack.

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

1. CloudFormation provisions the resources specified in the template. It can take a few minutes to finish provisioning your resources. Use the following command to see the status of your CloudFormation stack.

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

1. When the status of your CloudFormation stack is `StackStatus: "CREATE_COMPLETE"`, use the following command to retrieve relevant output values for future steps.

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

   The output values are the following:
   + ApiId, which is the ID for the API. For this tutorial, the API ID is `abc123`.
   + ResourceId, which is the ID for the validator resource where the `GET` and `POST` methods are exposed. For this tutorial, the Resource ID is `efg456`

**To create the request validators and import a model**

1. A validator is required to use request validation with the AWS CLI. Use the following command to create a validator that validates only request parameters. 

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

   Note the ID of the `params-only` validator.

1.  Use the following command to create a validator that validates only the request body. 

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

   Note the ID of the `body-only` validator.

1.  A model is required to use request validation on the body of an incoming request. Use the following command to import a model.

   ```
   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}}}}' 
   ```

   If no matching content type is found, request validation is not performed. To use the same model regardless of the content type, specify `$default` as the key.

**To create the `GET` and `POST` methods**

1. Use the following command to add the `GET` HTTP method on the `/validate` resource. This command creates the `GET`method, adds the `params-only` validator, and sets the query string `petType` as required. 

   ```
   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"
   ```

   Use the following command to add the `POST` HTTP method on the `/validate` resource. This command creates the `POST`method, adds the `body-only` validator, and attaches the model to the body-only validator. 

   ```
   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.  Use the following command to set up the `200 OK` response of the `GET /validate` method. 

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

    Use the following command to set up the `200 OK` response of the `POST /validate` method.

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

1.  Use the following command to set up an `Integration` with a specified HTTP endpoint for the `GET /validation` method. 

   ```
   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'
   ```

    Use the following command to set up an `Integration` with a specified HTTP endpoint for the `POST /validation` method. 

   ```
   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.  Use the following command to set up an integration response for the `GET /validation` method. 

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

    Use the following command to set up an integration response for the `POST /validation` method.

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

**To test the API**

1. To test the `GET` method, which will perform request validation for the query strings, use the following command:

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

   The result will return a `200 OK` and list of dogs.

1. Use the following command to test without including the query string `petType`

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

   The result will return a `400` error.

1. To test the `POST` method, which will perform request validation for the request body, use the following command:

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

   The result will return a `200 OK` and a success message. 

1. Use the following command to test using an invalid body.

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

   The result will return a `400` error, as the price of the dog is over the maximum price defined by the model.

**To delete an CloudFormation stack**
+ Use the following command to delete your CloudFormation resources.

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

## Set up basic request validation using an OpenAPI definition
<a name="api-gateway-request-validation-setup-importing-swagger"></a>

 You can declare a request validator at the API level by specifying a set of the [x-amazon-apigateway-request-validators.requestValidator object](api-gateway-swagger-extensions-request-validators.requestValidator.md) objects in the [x-amazon-apigateway-request-validators object](api-gateway-swagger-extensions-request-validators.md) map to select what part of the request will be validated. In the example OpenAPI definition, there are two validators: 
+ `all` validator which validates both the body, using the `RequestBodyModel` data model, and the parameters.

  The `RequestBodyModel` data model requires that the input JSON object contains the `name`, `type`, and `price` properties. The `name` property can be any string, `type` must be one of the specified enumeration fields (`["dog", "cat", "fish"]`), and `price` must range between 25 and 500. The `id` parameter is not required. 
+ `param-only` which validates only the parameters.

 To turn a request validator on all methods of an API, specify an [x-amazon-apigateway-request-validator property](api-gateway-swagger-extensions-request-validator.md) property at the API level of the OpenAPI definition. In the example OpenAPI definition, the `all` validator is used on all API methods, unless otherwise overridden. When using a model to validate the body, if no matching content type is found, request validation is not performed. To use the same model regardless of the content type, specify `$default` as the key.

To turn on a request validator on an individual method, specify the `x-amazon-apigateway-request-validator` property at the method level. In the example, OpenAPI definition, the `param-only` validator overwrites the `all` validator on the `GET` method.



To import the OpenAPI example into API Gateway, see the following instructions to [Import a Regional API into API Gateway](import-export-api-endpoints.md) or to [Import an edge-optimized API into 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 template of a sample API with basic request validation
<a name="api-gateway-request-validation-sample-cloudformation"></a>

 The following CloudFormation example template definition defines a sample API with request validation enabled. The API is a subset of the [PetStore API](http://petstore-demo-endpoint.execute-api.com/petstore/pets). It exposes a `POST` method to add a pet to the `pets` collection and a `GET` method to query pets by a specified type. 

 There are two request validators declared:

**`GETValidator`**  
This validator is enabled on the `GET` method. It allows API Gateway to verify that the required query parameter (`q1`) is included and not blank in the incoming request. 

**`POSTValidator`**  
This validator is enabled on the `POST` method. It allows API Gateway to verify that payload request format adheres to the specified `RequestBodyModel` when the content type is `application/json` if no matching content type is found, request validation is not performed. To use the same model regardless of the content type, specify `$default`. `RequestBodyModel` contains an additional model, `RequestBodyModelId`, to define the pet 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}'
```