JSON Schema Validation in REST Assured 

Field-by-field assertions check a few values. JSON Schema validation checks the whole response — structure, required fields, data types, allowed values — in one assertion. It's the simplest form of contract testing: if a developer renames a field or starts sending a number as a string, the schema test catches it before clients break.

Advertisement

What Is a JSON Schema?

A JSON Schema is a JSON document that describes what another JSON document must look like — a blueprint for the API contract. It can define:

  • The structure (objects, nested objects, arrays).
  • Required and optional fields.
  • Data types — string, integer, number, boolean, object, array, null.
  • Constraints — minimum values, string length, patterns, allowed values (enum), array sizes.
  • Whether unexpected extra fields are allowed.

Interview answer: "JSON Schema is a blueprint of the API contract — structure, required fields, data types and constraints. In REST Assured I validate responses against schema files with matchesJsonSchemaInClasspath, so any contract change fails the test immediately, and I use field assertions on top for business values."

Sample Response and Schema

{
  "id": 101,
  "name": "John",
  "email": "john@test.com",
  "active": true,
  "roles": ["admin", "tester"],
  "address": { "city": "Hyderabad", "zip": "500001" }
}

The schema, saved as src/test/resources/schemas/user_schema.json:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "required": ["id", "name", "email", "active", "address"],
  "properties": {
    "id":      { "type": "integer", "minimum": 1 },
    "name":    { "type": "string", "minLength": 1 },
    "email":   { "type": "string", "pattern": "^[^@\\s]+@[^@\\s]+$" },
    "active":  { "type": "boolean" },
    "status":  { "type": "string", "enum": ["ACTIVE", "INACTIVE"] },
    "roles":   { "type": "array", "items": { "type": "string" }, "minItems": 1 },
    "address": {
      "type": "object",
      "required": ["city"],
      "properties": { "city": { "type": "string" }, "zip": { "type": "string" } }
    },
    "manager": { "type": ["string", "null"] }
  },
  "additionalProperties": false
}

This checks that the root is an object; five fields are required; every field has the right type; id is at least 1; status, if present, is ACTIVE or INACTIVE; roles has at least one string; address must contain a city; manager may be a string or null; and no unexpected fields are allowed.

Which draft? An important detail

REST Assured's json-schema-validator module is built on a validator that supports draft-04, so use the draft-04 $schema line shown above and draft-04 keywords. Newer keywords (such as const or if/then/else from later drafts) aren't enforced. If your team's schemas use draft 2019-09 or 2020-12 — common when they're generated from OpenAPI 3.1 — validate the response body with a newer Java library such as networknt's json-schema-validator instead.

Setting It Up

1. Add the dependency

<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>json-schema-validator</artifactId>
    <version>5.5.0</version>   <!-- keep it the same as your rest-assured version -->
    <scope>test</scope>
</dependency>

2. Store schemas on the classpath

src/test/resources/
└── schemas/
    ├── user_schema.json
    ├── order_schema.json
    └── product_list_schema.json

3. Validate

import static io.restassured.RestAssured.given;
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;
import static org.hamcrest.Matchers.equalTo;

given()
.when()
    .get("/users/101")
.then()
    .statusCode(200)
    .body(matchesJsonSchemaInClasspath("schemas/user_schema.json"))   // the contract
    .body("name", equalTo("John"));                                  // a business value

Other options: matchesJsonSchema(new File("…")) for a file path, or matchesJsonSchema(schemaString) for a schema held in a string.

What Failures Look Like

Each change below was run against the schema above; the messages are what a draft-04 validator reports:

API change Validation result
email missing 'email' is a required property
"id": "101" instead of 101 '101' is not of type 'integer'
"address": {} 'city' is a required property
"status": "DELETED" 'DELETED' is not one of ['ACTIVE', 'INACTIVE']
A new field "nickname": "JJ" Additional properties are not allowed ('nickname' was unexpected)

REST Assured's exact wording differs slightly, but it reports the same problem and the path to the failing field.

additionalProperties: the Setting That Decides Strictness ⭐

By default, JSON Schema allows fields the schema doesn't mention. Without "additionalProperties": false, the "new field" example above passes — we checked. So a schema without it won't tell you when the API adds new fields or leaks extra data — and a renamed field is caught only if the old name was listed as required.

Setting Behaviour Use when
additionalProperties: false Any unexpected field fails the test Strict contracts; catching data leaks (e.g. a password hash appearing in a response)
Not set (default) Extra fields are ignored APIs that add fields often and consumers tolerate them

Many teams use strict schemas for their own APIs and lenient ones for third-party APIs.

When the Contract Changes

Developer changes the API
        ↓
Schema test fails in CI
        ↓
Discuss with the developer / check the API spec
        ↓
Intentional change? ── Yes → update the schema file (in the same pull request ideally)
                   └── No  → raise a defect

A schema failure is information, not automatically a bug — but it must never be "fixed" by loosening the schema without asking why the response changed.

JSON Schema vs Field-Level Assertions

Field assertions Schema validation
Check specific values (name is "John") Check structure, types and required fields
Many assertions for a large payload One assertion covers the whole response
Miss fields nobody asserted on Catch missing, mistyped or unexpected fields
Verify business logic Can't tell whether a value is correct, only whether it's valid

Use both: the schema proves the shape; field assertions prove the business values. More: Response Validation in REST Assured.

Best Practices

  • One schema file per response type, under src/test/resources/schemas, versioned with the tests.
  • Generate a first draft from a real response or the OpenAPI spec, then tighten it by hand (required fields, enums, additionalProperties).
  • Validate every business-critical endpoint, including error responses — their shape is part of the contract too.
  • Review schema changes with developers; never loosen a schema just to make a test pass.
  • Keep the schema draft consistent with your validator (draft-04 for REST Assured's module).

See how a request is built and its response validated step by step in the REST Assured Visualizer. The same idea in Postman and for XML: JSON & XML in API Testing.

From Real Projects

My API experience covers CRUD operations, HTTP methods, JSON path, and validating JSON and XML responses, and my automation work was in Java with TestNG. That combination is exactly what REST Assured builds on: HTTP calls in Java, JSON path for extracting values, and TestNG for running and grouping the tests. If you already know Selenium with TestNG, REST Assured fits into the same project structure. Testsigma supports web, mobile and API test automation, so understanding APIs was part of understanding the product I was testing. A schema check catches missing and wrongly typed fields that value checks can miss.

📚 Official documentation: REST Assured official site · MDN: HTTP

Frequently Asked Questions

What is JSON Schema validation?

Checking a JSON response against a schema that defines its structure, required fields, types and constraints — a quick, automated contract test.

How do you validate a JSON schema in REST Assured?

Add the json-schema-validator dependency, put the schema under src/test/resources, and assert .body(matchesJsonSchemaInClasspath("schemas/user_schema.json")).

Does schema validation fail when the API adds a field?

Only if the schema sets "additionalProperties": false. By default, extra fields are allowed.

Which JSON Schema draft does REST Assured support?

Its json-schema-validator module supports draft-04. For newer drafts, use a newer validator library on the response body.

Where should schema files live?

Under src/test/resources/schemas, so matchesJsonSchemaInClasspath() can find them.

Does a schema replace field assertions?

No — the schema checks the shape; field assertions check that the values are right for the scenario.