← Back to libraryQuestion 240 of 468
🔌REST AssuredAdvanced

JSON Schema Validation

📌 Definition:

JSON Schema validation checks that a response's STRUCTURE (fields, types, required keys) conforms to a defined schema — a contract test that catches breaking API changes beyond individual field values.

📖 Detailed Explanation:

With the json-schema-validator module, you assert then().body(matchesJsonSchemaInClasspath('user-schema.json')). The schema (a .json file) declares expected properties, their types, which are required, formats, and constraints. Unlike field-by-field checks, schema validation verifies the whole shape at once, so it catches renamed/removed/mis-typed fields — ideal for contract/regression testing across API versions. You can also validate against an inline schema string or a URL. Keeping schemas versioned alongside tests turns REST Assured into a lightweight contract-testing tool.

🔑 Key Points:
  • matchesJsonSchemaInClasspath('schema.json') validates structure
  • Checks required fields, types, formats — the whole shape
  • Catches renamed/removed/mis-typed fields (contract regressions)
  • Needs the json-schema-validator dependency
🌍 Real-World Example:

A contract test: when().get('/users/1').then().body(matchesJsonSchemaInClasspath('schemas/user.json')) fails immediately if the API drops the 'email' field or changes 'id' from number to string.

🎯 Scenario-Based Interview Question:

Field-level assertions pass, but a downstream consumer broke when the API changed 'id' from int to string. How could REST Assured have caught this earlier?