JSON Schema Validation
JSON Schema Validation with REST Assured: Ensuring API Data Integrity
Introduction
In our REST Assured series, we’ve explored topics like File Uploads and File Downloads, Multi-Part Form Data, and Filters, building a robust foundation for API testing. Now, we’ll dive into JSON Schema Validation, a powerful technique to verify that API responses conform to expected JSON structures. This guide demonstrates how to use REST Assured to validate JSON responses against a schema, with practical examples and best practices. It’s designed for beginners and experienced developers, ensuring you can confidently test API data integrity.
Key Point: JSON Schema Validation in REST Assured ensures API responses match predefined data structures, enhancing test reliability and catching data contract violations early.
What is JSON Schema Validation?
JSON Schema is a specification for defining the structure and data types of JSON data. It allows you to specify properties, required fields, data types, and constraints (e.g., string length, number ranges). In API testing, JSON Schema Validation ensures that responses adhere to this schema, catching issues like missing fields, incorrect types, or invalid values.
REST Assured supports JSON Schema Validation through the io.rest-assured.module.jsv module, using the matchesJsonSchemaInClasspath() or matchesJsonSchema() methods. We’ll use https://jsonplaceholder.typicode.com/posts for examples, validating its JSON response against a schema stored in the project’s resources. The schema will define the structure of a post object, ensuring fields like id, userId, title, and body are present and correctly typed.
Setting Up for JSON Schema Validation
We’ll set up a Maven project with REST Assured, JUnit, and Allure for reporting, adding the rest-assured-json-schema-validator dependency for schema validation. The JSON Schema will be stored in src/test/resources/schemas/post-schema.json.
Here’s the updated pom.xml:
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-schema-validator</artifactId>
<version>5.4.0</version>
<scope>test</scope>
</dependency>
Create a JSON Schema file at src/test/resources/schemas/post-schema.json:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"id": { "type": "integer" },
"userId": { "type": "integer" },
"title": { "type": "string" },
"body": { "type": "string" }
},
"required": ["id", "userId", "title", "body"],
"additionalProperties": false
}
Performing JSON Schema Validation
Example 1: Basic JSON Schema Validation
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.restassured.RestAssured;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.*;
import static io.restassured.module.jsv.JsonSchemaValidator.*;
@Feature("JSON Schema Validation Testing")
public class BasicSchemaValidationTest {
@Test
@Description("Test JSON Schema validation for a single post")
public void testBasicSchemaValidation() {
RestAssured.baseURI = "https://jsonplaceholder.typicode.com";
given()
.log().all()
.when()
.get("/posts/1")
.then()
.statusCode(200)
.body(matchesJsonSchemaInClasspath("schemas/post-schema.json"));
}
}
Example 2: Validating an Array of Objects
Schema file: src/test/resources/schemas/posts-array-schema.json
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "array",
"items": {
"type": "object",
"properties": {
"id": { "type": "integer" },
"userId": { "type": "integer" },
"title": { "type": "string" },
"body": { "type": "string" }
},
"required": ["id", "userId", "title", "body"],
"additionalProperties": false
}
}
given()
.log().all()
.when()
.get("/posts")
.then()
.statusCode(200)
.body(matchesJsonSchemaInClasspath("schemas/posts-array-schema.json"));
Example 3: Combining Schema Validation with Assertions
given()
.log().all()
.when()
.get("/posts/1")
.then()
.statusCode(200)
.body(matchesJsonSchemaInClasspath("schemas/post-schema.json"))
.body("id", equalTo(1))
.body("title", notNullValue());
Pro Tip: Use schema validation for structure and Hamcrest for specific value checks to balance thoroughness and flexibility.
Example 4: Schema Validation with Authentication
given()
.header("Authorization", "Bearer my-bearer-token")
.log().all()
.when()
.get("https://httpbin.org/get")
.then()
.statusCode(200)
.body(matchesJsonSchemaInClasspath("schemas/httpbin-get-schema.json"))
.body("headers.Authorization", equalTo("Bearer my-bearer-token"));
Example 5: Schema Validation with Response Specification
private ResponseSpecification postSchemaSpec;
@BeforeEach
public void setup() {
postSchemaSpec = new ResponseSpecBuilder()
.expectStatusCode(200)
.expectBody(matchesJsonSchemaInClasspath("schemas/post-schema.json"))
.build();
}
// In test
given()
.log().all()
.when()
.get("/posts/1")
.then()
.spec(postSchemaSpec)
.body("id", equalTo(1));
Integrating with Allure Reporting
Response response = given().log().all()
.when().get("/posts/1")
.then().extract().response();
Allure.addAttachment("Response Body", "application/json", response.asString(), ".json");
try (InputStream schemaStream = getClass().getResourceAsStream("/schemas/post-schema.json")) {
Allure.addAttachment("JSON Schema", "application/json",
new String(schemaStream.readAllBytes()), ".json");
}
Integrating with CI/CD Pipeline
Add this .github/workflows/ci.yml:
name: REST Assured CI
on:
push:
branches: [ main ]
pull_request:
jobs:
build-and-test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up JDK 11
uses: actions/setup-java@v4
with:
java-version: '11'
distribution: 'temurin'
- name: Run tests
run: mvn clean test
- name: Generate Allure report
run: mvn allure:report
Tips for Beginners
- Create Simple Schemas: Start basic, add constraints gradually.
- Store Schemas in Resources: Always keep them in
src/test/resources. - Debug Failures: Use
log().all()and read the detailed schema error message. - Reuse Schemas: Combine with
ResponseSpecificationfor DRY tests.
Troubleshooting Tip: If validation fails, double-check schema typos and compare actual JSON vs expected structure.
What’s Next?
Next in the series:
- GraphQL Testing with REST Assured
- Advanced Allure Customization
- Combining REST Assured + Selenium for E2E
Stay tuned — happy testing!