How to validate request body | Amazon API Gateway
Tags: serverless, api, aws, apigatewa
Published: 2022-07-27 20:44:20

this week I have learned about payload or body validation in AWS API Gateway and want to share it. Last week we learned how to create API using the AWS API Gateway service. [Here,  you can read about it](https://dev.to/shakeel0581/how-to-create-api-using-aws-api-gateway-service-amazon-api-gateway-serverless-3fnj)
In this session, we will learn about how to validate body or payload in the AWS API. we have already set up the API gateway and we just focus on API body validation, how can active body validation and how its works.

## Overview of basic request validation in API Gateway

Request validation is used to ensure that the incoming request message is properly formatted and contains the proper attributes. API Gateway can perform the basic validation. This enables you, the API developer, to focus on app-specific deep validation in the backend. For the basic validation, API Gateway verifies either or both of the following conditions:

1. The required request parameters in the URI, query string, and headers of an incoming request are included and non-blank.
2. The applicable request payload adheres to the configured JSON schema request model of the method.

First, we need to create a model to set up JSON schema request. Before creating  model, we need to know about the model.

## Models

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://datatracker.ietf.org/doc/html/draft-zyp-json-schema-04).

The following JSON object describes sample data that describes the fruit or vegetable inventory in the produce department of a likely supermarket.

Suppose we have an API for managing clothing inventory in the produce department of a supermarket. When a manager queries the backend for the current inventory, the server sends back the following response payload:

```
{
  "department": "produce",
  "categories": [
    "jeans",
    "shirt"
  ],
  "dress": [
    {
      "category": "jeans",
      "type": "pants",
      "price": 1.99,
      "quantity": 232
    },
    {
      "category": "jeans",
      "type": "casual",
      "price": 0.19,
      "quantity": 112
    },
    {
      "category": "jeans",
      "type": "shorts",
      "price": 1.29,
      "quantity": 57
    }
  ]
}
```
[you can see detail about Models here ](https://docs.aws.amazon.com/apigateway/latest/developerguide/models-mappings.html?icmpid=docs_apigateway_console#models-mappings-models)

## Create a model

1. Sign in to the API Gateway console at [https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway).

2. Choose a REST API. In my case I will choose `sample-Api`, that I have been created in last story. [see here](https://dev.to/shakeel0581/how-to-create-api-using-aws-api-gateway-service-amazon-api-gateway-serverless-3fnj)

3. Choose the Models tab from left and Choose Create.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/md3kjtjgr4zgoddp2yxd.png)

4. For Model Name, type name for the model 'item'.

5. For Content Type, type the model's content type (for example, application/json for JSON).

6. (Optional) For Model description, type a description for the model.

7. For Model schema, type the model's schema.

```
{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "title":"Item Schema",
        "type": "object",
        "properties":{
            "ID":{ "type": "number"},
            "name":{ "type": "string"},
            "price":{ "type": "number"}
        },
        "required":["ID","name","price"]
        
}
```
8. Choose Create model.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6gomzh49lyxg0w4016j9.png)

## Request validation using the API Gateway console with model

The API Gateway console lets you set up the basic request validation on a method using one of the three validators:

- Validate body: This is the body-only validator.
- Validate query string parameters and headers: This is the parameters-only validator.

Validate body, query string parameters, and headers: This validator is for both body and parameters validation.

**To enable a request validator on a method**

1. Choose resource tab and then choose method the resource 'POST'.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b6u4mlbr95tej9hjl7wr.png)

2. Choose Method Request.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bis55v5hbhl6mmolpckm.png)

3. Choose the pencil icon of Request Validator under Settings.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6tbsb258cubdge4uyjzj.png)

4. Choose Validate body from drop down list. Then choose the check mark icon to save your choice.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9cjb6qmlwnwbqwt7iwai.png)

5. Choose the Body Request and choose add model.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1xbsaeaaaax52mmhi55p.png)

6. Now add Content type 'application/json' and Model name 'item' from drop down list under the Modle Name. Then choose the check mark icon to save your choice.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/olqi614le3q8gitpzpp7.png)

7. last step to deploy the API to sample stage. Select Actions button and choose Deploy API.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hr49yxbmcouw625yu6j7.png)

8. A pop up appear, choose 'smapleStage' from Deployment stage drop down and Deploy.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a9vik6jzbq12q4dl9ul1.png)

## How does it work
we need to check this out request body validation is working fine with the rest API. For this, we need to use the postman to generate the post request with the request body

**Test REST API in postman to verify that body validation working file with rest API**

1. CHoose POST request, Set header 'Content-Type' with value 'application/json' and body

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dw00ty2za61wqb7ubdup.png)

2. Set request body with dummy data and hit the send button.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jc789mbacvlrszqx5pyn.png)
you can see that our Lambda function invoked and its return response.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5df1wjd22lyo894bklp4.png)

Now change the body request and remove the any field and its value. Hite the send button. This time you can see its return error "Invalid request body".


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6r8itrkoxhsi5vze0we5.png)