Validate Responses Against a JSON Schema in REST Assured
Check the shape of a whole response with JSON Schema draft 2020-12, covering matchesJsonSchemaInClasspath(..), a response that breaks the contract, an inline schema, and validating JSON that didn't come over HTTP.
Your payment tests check body("status", equalTo("RCVD")) and a few other fields. Then a release changes the amount from a string to a number, drops a required field, and starts sending an internal risk score, and every test still passes, because none of them reads those fields. In this guide, you’ll check the whole shape of a response against a JSON Schema: which fields exist, what type each one has, and that nothing else is there.
Level: Intermediate · Time: 25 minutes · Part of: Module 6: Schema and Contract Validation, section 1
What You’ll Build
You’ll build a test class called JsonSchemaTest with five tests. Two validate real responses against a schema file, one catches a response that breaks the contract, one uses a small inline schema, and one validates JSON that never went over HTTP.
The first test sends this request and validates the whole response:
1
2
3
4
5
6
7
8
9
10
11
POST /pisp/v1/domestic-payments HTTP/1.1
Host: localhost:<port>
Content-Type: application/json
{"instructionId":"INV-1","debtor":{...},"creditor":{...},"amount":{"value":"25.00","currency":"EUR"}, ...}
HTTP/1.1 201 Created
Content-type: application/json; charset=utf-8
Location: /pisp/v1/domestic-payments/pmt-1
{"paymentId":"pmt-1","instructionId":"INV-1","status":"RCVD", ...}
When you’re done, Maven reports five passing tests:
1
2
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
In this guide, you will:
- Validate a response against a schema file.
- Catch a response that breaks the contract.
- Validate with an inline schema.
- Validate JSON without an HTTP call.
What You Need
- About 25 minutes
- JDK 26 or later
- Maven 3.9 or later
- An IDE (IntelliJ IDEA, VS Code or Eclipse)
- Knowledge: you can check a response body with Hamcrest matchers, as taught in Pick the Right Hamcrest Matcher in REST Assured, and extract a value, from Extract Values From a Response in REST Assured. No earlier JSON Schema knowledge is needed.
How to Complete This Guide
You can work through this guide in one of two ways:
- Build it step by step: this is the first section of Module 6, so you start from scratch. Create
JsonSchemaTestin themodule-06test sources and follow every heading below. - Skip ahead: open the finished class (
JsonSchemaTest.java) and read along. You can run it at any time with the command in Run the Tests.
Get the code: clone the examples repository and change into it:
1
2
git clone https://github.com/javanibble/rest-assured-examples.git
cd rest-assured-examples
If you’ve already cloned it for an earlier module, run git pull instead.
Out of scope: this guide doesn’t cover the contract for errors, XML schemas, or validating every request against an OpenAPI document; they’re taught in section 2, section 3 and section 4.
Understand JSON Schema
The problem. A value check tests one field and says nothing about the rest. A field whose type changes, a required field that disappears, or a new field that leaks internal data all pass every test that doesn’t read them. To catch those, you need one check of the whole shape.
The concept. JSON Schema is a JSON document that describes other JSON documents: the type of each value, which properties are required, patterns, ranges and enumerations. REST Assured checks a response against one with its json-schema-validator module:
matchesJsonSchemaInClasspath(path)loads a schema from the classpath, usuallysrc/test/resources.matchesJsonSchema(schema)takes the schema as a string, aFileor a URL.
Both are static imports from io.restassured.module.jsv.JsonSchemaValidator, and both are plain Hamcrest matchers on a String. The $schema keyword at the top of a schema says which version of JSON Schema it uses. Since REST Assured 6.1, a schema that declares draft 2019-09 or 2020-12 is validated with the networknt validator, so modern keywords such as $defs, const and if/then/else work.
When to use it. Validate every response of an endpoint against its schema, as well as checking the values a test is about. Keep one schema per resource in src/test/resources, and use small inline schemas for one part of a large response. Use the same matcher on JSON from anywhere: stored examples, documentation or messages from a queue.
Check the values a test is about, and the shape of everything else.
Meet the API Under Test
Module 6 tests a payment initiation API in the style of PSD2. It runs on the JDK’s built-in HTTP server, like the APIs of the earlier modules, starts on a free port, and serves its endpoints under /pisp/v1. This guide uses two of them:
| Method | Path | Purpose |
|---|---|---|
POST | /domestic-payments | Create a payment; answers 201 |
GET | /domestic-payments/{id} | Read a payment; with ?format=v0, in an old shape that breaks the contract |
A created payment looks like this:
1
2
3
4
5
6
7
8
9
10
11
12
{
"paymentId": "pmt-1",
"instructionId": "INV-1",
"status": "RCVD",
"debtor": { "iban": "NL91ABNA0417164300", "name": "Anna de Vries" },
"creditor": { "iban": "NL69INGB0123456789", "name": "Jan Jansen" },
"amount": { "value": "25.00", "currency": "EUR" },
"remittanceInformation": "Invoice INV-1",
"requestedExecutionDate": "2026-11-21",
"createdAt": "2026-11-21T19:55:56Z",
"_links": { "self": { "href": "/pisp/v1/domestic-payments/pmt-1" } }
}
With ?format=v0, the same payment comes back in an old shape:
1
{ "paymentId": "pmt-2", "status": "PENDING", "amount": 25.0, "currency": "EUR" }
The contract lives in the module’s test resources, shortened here:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"required": ["paymentId", "instructionId", "status", "debtor", "creditor", "amount", "createdAt", "_links"],
"additionalProperties": false,
"properties": {
"paymentId": { "type": "string", "pattern": "^pmt-[0-9]+$" },
"status": { "enum": ["RCVD", "PDNG", "ACSP", "ACSC", "RJCT"] },
"debtor": { "$ref": "#/$defs/party" },
"creditor": { "$ref": "#/$defs/party", "required": ["iban", "name"] },
"amount": { "$ref": "#/$defs/amount" },
"createdAt": { "type": "string", "format": "date-time" },
...
},
"$defs": {
"party": { ... },
"amount": {
"type": "object",
"required": ["value", "currency"],
"additionalProperties": false,
"properties": {
"value": { "type": "string", "pattern": "^[0-9]{1,13}\\.[0-9]{2}$" },
"currency": { "type": "string", "pattern": "^[A-Z]{3}$" }
}
}
}
}
The schema uses these keywords:
requiredlists the fields that must be there.additionalProperties: falseforbids any field the schema doesn’t list.enumandpatternrestrict values: the status must be an ISO 20022 status code, and the amount a string with two decimals.$defsholds reusable parts, referenced with$ref. The creditor reusespartyand adds that it must have a name.
Validate a Response Against a Schema File
Set Up the Test Class
Goal: create the test class with the schema’s location and a helper that creates a payment.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package com.javanibble.module_06.section_01;
import static com.javanibble.module_06.support.SamplePayments.domesticPayment;
import static io.restassured.RestAssured.given;
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchema;
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertThrows;
import com.javanibble.pisp.PaymentInitiationApi;
import io.restassured.http.ContentType;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
class JsonSchemaTest {
private static final String PAYMENT_SCHEMA = "schemas/payment.schema.json";
private static PaymentInitiationApi api;
@BeforeAll
static void startApi() {
api = PaymentInitiationApi.start();
}
@AfterAll
static void stopApi() {
api.close();
}
private static RequestSpecification pisp() {
return given().baseUri(api.baseUri()).port(api.port()).basePath(PaymentInitiationApi.BASE_PATH);
}
private static String createPayment(String instructionId) {
return pisp().contentType(ContentType.JSON).body(domesticPayment(instructionId, "25.00"))
.when().post("/domestic-payments")
.then().statusCode(201)
.extract().path("paymentId");
}
}
What’s happening:
PaymentInitiationApiis Module 6’s test server. It starts and stops like the APIs of the earlier modules.PAYMENT_SCHEMAis the schema’s path on the classpath, relative tosrc/test/resources, without a leading slash.domesticPayment(..)comes from the module’sSamplePaymentshelper and returns a valid request body.createPayment(..)uses it to create a payment and returns its id.
Checkpoint: the class compiles. There are no tests yet, so there’s nothing to run until the next step.
Validate a Created Payment
Goal: create a payment and check every field of the response against the schema.
1
2
3
4
5
6
7
8
9
10
11
@Test
void aCreatedPaymentMatchesTheSchema() {
pisp()
.contentType(ContentType.JSON)
.body(domesticPayment("INV-1", "25.00"))
.when()
.post("/domestic-payments")
.then()
.statusCode(201)
.body(matchesJsonSchemaInClasspath(PAYMENT_SCHEMA));
}
What’s happening:
body(..)without a path passes the whole body, as text, to the matcher.matchesJsonSchemaInClasspath(..)validates it against the payment schema: one line checks every field of the response.
Checkpoint: run JsonSchemaTest from your IDE. One test runs and passes.
Validate a Read Payment Against the Same Schema
Goal: prove that GET returns the same shape as POST.
1
2
3
4
5
6
7
8
9
10
11
@Test
void aReadPaymentMatchesTheSameSchema() {
String id = createPayment("INV-2");
pisp()
.when()
.get("/domestic-payments/{id}", id)
.then()
.statusCode(200)
.body(matchesJsonSchemaInClasspath(PAYMENT_SCHEMA));
}
What’s happening:
createPayment(..)creates a payment and returns its id, and the test reads it back.- One schema for both endpoints proves they return the same shape, a promise that breaks quietly when two endpoints are built separately.
Checkpoint: run the class again. Two tests pass.
Catch a Response That Breaks the Contract
Validate the Old Shape
Goal: prove that the schema fails on a response that a value check would accept.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Test
void theSchemaCatchesAResponseThatBreaksTheContract() {
String id = createPayment("INV-3");
AssertionError error = assertThrows(AssertionError.class, () ->
pisp()
.queryParam("format", "v0")
.when()
.get("/domestic-payments/{id}", id)
.then()
.statusCode(200)
.body(matchesJsonSchemaInClasspath(PAYMENT_SCHEMA)));
assertThat(error.getMessage(), containsString("_links"));
}
What’s happening:
- The old shape still has a
paymentIdand a200status, so a test that reads only those would pass. - The schema fails, and
assertThrows(..)captures the failure so the test can check the report names a missing field. - The report lists every problem, each with a JSON path:
1
2
3
4
5
6
7
8
9
10
Response body doesn't match expectation.
Expected: The content to match the given JSON schema.
$.status: does not have a value in the enumeration ["RCVD", "PDNG", "ACSP", "ACSC", "RJCT"]
$.amount: number found, object expected
$: required property 'instructionId' not found
$: required property 'debtor' not found
$: required property 'creditor' not found
$: required property 'createdAt' not found
$: required property '_links' not found
$: property 'currency' is not defined in the schema and the schema does not allow additional properties
Checkpoint: run the class again. Three tests pass.
Decide per object whether extra fields are allowed. Without
additionalProperties: false, a schema accepts any extra field, including one that leaks data, such as an internal risk score. The last line of the report above comes from that keyword.
Validate With an Inline Schema
Check One Part of a Response
Goal: check only the amount of a payment, with a schema written in the test.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@Test
void anInlineSchemaForAQuickCheck() {
String id = createPayment("INV-4");
pisp()
.when()
.get("/domestic-payments/{id}", id)
.then()
.body(matchesJsonSchema("""
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"required": ["amount"],
"properties": {
"amount": {
"properties": {
"value": { "type": "string", "pattern": "^[0-9]+\\\\.[0-9]{2}$" },
"currency": { "const": "EUR" }
}
}
}
}
"""));
}
What’s happening:
- A schema doesn’t have to describe everything. This one checks only the amount, which suits a test that cares about one part of a large response.
- The matcher reads the whole body, so the schema starts at the root and walks down to
amount. constrequires an exact value. It’s a draft 2020-12 keyword, which is why the schema declares$schema.- The four backslashes are two for the Java text block and two for JSON, leaving one in the regular expression.
Checkpoint: run the class again. Four tests pass.
Always declare
$schema. Without it, REST Assured uses its older validator, which doesn’t know newer keywords and ignores them without a word: a schema with{"const": "EUR"}but no$schemaaccepts"USD".
Don’t combine the matcher with a path.
body("amount", matchesJsonSchema(..))passes a map, not JSON text, and fails with an emptyExpected:line. Usebody(matcher)without a path, and write the schema from the root.
Validate JSON Without an HTTP Call
Validate a Stored Example
Goal: check one example the schema must reject, and one it must accept.
1
2
3
4
5
6
7
8
9
10
11
12
@Test
void validatingJsonWithoutAnHttpCall() {
String example = """
{"paymentId": "pmt-1", "instructionId": "X", "status": "UNKNOWN",
"debtor": {"iban": "NL91ABNA0417164300"}, "creditor": {"iban": "NL69INGB0123456789", "name": "Jan"},
"amount": {"value": "1.00", "currency": "EUR"}, "createdAt": "2026-03-01T10:00:00Z",
"_links": {"self": {"href": "/pisp/v1/domestic-payments/pmt-1"}}}
""";
assertThat(example, not(matchesJsonSchemaInClasspath(PAYMENT_SCHEMA)));
assertThat(example.replace("UNKNOWN", "RCVD"), matchesJsonSchemaInClasspath(PAYMENT_SCHEMA));
}
What’s happening:
assertThat(..)is Hamcrest’s, and the schema matcher works on any string, so no request is sent."UNKNOWN"isn’t in the status enumeration, so the first example is rejected; with"RCVD", the same example is accepted.- This checks the schema itself, and suits stored examples, documentation or messages from a queue.
Checkpoint: run the class again. All five tests pass.
Don’t expect
formatto be checked. In draft 2020-12,formatis an annotation by default, so"format": "date-time"accepts"yesterday". Use apatternwhen the format matters.
Run the Tests
Run the following command from the repository root:
1
mvn test -pl module-06 -Dtest=JsonSchemaTest
You should see a result similar to the following:
1
2
3
4
5
6
[INFO] Running com.javanibble.module_06.section_01.JsonSchemaTest
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.490 s -- in com.javanibble.module_06.section_01.JsonSchemaTest
[INFO]
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS
Make a Test Fail
In anInlineSchemaForAQuickCheck, change "const": "EUR" to "const": "GBP" and run the command again. You should see a result similar to the following:
1
2
3
4
5
6
7
[ERROR] Failures:
[ERROR] JsonSchemaTest.anInlineSchemaForAQuickCheck:108 1 expectation failed.
Response body doesn't match expectation.
Expected: The content to match the given JSON schema.
$.amount.currency: must be the constant value 'GBP'
Actual: {"paymentId":"pmt-4","instructionId":"INV-4","status":"RCVD", ...}
The report names the JSON path, $.amount.currency, and the rule it broke. Below it, Actual shows the whole body, because the matcher received the whole body. Read the report lines first, then find the value in Actual.
Change "GBP" back to "EUR" and run the tests once more to confirm they pass.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
IllegalArgumentException: Schema to use cannot be null | The classpath location is wrong, such as schemas/paymnet.schema.json | Check the path, relative to src/test/resources, without a leading slash |
A failure with an empty Expected: line | The matcher was combined with a path, as in body("amount", ..) | Use body(matcher) without a path |
A schema accepts a value that breaks const | The schema has no $schema, so the older validator ignores the keyword | Declare draft 2020-12 with $schema |
| A schema accepts an invalid date | format is an annotation in draft 2020-12 | Use a pattern |
Try It Yourself
Exercise 1: Check the Id and Status of a New Payment
Add a test called aNewPaymentHasAValidIdAndStatus that creates a payment for "99.95" and validates the response with an inline schema that requires paymentId and status: the id must match ^pmt-[0-9]+$, and the status must be the constant "RCVD".
Hint
Start from aCreatedPaymentMatchesTheSchema, and use matchesJsonSchema(..) with a text block, as anInlineSchemaForAQuickCheck does. Remember $schema, or const is ignored.
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@Test
void aNewPaymentHasAValidIdAndStatus() {
pisp()
.contentType(ContentType.JSON)
.body(domesticPayment("INV-7", "99.95"))
.when()
.post("/domestic-payments")
.then()
.statusCode(201)
.body(matchesJsonSchema("""
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"required": ["paymentId", "status"],
"properties": {
"paymentId": { "type": "string", "pattern": "^pmt-[0-9]+$" },
"status": { "const": "RCVD" }
}
}
"""));
}
Exercise 2: Test What the Schema Rejects
Add a test called theSchemaRejectsBrokenExamples. Start from a valid example payment, and check that the payment schema accepts it. Then check that it rejects three broken versions: one whose creditor has no name, one with an extra field "internalRiskScore": 12, and one with the amount "99.9".
Hint
Use String.replace(..) on the valid example to make each broken version, and not(matchesJsonSchemaInClasspath(..)) for each rejection. The schema’s creditor, additionalProperties and amount rules each catch one.
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Test
void theSchemaRejectsBrokenExamples() {
String valid = """
{"paymentId": "pmt-7", "instructionId": "INV-7", "status": "RCVD",
"debtor": {"iban": "NL91ABNA0417164300"}, "creditor": {"iban": "NL69INGB0123456789", "name": "Jan Jansen"},
"amount": {"value": "99.95", "currency": "EUR"}, "createdAt": "2026-03-01T10:00:00Z",
"_links": {"self": {"href": "/pisp/v1/domestic-payments/pmt-7"}}}
""";
assertThat(valid, matchesJsonSchemaInClasspath(PAYMENT_SCHEMA));
assertThat(valid.replace(", \"name\": \"Jan Jansen\"", ""), not(matchesJsonSchemaInClasspath(PAYMENT_SCHEMA)));
assertThat(valid.replace("\"status\": \"RCVD\",", "\"status\": \"RCVD\", \"internalRiskScore\": 12,"),
not(matchesJsonSchemaInClasspath(PAYMENT_SCHEMA)));
assertThat(valid.replace("\"99.95\"", "\"99.9\""), not(matchesJsonSchemaInClasspath(PAYMENT_SCHEMA)));
}
Summary
You built JsonSchemaTest, which validates created and read payments against a schema file, catches a response that breaks the contract, checks one part of a payment with an inline schema, and validates JSON that never went over HTTP. A changed type, a missing field or a leaked one now turns a test red.
- A JSON Schema checks the whole shape of a response: required fields, types, patterns, enumerations and, with
additionalProperties: false, that nothing extra is there. matchesJsonSchemaInClasspath(..)validates against a schema insrc/test/resources, andmatchesJsonSchema(..)against an inline one.- Declare draft 2020-12 with
$schema, so REST Assured 6.1 and later use the networknt validator and keywords such asconstwork. - The matcher reads the whole body, so use it without a path, and write the schema from the root.
- The matcher works on any JSON string, so it can check stored examples and the schema itself, not only responses.
Here are the commands you used in this guide:
1
2
3
git clone https://github.com/javanibble/rest-assured-examples.git
cd rest-assured-examples
mvn test -pl module-06 -Dtest=JsonSchemaTest
What’s Next
Next: continue with Test an RFC 9457 Error Contract in REST Assured, which validates every error response against one RFC 9457 problem schema.
The code:
- The finished test class:
JsonSchemaTest.java - The schema:
payment.schema.json - The code and run commands for this module: Module 6 README
Go deeper:
- JSON Schema 2020-12, for every keyword the schemas use.
- Understanding JSON Schema, a guide to writing schemas.
- REST Assured Usage wiki, for the
json-schema-validatormodule.
Related guides:
- Pick the Right Hamcrest Matcher in REST Assured, for the value checks a schema complements.
- Share Response Checks With Response Specifications in REST Assured, for putting a schema check into a shared response specification.
