# Validate JSON Schema in Rest Assured.

Rest AssuredDynamic ProgrammingProgramming

We can validate JSON schema in Rest Assured. The schema validation ensures that the Response obtained from a request satisfies a set of pre-built rules and the JSON body in the Response has a specific format.

We shall use the method matchesJsonSchema (part of the JSONSchemaValidator class) for verifying the schema. To work with JSON schema validation we have to add the additional JSON Schema Validator dependency in the pom.xml in our Maven project −

https://mvnrepository.com/artifact/io.rest-assured/json-schema-validator

We shall first send a GET request via Postman on an endpoint:  https://jsonplaceholder.typicode.com/posts/2 and observe its Response.

Generally, a scheme for JSON Response is provided by a developer. However, we can also generate one with the help of an online resource with a link −https://www.liquid-technologies.com/online-json-to-schema-converter

Once we launch this application, we shall get a field called the Sample JSON Document. Here, we have to add the JSON body whose scheme we want to validate. Then click on the Generate Schema button.

Then the corresponding scheme for the JSON gets generated at the bottom of the page.

Let us create a JSON file, say schema.json, add below the generated schema. This is created within the project.

{
"\$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"userId": {
"type": "integer"
},
"id": {
"type": "integer"
},
"title": {
"type": "string"
},
"body": {
"type": "string"
}
},
"required": [
"userId",
"id",
"title",
"body"
]
}

## Example

Code Implementation

import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import java.io.File;
import io.restassured.RestAssured;
import io.restassured.module.jsv.JsonSchemaValidator;
public class NewTest {
@Test
public void validateJSONSchema(){

//base URL
RestAssured.baseURI = "https://jsonplaceholder.typicode.com/posts/2";

//obtain response
given()
.when().get()

//verify JSON Schema
.then().assertThat()
.body(JsonSchemaValidator.
matchesJsonSchema(new File("/Users/src/Parameterize/schema.json")));
}
}

## Output

Updated on 17-Nov-2021 13:24:34