π Contract Governance, Structural Integrity & Strict Type Invariants
While functional test assertions evaluate specific data instances (e.g., verifying fullName == "Nikita Sharma"), they leave APIs vulnerable to undetected contract drift, unexpected nullability shifts, missing mandatory attributes, and subtle primitive data type mutations. JSON Schema Validation introduces formal Contract Testing into REST Assured pipelines by validating the entire JSON response against an explicit structural specification under the IETF JSON Schema Draft-07 standard. Using REST Assured's official json-schema-validator moduleβpowered by Francis Galiegue's json-schema-validator engine or modern high-throughput validators like NetworkNTβtest engineers evaluate entire JSON trees with a single line: .body(matchesJsonSchemaInClasspath("schemas/student.json")). This enforces strict property typing, pattern constraints, nested object compositions, array item bounds, and required field invariants across continuous deployment environments.
INBOUND WIRE RESPONSE TO JSON SCHEMA VALIDATION PIPELINE:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β WIRE RESPONSE STREAM (HTTP 200 OK | Content-Type: application/json) β
β { β
β "id": "STU-88219", β
β "fullName": "Nikita Sharma", β
β "email": "nikita.sharma@nikita-infotech.com", β
β "enrolledCredits": 16, β
β "gpa": 3.85, β
β "active": true β
β } β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ (Passed into .then().body(matchesJsonSchemaInClasspath(...)))
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β JSON-SCHEMA-VALIDATOR MODULE (io.restassured.module.jsv.JsonSchemaValidator) β
β βββ 1. Classpath Loader: Resolves "schemas/student-schema.json" from target/test-classes β
β βββ 2. AST Compilation: Compiles Draft-07 JSON Schema into memory cache β
β βββ 3. Validator Factory: Configures SchemaValidationFlags & JsonSchemaFactory settings β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ (Evaluates Structural Invariants)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β DRAFT-07 SCHEMA CONFORMANCE CHECKS β
β βββ Primitive Types βββΊ id: string, credits: integer, gpa: number, active: boolean β
β βββ Required Attributes βββΊ "id", "fullName", "email", "enrolledCredits" β
β βββ Pattern Rules βββΊ id matches "^STU-[0-9]{5,}$" β
β βββ Format Standards βββΊ email matches RFC 5322 format: "email" β
β βββ Numerical Ranges βββΊ enrolledCredits: minimum: 1, maximum: 30 β
β βββ Object Policies βββΊ additionalProperties: false (Strict contract lockdown) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
ββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββ
βΌ βΌ
ββββββββββββββββββββββββββββββββββββββββββββββββ ββββββββββββββββββββββββββββββββββββββββββββββββ
β SCHEMA VALIDATION PASS β β SCHEMA VALIDATION FAILURE β
ββββββββββββββββββββββββββββββββββββββββββββββββ€ ββββββββββββββββββββββββββββββββββββββββββββββββ€
β Pipeline continues seamlessly to downstream β β Throws JsonSchemaValidationException β
β Hamcrest value assertions or POJO transforms β β Lists exact path, expected type, and missing β
β [CONTRACT CONFIRMED COMPLIANT] β β fields with line numbers [FAST-FAIL] β
ββββββββββββββββββββββββββββββββββββββββββββββββ ββββββββββββββββββββββββββββββββββββββββββββββββ
additionalProperties: false for strict contract enforcement.
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "StudentProfileContract",
"description": "Enterprise API contract schema for student profile entities",
"type": "object",
"required": [
"id",
"fullName",
"email",
"academicTrack",
"enrolledCredits",
"gpa",
"active",
"contactInfo",
"courses"
],
"additionalProperties": false,
"properties": {
"id": {
"type": "string",
"pattern": "^STU-[0-9]{5,}$"
},
"fullName": {
"type": "string",
"minLength": 3,
"maxLength": 100
},
"email": {
"type": "string",
"format": "email"
},
"academicTrack": {
"type": "string",
"enum": [
"ENTERPRISE_AUTOMATION",
"FULLSTACK_SDET",
"CLOUD_DEVOPS_QA"
]
},
"enrolledCredits": {
"type": "integer",
"minimum": 1,
"maximum": 30
},
"gpa": {
"type": "number",
"minimum": 0.0,
"maximum": 4.0
},
"active": {
"type": "boolean"
},
"contactInfo": {
"type": "object",
"required": ["phone", "city", "postalCode"],
"additionalProperties": false,
"properties": {
"phone": {
"type": "string",
"pattern": "^\\+91-[0-9]{10}$"
},
"city": {
"type": "string"
},
"postalCode": {
"type": "string",
"pattern": "^[0-9]{6}$"
}
}
},
"courses": {
"type": "array",
"minItems": 1,
"items": {
"type": "object",
"required": ["courseCode", "credits"],
"properties": {
"courseCode": {
"type": "string",
"pattern": "^[A-Z]{3,4}-[A-Z]{3,4}-[0-9]{3}$"
},
"credits": {
"type": "integer",
"minimum": 1,
"maximum": 6
}
}
}
}
}
}
student-v1-schema.json from src/test/resources/schemas/ and asserts complete structural conformance in a single line.
package com.nikita.restassured.schema;
import io.restassured.http.ContentType;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;
import static org.hamcrest.Matchers.equalTo;
public class BasicJsonSchemaValidationTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "Validate API response against Draft-07 JSON Schema stored in classpath")
public void testStudentProfileJsonSchema() {
given()
.baseUri(BASE_URI)
.accept(ContentType.JSON)
.pathParam("studentId", "STU-88219")
.log().ifValidationFails()
.when()
.get("/students/{studentId}")
.then()
.log().ifValidationFails()
// 1. Assert transport status code
.statusCode(200)
.contentType(ContentType.JSON)
// 2. Validate complete structural contract against Draft-07 schema
.body(matchesJsonSchemaInClasspath("schemas/student-v1-schema.json"))
// 3. Layer specific business value assertions
.body("id", equalTo("STU-88219"))
.body("fullName", equalTo("Nikita Sharma"));
System.out.println("[β] Response fully conforms to Draft-07 JSON Schema contract.");
}
}
java.io.File paths, java.io.InputStream, and raw dynamically generated JSON schema strings using matchesJsonSchema().
package com.nikita.restassured.schema;
import org.testng.annotations.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import static io.restassured.RestAssured.given;
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchema;
public class DynamicSchemaSourcesTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "Validate schema loaded from absolute or relative java.io.File")
public void testValidateSchemaFromFile() {
File schemaFile = new File("src/test/resources/schemas/student-v1-schema.json");
given()
.baseUri(BASE_URI)
.pathParam("studentId", "STU-88219")
.when()
.get("/students/{studentId}")
.then()
.statusCode(200)
// Validating directly from a File reference:
.body(matchesJsonSchema(schemaFile));
System.out.println("[β] Verified schema loaded directly from java.io.File.");
}
@Test(description = "Validate schema loaded from an InputStream")
public void testValidateSchemaFromInputStream() throws IOException {
try (InputStream stream = new FileInputStream("src/test/resources/schemas/student-v1-schema.json")) {
given()
.baseUri(BASE_URI)
.pathParam("studentId", "STU-88219")
.when()
.get("/students/{studentId}")
.then()
.statusCode(200)
// Validating directly from an InputStream:
.body(matchesJsonSchema(stream));
}
System.out.println("[β] Verified schema loaded from InputStream.");
}
@Test(description = "Validate schema defined inline as a raw Java String")
public void testValidateSchemaFromRawString() {
// Minimal inline schema asserting status and timestamp
String inlineSchema = "{\n" +
" \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n" +
" \"type\": \"object\",\n" +
" \"required\": [\"status\"],\n" +
" \"properties\": {\n" +
" \"status\": { \"type\": \"string\", \"enum\": [\"UP\", \"DOWN\"] }\n" +
" }\n" +
"}";
given()
.baseUri(BASE_URI)
.when()
.get("/health")
.then()
.statusCode(200)
// Validating directly from a raw String:
.body(matchesJsonSchema(inlineSchema));
System.out.println("[β] Verified schema defined as inline Java String.");
}
}
JsonSchemaFactory with ValidationConfiguration to enable checked validation flags, customize format attributes, and enable caching.
package com.nikita.restassured.schema;
import com.github.fge.jsonschema.cfg.ValidationConfiguration;
import com.github.fge.jsonschema.main.JsonSchemaFactory;
import io.restassured.module.jsv.JsonSchemaValidator;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;
public class CustomSchemaFactoryConfigTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@BeforeClass
public void configureJsonSchemaEngine() {
// Build customized ValidationConfiguration
ValidationConfiguration validationConfig = ValidationConfiguration.newBuilder()
.setDefaultVersion(com.github.fge.jsonschema.SchemaVersion.DRAFTV4) // Default fallback version
.freeze();
// Instantiate JsonSchemaFactory with customized configuration
JsonSchemaFactory factory = JsonSchemaFactory.newBuilder()
.setValidationConfiguration(validationConfig)
.freeze();
// Apply custom factory globally or via JsonSchemaValidator settings
JsonSchemaValidator.settings = JsonSchemaValidator.settings().with().jsonSchemaFactory(factory).and().with().checkedValidation(true);
System.out.println("[*] Configured JsonSchemaValidator engine with strict checked validation flags.");
}
@Test(description = "Execute schema check with customized validation factory active")
public void testExecuteWithCustomFactory() {
given()
.baseUri(BASE_URI)
.pathParam("studentId", "STU-88219")
.when()
.get("/students/{studentId}")
.then()
.statusCode(200)
.body(matchesJsonSchemaInClasspath("schemas/student-v1-schema.json"));
System.out.println("[β] Validated response against schema using customized factory.");
}
}
json-schema-validatorβan ultra-fast Draft-07 and Draft-2020-12 engineβinto REST Assured response evaluation for performance-sensitive CI/CD suites.
package com.nikita.restassured.schema;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.networknt.schema.JsonSchema;
import com.networknt.schema.JsonSchemaFactory;
import com.networknt.schema.SpecVersion;
import com.networknt.schema.ValidationMessage;
import io.restassured.response.Response;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.io.InputStream;
import java.util.Set;
import static io.restassured.RestAssured.given;
public class NetworkNtSchemaValidationTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
private JsonSchema compiledNetworkNtSchema;
private ObjectMapper objectMapper;
@BeforeClass
public void setupNetworkNtEngine() {
objectMapper = new ObjectMapper();
// Compile Draft-07 schema using NetworkNT high-speed validator
JsonSchemaFactory factory = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V7);
InputStream schemaStream = getClass().getClassLoader().getResourceAsStream("schemas/student-v1-schema.json");
Assert.assertNotNull(schemaStream, "Schema file not found in classpath!");
compiledNetworkNtSchema = factory.getSchema(schemaStream);
System.out.println("[*] Compiled NetworkNT Draft-07 schema for high-throughput validation.");
}
@Test(description = "Validate response payload using pre-compiled NetworkNT schema validator")
public void testNetworkNtValidation() throws Exception {
Response response = given()
.baseUri(BASE_URI)
.pathParam("studentId", "STU-88219")
.when()
.get("/students/{studentId}")
.then()
.statusCode(200)
.extract().response();
// Parse response into Jackson JsonNode
JsonNode responseJsonNode = objectMapper.readTree(response.asString());
// Validate using NetworkNT pre-compiled schema
Set<ValidationMessage> errors = compiledNetworkNtSchema.validate(responseJsonNode);
// Assert zero schema violations
if (!errors.isEmpty()) {
StringBuilder errorLog = new StringBuilder("NetworkNT Schema Violations Found:\n");
for (ValidationMessage vm : errors) {
errorLog.append(" β’ ").append(vm.getMessage()).append(" at ").append(vm.getPath()).append("\n");
}
Assert.fail(errorLog.toString());
}
System.out.println("[β] Zero schema violations detected across " + responseJsonNode.size() + " nodes via NetworkNT.");
}
}
[...]). Demonstrates authoring a schema with "type": "array", enforcing minItems, uniqueItems, and asserting schemas on every array element.
// ==============================================================================
// SCHEMA DEFINITION: src/test/resources/schemas/students-array-schema.json
// ==============================================================================
// {
// "$schema": "http://json-schema.org/draft-07/schema#",
// "title": "StudentsCollectionContract",
// "type": "array",
// "minItems": 1,
// "uniqueItems": true,
// "items": {
// "type": "object",
// "required": ["id", "fullName", "enrolledCredits", "active"],
// "properties": {
// "id": { "type": "string", "pattern": "^STU-[0-9]{5,}$" },
// "fullName": { "type": "string" },
// "enrolledCredits": { "type": "integer", "minimum": 1 },
// "active": { "type": "boolean" }
// }
// }
// }
package com.nikita.restassured.schema;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;
import static org.hamcrest.Matchers.greaterThan;
public class RootArraySchemaTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "Validate endpoint returning root-level JSON array against array schema")
public void testValidateRootArraySchema() {
given()
.baseUri(BASE_URI)
.queryParam("status", "ACTIVE")
.when()
.get("/students")
.then()
.statusCode(200)
// Validates that root is an array, has minItems: 1, and every item matches object schema:
.body(matchesJsonSchemaInClasspath("schemas/students-array-schema.json"))
.body("size()", greaterThan(0));
System.out.println("[β] Root-level array response validated successfully against collection schema.");
}
}
matchesJsonSchemaInClasspath() into a ResponseSpecBuilder template so all inheriting tests enforce both transport contracts and schema structures automatically.
package com.nikita.restassured.schema;
import io.restassured.builder.ResponseSpecBuilder;
import io.restassured.http.ContentType;
import io.restassured.specification.ResponseSpecification;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.lessThan;
public class SchemaResponseSpecIntegrationTest {
private ResponseSpecification studentContractSpec;
@BeforeClass
public void setupContractSpecification() {
// Standardize 200 OK + JSON ContentType + SLA + JSON Schema in a single specification
studentContractSpec = new ResponseSpecBuilder()
.expectStatusCode(200)
.expectContentType(ContentType.JSON)
.expectResponseTime(lessThan(1500L))
// Embed schema matcher directly into the ResponseSpecification template:
.expectBody(matchesJsonSchemaInClasspath("schemas/student-v1-schema.json"))
.build();
System.out.println("[*] Compiled student contract ResponseSpecification with embedded JSON Schema.");
}
@Test(description = "Verify /students/{id} automatically inherits schema validation from specification")
public void testEndpointWithSchemaResponseSpec() {
given()
.baseUri("https://staging-api.nikita-infotech.com/v1")
.pathParam("studentId", "STU-88219")
.when()
.get("/students/{studentId}")
.then()
// In one line: validates status 200, Content-Type, latency SLA, and Draft-07 schema!
.spec(studentContractSpec)
// Layer endpoint-specific value assertions
.body("fullName", equalTo("Nikita Sharma"));
System.out.println("[β] Verified endpoint using contract specification with embedded schema.");
}
}
package com.nikita.restassured.schema;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchema;
public class SchemaViolationTriageTest {
// ==========================================================================
// ANATOMY OF A SCHEMA VIOLATION
// Below we validate a payload with deliberate defects against a strict schema:
// 1. "enrolledCredits" is sent as a string ("16") instead of integer (16)
// 2. Mandatory field "email" is missing
// 3. Unapproved field "unexpectedBackdoorKey" is present (additionalProperties: false)
// ==========================================================================
@Test(description = "Demonstrate detailed diagnostic trace generated by schema violations")
public void testDiagnoseSchemaViolations() {
String strictSchema = "{\n" +
" \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n" +
" \"type\": \"object\",\n" +
" \"required\": [\"id\", \"email\", \"enrolledCredits\"],\n" +
" \"additionalProperties\": false,\n" +
" \"properties\": {\n" +
" \"id\": { \"type\": \"string\" },\n" +
" \"email\": { \"type\": \"string\", \"format\": \"email\" },\n" +
" \"enrolledCredits\": { \"type\": \"integer\" }\n" +
" }\n" +
"}";
// Defective payload simulating broken backend contract
String defectivePayload = "{\n" +
" \"id\": \"STU-88219\",\n" +
" \"enrolledCredits\": \"16\",\n" +
" \"unexpectedBackdoorKey\": true\n" +
"}";
// The assertion below will fail with detailed diagnostic violation reports:
// matchesJsonSchema(strictSchema).matches(defectivePayload)
}
// ==========================================================================
// DIAGNOSTIC FAILURE TRACE GENERATED BY VALIDATOR ENGINE:
// ==========================================================================
// java.lang.AssertionError: 1 expectation failed.
// Response body doesn't match expectation.
// Expected: The content to match the given a json schema.
// error: instance type (string) does not match any allowed primitive type (allowed: ["integer"])
// level: "error"
// schema: {"domain":"syntax","keyword":"type"}
// instance: {"pointer":"/enrolledCredits"}
// domain: "validation"
//
// error: object has missing required properties (["email"])
// level: "error"
// schema: {"domain":"syntax","keyword":"required"}
// instance: {"pointer":""}
//
// error: object instance has properties which are not allowed by the schema: ["unexpectedBackdoorKey"]
// level: "error"
// schema: {"domain":"syntax","keyword":"additionalProperties"}
// instance: {"pointer":""}
}
JSON SCHEMA DRAFT-07 SPECIFICATION MATRIX:
βββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬βββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββ
β SCHEMA KEYWORD / METHOD β DSL / SYNTAX SIGNATURE β TARGET VALUE β PRIMARY OPERATIONAL PURPOSE β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββββ€
β $schema β "http://json-schema.org/..." β Version URI β Declares Draft-07 dialect β
β Classpath Matcher β matchesJsonSchemaInClasspath β String path β Resolves schema from resources β
β File Matcher β matchesJsonSchema(File) β java.io.File β Resolves schema from filesystem β
β Stream Matcher β matchesJsonSchema(Stream) β java.io.Stream β Resolves schema from stream β
β Raw String Matcher β matchesJsonSchema(String) β JSON String β Resolves inline schema string β
β type β "type": "string"|"integer"|..β Primitive Type β Enforces strict data types β
β required β "required": ["id", "email"] β Array of Strings β Enforces mandatory properties β
β additionalProperties β "additionalProperties": falseβ Boolean flag β Disallows undocumented fields β
β format: email β "format": "email" β RFC 5322 String β Validates email format β
β format: date-time β "format": "date-time" β ISO-8601 String β Validates timestamp format β
β format: uri β "format": "uri" β RFC 3986 String β Validates URI / URL strings β
β pattern β "pattern": "^STU-[0-9]{5,}$" β ECMA-262 Regex β Enforces regex character rules β
β minimum / maximum β "minimum": 1, "maximum": 30 β Numeric bounds β Numerical range restrictions β
β minLength / maxLength β "minLength": 3 β Integer bounds β String length restrictions β
β minItems / uniqueItems β "minItems": 1, "unique..:trueβ Array properties β Array length & uniqueness rule β
β enum β "enum": ["ACTIVE", "CLOSED"] β Allowed Values β Restricts to allowed constants β
β NetworkNT Engine β JsonSchemaFactory.getInst(V7)β Factory Instance β High-throughput fast validator β
βββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄βββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββ€
β TOP 5 JSON SCHEMA VALIDATION BEST PRACTICES: β
β 1. Always set additionalProperties: false: Prevent API contract drift by disallowing undocumented keys. β
β 2. Validate schemas in ResponseSpecBuilder: Standardize contract validation across all test suites. β
β 3. Store schemas in src/test/resources/schemas/: Maintain schemas alongside test source code in Git. β
β 4. Use format: "email" and "date-time": Enforce standardized string formatting beyond simple regex. β
β 5. Use NetworkNT for high-volume collection testing: Maximize execution speed during large CI runs. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ