Answer
JSON Schema Validation with Rest Assured
What is Schema?
A Schema is a JSON file that contains only datatype information and expected keys of the JSON. There are no values present in the schema.
JSON Schema is a JSON media type for defining the structure of JSON data. It provides a contract for:
- ✓What JSON data is required for a given application
- ✓How to interact with it
- ✓Defines validation, documentation, and hyperlink navigation
Why JSON Schema Validation?
JSON Schema Validation is required to monitor API responses and ensure that the format we are getting is the same as the expected one. It catches structural issues like:
- ✓Missing required fields
- ✓Wrong data types (e.g., integer returned instead of string)
- ✓Extra unexpected fields
How to Automate Schema Validation
Step 1: Add Dependencies to pom.xml
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-schema-validator</artifactId>
<version>5.3.0</version>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<version>1.3</version>
</dependency>
Step 2: Create the JSON Schema File
Create src/test/resources/JsonSchema.json:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"data": {
"type": "object",
"properties": {
"id": { "type": "integer" },
"email": { "type": "string" },
"first_name": { "type": "string" },
"last_name": { "type": "string" }
},
"required": ["id", "email", "first_name", "last_name"]
}
},
"required": ["data"]
}
Step 3: Validate Using matchesJsonSchema
import static io.restassured.module.jsv.JsonSchemaValidator.*;
@Test
public void givenUrl_validateSchema() throws FileNotFoundException, IOException {
File schema = new File(System.getProperty("user.dir") + "/JsonSchema.json");
RestAssured.given()
.get("https://reqres.in/api/users/2")
.then()
.body(matchesJsonSchema(schema));
}
Common Schema Validation Errors
| Error | What It Means |
|---|---|
object has missing required properties | API response is missing a field defined as required in schema |
instance type (integer) does not match any allowed primitive type (allowed: ["string"]) | Wrong data type returned |
Manual Schema Comparison
To compare schemas manually, use jsonschema2pojo or paste both JSONs into: http://www.jsondiff.com/
