
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Validate JSON Schema in REST Assured
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 −
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"))); } }