Set up basic request validation in API Gateway
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
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 map.
To follow this tutorial, you'll use an AWS 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
GETmethod, you will configure request validation for URL query string parameters. -
In the
POSTmethod, 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 AWS CloudFormation. 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 AWS CloudFormation stack
Open the AWS CloudFormation console at https://console.aws.amazon.com/cloudformation
. -
Choose Create stack and then choose With new resources (standard).
-
For Specify template, choose Upload a template file.
-
Select the template that you downloaded.
-
Choose Next.
-
For Stack name, enter
request-validation-tutorial-consoleand then choose Next. -
For Configure stack options, choose Next.
-
For Capabilities, acknowledge that AWS CloudFormation can create IAM resources in your account.
-
Choose Submit.
AWS CloudFormation provisions the resources specified in the template. It can take a few minutes to finish provisioning your resources. When the status of your AWS CloudFormation stack is CREATE_COMPLETE, you're ready to move on to the next step.
To select your newly created API
Select the newly created
request-validation-tutorial-consolestack.Choose Resources.
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
-
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.
-
Choose Create model.
-
For Name, enter
PetStoreModel. -
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 Description, enter
My PetStore Modelas the model description. -
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.
To configure request validation for a GET method
-
In the main navigation pane, choose Resources, and then select the GET method.
-
On the Method request tab, under Method request settings, choose Edit.
-
For Request validator, select Validate query string parameters and headers.
Under URL query string parameters, do the following:
Choose Add query string.
For Name, enter
petType.Turn on Required.
Keep Caching turned off.
-
Choose Save.
-
On the Integration request tab, under Integration request settings, choose Edit.
Under URL query string parameters, do the following:
Choose Add query string.
For Name, enter
petType.For Mapped from, enter
method.request.querystring.petType. This maps thepetTypeto the pet's type.For more information about data mapping, see the data mapping tutorial.
Keep Caching turned off.
Choose Save.
To test request validation for the GET method
-
Choose the Test tab. You might need to choose the right arrow button to show the tab.
-
For Query strings, enter
petType=dog, and then choose Test. -
The method test will return
200 OKand a list of dogs.For information about how to transform this output data, see the data mapping tutorial.
-
Remove
petType=dogand choose Test. -
The method test will return a
400error with the following error message:{ "message": "Missing required request parameters: [petType]" }
To configure request validation for the POST method
-
In the main navigation pane, choose Resources, and then select the POST method.
-
On the Method request tab, under Method request settings, choose Edit.
-
For Request validator, select Validate body.
-
Under Request body, choose Add model.
-
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.
Choose Save.
To test request validation for a POST method
-
Choose the Test tab. You might need to choose the right arrow button to show the tab.
-
For Request body paste the following into the code editor:
{ "id": 2, "name": "Bella", "type": "dog", "price": 400 }Choose Test.
-
The method test will return
200 OKand a success message. -
For Request body paste the following into the code editor:
{ "id": 2, "name": "Bella", "type": "dog", "price": 4000 }Choose Test.
-
The method test will return a
400error 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 AWS CloudFormation stack
Open the AWS CloudFormation console at https://console.aws.amazon.com/cloudformation
. -
Select your AWS CloudFormation stack.
-
Choose Delete and then confirm your choice.
Next steps
For information about how to transform output data and perform more data mapping, see the data mapping tutorial.
Follow the Set up basic request validation using the AWS CLI tutorial, to do similar steps using the AWS CLI.
Set up basic request validation using the AWS CLI
You can create a validator to set up request validation using the AWS CLI. To follow this tutorial, you'll use an AWS CloudFormation template to create an incomplete API Gateway API.
Note
This is not the same AWS CloudFormation template as the console tutorial.
Using a pre-exposed /validatorresource, 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
GETmethod, you will create aparams-onlyvalidator to validate URL query string parameters. -
On the
POSTmethod, you will create abody-onlyvalidator to validate the request body.
This will allow only certain API calls to pass through to the API.
To create an AWS CloudFormation stack
Download and unzip the app creation template for AWS CloudFormation.
To complete the following tutorial, you need the AWS Command Line Interface (AWS CLI) version 2.
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
Use the following command to create the AWS CloudFormation stack.
aws cloudformation create-stack --stack-name request-validation-tutorial-cli --template-body file://request-validation-tutorial-cli.zip --capabilities CAPABILITY_NAMED_IAM-
AWS 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 AWS CloudFormation stack.
aws cloudformation describe-stacks --stack-name request-validation-tutorial-cli -
When the status of your AWS 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
GETandPOSTmethods are exposed. For this tutorial, the Resource ID isefg456
To create the request validators and import a model
-
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-idabc123\ --no-validate-request-body \ --validate-request-parameters \ --name params-onlyNote the ID of the
params-onlyvalidator. -
Use the following command to create a validator that validates only the request body.
aws apigateway create-request-validator --rest-api-idabc123\ --validate-request-body \ --no-validate-request-parameters \ --name body-onlyNote the ID of the
body-onlyvalidator. -
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-idabc123--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
$defaultas the key.
To create the GET and POST methods
-
Use the following command to add the
GETHTTP method on the/validateresource. This command creates theGETmethod, adds theparams-onlyvalidator, and sets the query stringpetTypeas required.aws apigateway put-method --rest-api-idabc123\ --resource-idefg456\ --http-method GET \ --authorization-type "NONE" \ --request-validator-idaaa111\ --request-parameters "method.request.querystring.petType=true"Use the following command to add the
POSTHTTP method on the/validateresource. This command creates thePOSTmethod, adds thebody-onlyvalidator, and attaches the model to the body-only validator.aws apigateway put-method --rest-api-idabc123\ --resource-idefg456\ --http-method POST \ --authorization-type "NONE" \ --request-validator-idbbb222\ --request-models 'application/json'=PetStoreModel -
Use the following command to set up the
200 OKresponse of theGET /validatemethod.aws apigateway put-method-response --rest-api-idabc123\ --resource-idefg456\ --http-method GET \ --status-code 200Use the following command to set up the
200 OKresponse of thePOST /validatemethod.aws apigateway put-method-response --rest-api-idabc123\ --resource-idefg456\ --http-method POST \ --status-code 200 -
Use the following command to set up an
Integrationwith a specified HTTP endpoint for theGET /validationmethod.aws apigateway put-integration --rest-api-idabc123\ --resource-idefg456\ --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
Integrationwith a specified HTTP endpoint for thePOST /validationmethod.aws apigateway put-integration --rest-api-idabc123\ --resource-idefg456\ --http-method POST \ --type HTTP \ --integration-http-method GET \ --uri 'http://petstore-demo-endpoint.execute-api.com/petstore/pets' -
Use the following command to set up an integration response for the
GET /validationmethod.aws apigateway put-integration-response --rest-api-idabc123\ --resource-idefg456\ --http-method GET \ --status-code 200 \ --selection-pattern ""Use the following command to set up an integration response for the
POST /validationmethod.aws apigateway put-integration-response --rest-api-idabc123\ --resource-idefg456\ --http-method POST \ --status-code 200 \ --selection-pattern ""
To test the API
-
To test the
GETmethod, which will perform request validation for the query strings, use the following command:aws apigateway test-invoke-method --rest-api-idabc123\ --resource-idefg456\ --http-method GET \ --path-with-query-string '/validate?petType=dog'The result will return a
200 OKand list of dogs. -
Use the following command to test without including the query string
petTypeaws apigateway test-invoke-method --rest-api-idabc123\ --resource-idefg456\ --http-method GETThe result will return a
400error. -
To test the
POSTmethod, which will perform request validation for the request body, use the following command:aws apigateway test-invoke-method --rest-api-idabc123\ --resource-idefg456\ --http-method POST \ --body '{"id": 1, "name": "bella", "type": "dog", "price" : 400 }'The result will return a
200 OKand a success message. -
Use the following command to test using an invalid body.
aws apigateway test-invoke-method --rest-api-idabc123\ --resource-idefg456\ --http-method POST \ --body '{"id": 1, "name": "bella", "type": "dog", "price" : 1000 }'The result will return a
400error, as the price of the dog is over the maximum price defined by the model.
To delete an AWS CloudFormation stack
Use the following command to delete your AWS CloudFormation resources.
aws cloudformation delete-stack --stack-name request-validation-tutorial-cli
Set up basic request validation using an OpenAPI definition
You can declare a request validator at the API level by specifying a set of the x-amazon-apigateway-request-validators.requestValidator object objects in the x-amazon-apigateway-request-validators object map to select what part of the request will be validated. In the example OpenAPI definition, there are two validators:
allvalidator which validates both the body, using theRequestBodyModeldata model, and the parameters.The
RequestBodyModeldata model requires that the input JSON object contains thename,type, andpriceproperties. Thenameproperty can be any string,typemust be one of the specified enumeration fields (["dog", "cat", "fish"]), andpricemust range between 25 and 500. Theidparameter is not required.param-onlywhich validates only the parameters.
To turn a request validator on all methods of an API, specify an x-amazon-apigateway-request-validator property 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 or to Import an edge-optimized API into API Gateway.