When we are working with REST or HTTP based service API, we have the responsibility or we can say that it could come as a requirement to validate the behavior of the API. This we perform by validating the schema. For those who are not clear or familiar with what schema validation is? Schema validation ensures that the response coming back from the endpoint matches with the predefined set of rules. Note, that here we are not concerned about the data(values). Rest Assured provides the capability to test this feature using ‘Rest Assured Schema Validator’ and makes it very easy to test. In this example, we will learn “how to perform JSON schema validation with Rest-Assured?”.
Simple representation of validating JSON Schema with RESTAssured...!!! Share on X
Steps to follow:
Step 1. Adding ‘Rest Assured Schema Validator‘ to the project
In order to perform this feature testing, first we need to setup the project environment by adding the required dependency to it. So, let’s add below ‘Rest Assured Schema Validator’ maven dependency in your project POM.
1 2 3 4 5 | <dependency> <groupId>io.rest-assured</groupId> <artifactId>json-schema-validator</artifactId> <version>4.0.0</version> </dependency> |
Note: Considering that you have already setup the maven project. But, if you are just using plain java project then download the required dependency jar file from this link and add it to the project classpath. See below screenshot:
Step 2. Generate a sample schema to test
Now, in order to test schema, we need to have one. right? Well, it’s pretty simple, just copy the JSON returned by any of your existing API and generate the schema using any Online schema generator tool like this.
Well, for testing purposes, we have below JSON file and using this above-mentioned tool, we will generate the schema.
Note: Schema is generally provided by developers to test.
JSON:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | [ { "postId": 1, "id": 1, "name": "id labore ex et quam laborum", "email": "Eliseo@gardner.biz", "body": "laudantium enim quasi est quidem magnam voluptate ipsam eos\ntempora quo necessitatibus\ndolor quam autem quasi\nreiciendis et nam sapiente accusantium" }, { "postId": 1, "id": 2, "name": "quo vero reiciendis velit similique earum", "email": "Jayne_Kuhic@sydney.com", "body": "est natus enim nihil est dolore omnis voluptatem numquam\net omnis occaecati quod ullam at\nvoluptatem error expedita pariatur\nnihil sint nostrum voluptatem reiciendis et" }, { "postId": 1, "id": 3, "name": "odio adipisci rerum aut animi", "email": "Nikita@garfield.biz", "body": "quia molestiae reprehenderit quasi aspernatur\naut expedita occaecati aliquam eveniet laudantium\nomnis quibusdam delectus saepe quia accusamus maiores nam est\ncum et ducimus et vero voluptates excepturi deleniti ratione" }, { "postId": 1, "id": 4, "name": "alias odio sit", "email": "Lew@alysha.tv", "body": "non et atque\noccaecati deserunt quas accusantium unde odit nobis qui voluptatem\nquia voluptas consequuntur itaque dolor\net qui rerum deleniti ut occaecati" }, { "postId": 1, "id": 5, "name": "vero eaque aliquid doloribus et culpa", "email": "Hayden@althea.biz", "body": "harum non quasi et ratione\ntempore iure ex voluptates in ratione\nharum architecto fugit inventore cupiditate\nvoluptates magni quo et" } ] |
JSON Schema:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 | { "$schema": "http://json-schema.org/draft-04/schema", "type": "array", "items": [ { "type": "object", "properties": { "postId": { "type": "integer" }, "id": { "type": "integer" }, "name": { "type": "string" }, "email": { "type": "string" }, "body": { "type": "string" } }, "required": [ "postId", "id", "name", "email", "body" ] }, { "type": "object", "properties": { "postId": { "type": "integer" }, "id": { "type": "integer" }, "name": { "type": "string" }, "email": { "type": "string" }, "body": { "type": "string" } }, "required": [ "postId", "id", "name", "email", "body" ] }, { "type": "object", "properties": { "postId": { "type": "integer" }, "id": { "type": "integer" }, "name": { "type": "string" }, "email": { "type": "string" }, "body": { "type": "string" } }, "required": [ "postId", "id", "name", "email", "body" ] }, { "type": "object", "properties": { "postId": { "type": "integer" }, "id": { "type": "integer" }, "name": { "type": "string" }, "email": { "type": "string" }, "body": { "type": "string" } }, "required": [ "postId", "id", "name", "email", "body" ] }, { "type": "object", "properties": { "postId": { "type": "integer" }, "id": { "type": "integer" }, "name": { "type": "string" }, "email": { "type": "string" }, "body": { "type": "string" } }, "required": [ "postId", "id", "name", "email", "body" ] } ] } |
Now, save this schema in a JSON format file. let’s say “JsonSchemaFile.JSON“ and add it into the classpath of your project.
Step 3. Test Code to perform the JSON schema validation with Rest Assured
Finally, let’s jump on the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath; import org.testng.annotations.Test; import io.restassured.RestAssured; public class testJsonSchema { @Test public void testJsonSchema() { RestAssured.given() .when() .get("https://jsonplaceholder.typicode.com/comments?postId=1") .then() .assertThat() .body(matchesJsonSchemaInClasspath("JsonSchemaFile.json")); } } |
As per the above code, the “matchesJsonSchemaInClasspath” method available in the newly added ‘Rest Assured Schema Validator’ API will help to test the structure of the JSON file passed as an argument here (in our case JsonSchemaFile.json).
That’s it, it’s that easy to perform JSON schema validation with REST Assured API :)
Simple representation of validating JSON Schema with RESTAssured...!!! Share on X
If you like this post, please check out my other useful blog posts on Rest Assured:
Other Useful References:
Thank You !
I had a problem with the json place in the classpath you you brought me the solution!
I am so glad. It helped.
Thank you.
I tried your code but getting Exception in thread “main” java.lang.IllegalArgumentException: Schema to use cannot be null error. please help
Hello Sonia,
This error suggests that you must be missing the .json schema file meaning code couldn’t find your file at the location you’ve specified it your code.
Please make your json file is present in the classpath.
If it’s still happening, Kindly share your project folder structure and code so that I could help you better.
Thanks
How to add the file to the classpath??
It’s quite simple Apurva.
Just add the .json file in the ‘resources’ folder of your project. That’s it.
Let’s say. your project name is ‘JavaProject’, Ideally developers and testers tend to create at least these 2 folders in their build path (one is (src/main/java and another one is src/main/resources) or (src/test/java and another one is src/test/resources) respectively.
Now, let’s say you are a tester, then your package will go like below:
JavaProject
>src/test/java – {your packages}
>src/test/resources – {your files}
So, now if you understand, the resources folder is the one that holds any required files. So, in your case, just copy the JsonSchemaFile.json in this folder.
That’s it.
Kindly let me know if you still struggle with this.
Thanks
Hi Deepak Verma,
Is there any option available in REST ASSURED to extract the generated JSON schema. I want use a different validator instead of the REST ASSURED validator. Please confirm.
Thanks.
Hi Sathish,
First of all, sorry for the late response.
Well, Both the questions that you’ve mentioned are different.
If you want to extract JSON schema or generate one, there is no option straight option within Rest Assured to do that. But, there are plenty of options available just like the one I mentioned above.
And, In response to your validator question, Yes, you can use any validator, you don’t need to depend on Rest Assured validator.
I hope my answer would be satisfactory to you. If not, Kindly let me know I’ll try to help you further.
Thanks
Tank you so much for this page….. stay blessed
You’r welcome. I am glad it helped.
Thanks
I tried the above code using the Jar file you mentioned. I am getting error for the method – matchesJsonSchemaInClasspath. The error is that the method matchesJsonSchemaInClasspath is undefined. My aim is to validate a json response as per the schema. I have 2 files. One is json response and other is schema.json. Kindly suggest how to do it.
Hi Onkar,
As per your requirement, this script will do the job for you to validate your response against your predefined schema structure.
Well, It seems working fine to me. Could you please make sure that the .json is present at the classpath.
And, please share your complete console log in the comment if it’s still showing the same error message. I would be able to better suggest you after checking the log.
Thanks