JSON Schema in REST Assured
JSON Schema is a contract (or blueprint) that defines the structure, data types, required fields, and allowed values of a JSON request or response.
Think of it as a rulebook that verifies whether a JSON payload follows the expected API contract before it is accepted.
In API automation, JSON Schema is commonly used with REST Assured and the JSON Schema Validator library to validate API responses.
Interview Answer
"JSON Schema is a blueprint that defines the expected structure, data types, required fields, and allowed values of a JSON payload. In REST Assured, I validate API responses against JSON Schema using
matchesJsonSchemaInClasspath(). This ensures the API follows the agreed contract and prevents integration issues."
What Does JSON Schema Validate?
A JSON Schema validates:
- JSON structure
- Required fields
- Optional fields
- Data types
- Nested objects
- Arrays
- Value constraints
JSON Schema at a Glance
| Concept | Meaning | Why It Matters | Tools |
|---|---|---|---|
| JSON Schema | Blueprint for JSON structure | Validates API contract | REST Assured, JSON Schema Validator |
| Required Fields | Mandatory fields | Prevents missing data | JSON Schema |
| Data Types | Defines type of each field | Ensures correct values | REST Assured |
| Nested Objects | Object validation | Ensures correct hierarchy | JSON Schema |
| Arrays | Validates array structure | Ensures collection consistency | JSON Schema |
Why JSON Schema Validation Is Important
Without schema validation, APIs may return:
- Missing fields
- Incorrect data types
- Extra unexpected fields
- Wrong JSON structure
These issues can break client applications and downstream systems.
Benefits
- Validates API contract
- Ensures consistent responses
- Detects missing fields
- Validates data types
- Detects structural changes
- Prevents integration failures
- Improves automation reliability
Interview Answer
"JSON Schema validation ensures API responses follow the predefined contract by validating the response structure, mandatory fields, and data types. It helps prevent integration failures and ensures consistent responses across different environments."
Sample JSON Response
Suppose an API returns the following response:
{
"id": 101,
"name": "John",
"email": "john@test.com",
"active": true
}
Corresponding JSON Schema
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"id": {
"type": "integer"
},
"name": {
"type": "string"
},
"email": {
"type": "string"
},
"active": {
"type": "boolean"
}
},
"required": [
"id",
"name",
"email",
"active"
]
}
What Does This Schema Validate?
The schema ensures:
- Root object is valid
idis an integernameis a stringemailis a stringactiveis a boolean- All required fields are present
Adding the JSON Schema Validator Dependency
Include the JSON Schema Validator dependency along with REST Assured.
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-schema-validator</artifactId>
<version>5.5.0</version>
<scope>test</scope>
</dependency>
Project Structure
Store schema files under the test resources folder.
src
│
├── test
│
├── java
│
└── resources
│
├── schemas
│ user_schema.json
│ employee_schema.json
│ product_schema.json
│
└── config.properties
Validating a Response Against JSON Schema
REST Assured provides the matchesJsonSchemaInClasspath() method.
Example:
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;
given()
.when()
.get("/users/10")
.then()
.statusCode(200)
.body(matchesJsonSchemaInClasspath("schemas/user_schema.json"));
The schema file is automatically loaded from the classpath.
Complete Example
Response response =
given()
.when()
.get("/users/10");
response.then()
.statusCode(200)
.body(matchesJsonSchemaInClasspath("schemas/user_schema.json"));
Validation Flow
API Request
│
▼
Receive JSON Response
│
▼
Load JSON Schema
│
▼
Compare Response with Schema
│
▼
───────────────
│ Structure OK │────► PASS
───────────────
───────────────
│ Structure Wrong │──► FAIL
───────────────
What Happens During Validation?
REST Assured checks:
- Root JSON structure
- Required fields
- Optional fields
- Data types
- Nested objects
- Arrays
- Property names
If everything matches the schema, the test passes.
Otherwise, the test fails.
What If a Required Field Is Missing?
Suppose the API returns:
{
"id":101,
"name":"John"
}
The email field is missing.
Schema validation result:
FAILED
Reason:
Required property 'email' not found.
What If the Data Type Is Wrong?
Expected:
"id":101
Actual:
"id":"101"
Expected type:
Integer
Actual type:
String
Result:
Schema Validation Failed
What If an Entire Object Is Missing?
Expected:
{
"address":{
"city":"Hyderabad"
}
}
Actual:
{
}
Result:
Schema Validation Failed
What Happens If the API Schema Changes?
Schema validation tests are designed to fail whenever the API contract changes.
This acts as an early warning system.
Typical Workflow
Developer Changes API
│
▼
Schema Validation Test Runs
│
▼
Validation Fails
│
▼
Discuss With Developers
│
▼
Intentional Change?
│ │
▼ ▼
Yes No
│ │
▼ ▼
Update Schema Raise Defect
Real-Time Example
During one sprint, a new field was added to the User API response. The schema validation test failed immediately, indicating a contract change. After confirming the update with the development team, I modified the
user_schema.jsonfile to reflect the new API contract and reran the tests successfully.
Advantages of JSON Schema Validation
- Validates complete response structure
- Detects missing fields
- Validates data types
- Prevents contract violations
- Ensures API consistency
- Reduces integration failures
- Improves automation reliability
- Provides early detection of API changes
JSON Schema vs Field-Level Assertions
| Field-Level Assertions | JSON Schema Validation |
|---|---|
| Checks individual fields | Validates the complete JSON structure |
| Verifies specific values | Verifies the entire API contract |
| Requires multiple assertions | Single schema validation covers the whole response |
| Difficult to maintain for large payloads | Easy to maintain with schema files |
| Does not validate structure | Validates structure, types, and required fields |
Best Practices
- Maintain separate schema files for each API.
- Store schema files under
src/test/resources/schemas. - Validate all business-critical APIs.
- Version schema files along with API changes.
- Review schema updates with developers before modifying automation.
- Combine schema validation with field-level assertions for business logic validation.
Real-Time Interview Answer
"In our REST Assured framework, we maintain JSON Schema files for all important APIs under the
test/resources/schemasfolder. During execution, we validate responses usingmatchesJsonSchemaInClasspath(). This ensures the API response structure, mandatory fields, and data types always match the agreed API contract. If the schema changes, the validation fails immediately, allowing us to confirm the change with developers and either update the schema or raise a defect."
Frequently Asked Questions (FAQs)
1. What is JSON Schema?
JSON Schema is a contract or blueprint that defines the expected structure, data types, required fields, and allowed values of a JSON payload. It is used to validate whether an API request or response complies with the agreed API contract.
2. Why is JSON Schema validation important?
It ensures that API responses follow the expected contract by validating the response structure, required fields, nested objects, arrays, and data types. This prevents integration failures caused by unexpected API changes.
3. How do you validate a JSON Schema in REST Assured?
Add the JSON Schema Validator dependency, create a schema file under the classpath (typically src/test/resources), and validate the response using:
.body(matchesJsonSchemaInClasspath("schemas/user_schema.json"))
4. Where are JSON Schema files stored?
They are typically stored under:
src/test/resources/schemas
This allows matchesJsonSchemaInClasspath() to locate them automatically.
5. What happens if the API schema changes?
Schema validation tests fail immediately, indicating a contract change. After discussing the change with developers, you either update the schema file to match the new contract or raise a defect if the change was unintended.
6. What does JSON Schema validation detect that field-level assertions do not?
JSON Schema validates the entire response contract, including:
- Overall JSON structure
- Required and optional fields
- Data types
- Nested objects
- Arrays
Field-level assertions typically verify only individual field values and cannot guarantee overall contract compliance.