JSON Schema Validation with Rest Assured

Braulio Batista
3 min readNov 9, 2020

--

  1. Overview

The REST-assured library provides support for testing Rest APIs, usually in JSON format. Sometimes it may be necessary for analyzing the response in detail, to know first-off whether the JSON body conforms to a correct JSON format. This we can perform by validating the schema. Schema validation ensures that the response coming back from the endpoint matches with the predefined set of rules. The REST-assured provides this capability using the REST Assured Schema Validation.

2. Setup

In this tutorial, we will use the following tools :

  • VS Code;
  • Maven;
  • Java JDK 8+;

and the following technologies:

  • Java;
  • JUnit 5, you can find the versions here;
  • Rest Assured, you can find the versions here;
  • Hamcrest, you can find the versions here;

Firstly let´s configure the pom.xml, adding the core dependencies as a figure below.

3. The Test Class

To create our test class, we starting to import the references of Junit 5, of REST-assure, Hamcrest and module of JSON schema validator.

Next, let´s create a public void function with the tag @Test as an image bellow.

Now we can start writing the test.

4. Using REST-ASSURED

To explain how JSON Schema validation works, we create a simple test with REST-Assured and your traditional body validation.

In the test above, we are going to GET a user API, for this we use the REQRES API (available online) and in the response, we can validate the status code and several values received in the body for example page and company name.

5. JSON Schema Validation

Let´s have a look at an example of JSON Schema Validation. In the image, bellow we have the response of GET of user request used in the above example about Rest Assured.

Traditionally, in API tests we validate the status code of request if the request returns the expected JSON or we simply validate some fields of the response to verify that the field returns the respected value.

But, how do we validate the JSON schema?

First, let´s use the response received to generate our JSON schema, we can use many tools available online. In this tutorial, we will use the tool liquid-technologies.

We copy our JSON and put it in the tool´s text box and generate the JSON schema.

In the end, we should have a structure similar to the figure below, which will be the JSON Schema of the users GET.

6. Validating Files

Now we need to do our test that will validate if the generated schema matches the server´s response.

Note that in the test we used matchesJsonSchemaInClasspath to validate the schema structure.

7. Conclusion

In this article, we’ve shown how we can validate a JSON response against a schema when using REST-assured.

As always, the full source code for the example is available over on GitHub.

--

--