Validate a JSON response in REST Assured by chaining body matchers inside then(), and use matchesJsonSchema() when the response must satisfy a JSON Schema.
REST Assured can check the HTTP status, response headers, individual JSON values, array contents, nested objects, and the overall response contract. These checks answer different questions: a status assertion confirms the request outcome, a JSON path assertion confirms a particular value, and a schema assertion confirms the response shape.
Raw JSON syntax is a separate concern. A payload can be perfectly valid JSON while still failing a test because an ID has the wrong value, an array contains an extra record, or a required property is missing. A local syntax check helps distinguish malformed JSON from a failed content assertion.

What REST Assured validates
Start by deciding which part of the response belongs to the API contract. Rest Assured exposes response validation through a fluent chain, so the status, headers, and body can be checked in one place without manually parsing the response into a Java collection.
| Validation layer | Example matcher | What it confirms |
|---|---|---|
| HTTP status | statusCode(200) | The endpoint returned the expected HTTP outcome. |
| Content type | contentType("application/json") | The response declares a JSON-compatible media type. |
| JSON field | body("id", equalTo(123)) | A value at a specific JSON path matches the expected type and value. |
| Array or collection | body("items", hasSize(2)) | The collection has the expected size, contents, or element properties. |
| JSON Schema | body(matchesJsonSchema(schema)) | The response satisfies the selected schema rules. |
Do not rely on one assertion to cover all of these concerns. A body-path matcher does not replace a status check, and a schema matcher does not necessarily enforce a changing business value unless that value is represented in the schema.
Add the first JSON response assertions
-
Add REST Assured, Hamcrest, and REST Assured's separate json-schema-validator module to the test project before using matchesJsonSchema(), then import the static methods you need, such as given, equalTo, hasItem, hasSize, not, and emptyString.
-
Send the request and explicitly request JSON. Replace the placeholder URL with the test environment: given().baseUri("https://api.example.test").header("Accept", "application/json").when().get("/users/123").
-
Open the validation chain with then(). Check the transport-level result before checking fields: statusCode(200).contentType("application/json"). The content-type assertion is important because an HTML error page or a plain-text body is not the JSON response your paths expect.
-
Extend the same chain with a body matcher for each required value. For example, body("id", equalTo(123)) verifies both the value and its numeric type, while body("name", not(emptyString())) rejects a missing or blank name.
-
Add paths for nested objects and arrays. Use dot notation for object properties, square brackets for array indexes, and collection matchers when the whole list matters: body("items", hasSize(2)).body("items[0].sku", equalTo("ABC-123")).
-
Add a JSON Schema matcher if the endpoint has a documented response contract. Load the schema text into the test and apply body(matchesJsonSchema(schema)) to the response.
-
Run the test and inspect the reported JSON path, expected value, and actual value. If the failure message does not reveal enough context, extract and print the response body with response.asString() while avoiding secrets or sensitive personal data.
A compact fluent chain looks like this: given().baseUri("https://api.example.test").header("Accept", "application/json").when().get("/users/123").then().statusCode(200).contentType("application/json").body("id", equalTo(123)).body("name", not(emptyString())).body("roles", hasItem("admin")).
Assert nested values and arrays
REST Assured uses JSON-path-style expressions to locate values in a response. Paths are relative to the root object by default, so body("user.id", equalTo(123)) selects the id inside the user object. This makes the assertion readable without converting the response into a separate Java model first.
-
Use body("address.city", equalTo("London")) for a nested property.
-
Use body("items[0].sku", equalTo("ABC-123")) for a specific array element.
-
Use body("items", hasSize(2)) when the exact number of records is contractual.
-
Use body("roles", hasItem("admin")) when the array must contain a particular value.
-
Use body("items", everyItem(notNullValue())) when every element must be present and non-null.
-
Use explicit type matchers when a string such as "123" must not pass for the number 123. A loose equality check can conceal a server-side type change.
Prefer targeted assertions for fields that must be correct. Avoid comparing the entire response to one large literal unless the endpoint is deliberately fixed, because unrelated metadata or generated timestamps can make the test brittle.
Check the full contract with JSON Schema
A JSON Schema assertion is useful when many endpoints share rules such as required properties, object types, array item types, enumerations, or additional-property restrictions. It complements JSON path assertions: the schema describes the permitted structure, while path assertions check individual business values.
Load the schema from a controlled test resource and apply it with body(matchesJsonSchema(schema)). Keep the schema beside the test rather than embedding a large document in the method. When a schema check fails, inspect the reported instance path to identify the property whose type, required status, or allowed value does not match.
Check the JSON Schema draft and your REST Assured version before depending on a particular keyword or format rule. Schema validation also depends on the quality of the schema: a permissive fixture can pass many incorrect payloads. Use JSON paths for important values that are not represented in the schema.
Check raw JSON syntax and structure locally
-
Capture the exact response body, not an expected fixture or a manually recreated example. In a failing test, response.asString() can provide the body for inspection. Preserve its line breaks so a reported position maps back to the original response.
-
Open the JSON Validator and paste or type the response into its input box.
-
Read the verdict. A green “Valid JSON” result means the parser accepted the text. A red result identifies a parsing failure and the line and column where it occurred.
-
If the result is invalid, correct the character at the reported location, paste the revised text again, and repeat until the parser accepts it. Common strict-JSON failures include single quotes, unquoted keys, trailing commas, comments, and unbalanced braces or brackets.
-
For valid JSON, review the structure report. Its top-level type, maximum depth, and total key count provide a quick sanity check against the endpoint contract. An unexpected array, excessive nesting, or a much larger key count can reveal that the wrong representation was returned.
Validation runs entirely in the browser using the native JSON parser, so the response text is not uploaded to a server. This makes the tool suitable for checking private payloads without sending them to an external service. The RFC 8259 JSON grammar is strict; the validator does not repair malformed input or guess a intended correction.
The JSON Validator deliberately leaves the text unchanged and is not a formatter. It does not beautify or minify the response. Also, its “Valid JSON” verdict confirms syntax rather than business correctness or schema compliance. The parser reads numbers as IEEE-754 doubles, so integers beyond 2^53 can lose precision. Treat a valid result as a clean starting point, then let REST Assured perform the field and schema assertions.
Trace common validation failures
| Symptom | Likely interpretation | Next check |
|---|---|---|
| A JSON path is reported as missing | The root key differs, the path is incorrect, or the body was not exposed as JSON. | Inspect the status, Content-Type, and exact response body. |
| The expected number differs from a string | The server changed the field’s JSON type. | Use an explicit numeric matcher or correct the response contract. |
| An array-size assertion fails | The response contains missing or additional records. | Inspect the array before deciding whether its exact size is contractual. |
| A schema assertion fails | A required field, property type, or other schema rule is not satisfied. | Use the reported instance path to locate the mismatched value. |
| The whole body cannot be traversed | The payload may be malformed, empty, or labeled with a non-JSON content type. | Validate the raw text and verify the response headers. |
For diagnostic output, capture the response and print only the information needed to explain the failure:
Response response = given().baseUri(baseUri).header("Accept", "application/json").when().get("/users/123");
System.out.println("status=" + response.statusCode());
System.out.println("contentType=" + response.getContentType());
System.out.println(response.asString());
Redact credentials, tokens, and personal information before adding response bodies to CI logs. If the raw text is valid but the REST Assured path still fails, focus on the expected root shape, the JSON-path expression, and the declared content type rather than rewriting the payload.
Keep the validation suite maintainable
Put stable expectations in a reusable REST Assured response specification, then keep endpoint-specific values in individual tests. A shared specification can hold the expected status, JSON content type, and common required fields; each test can then assert the values unique to that endpoint.
-
Use schema assertions for stable structural rules and JSON path assertions for business values.
-
Assert relationships as well as standalone values when the relationship is part of the contract.
-
Avoid assertions on generated timestamps, random identifiers, or ordering that the API does not guarantee.
-
Keep one focused test for a missing field, incorrect type, malformed JSON, and wrong status so each failure identifies a different category of regression.
-
When a test fails unexpectedly, validate the captured body with JSON Validator, inspect its structure, and then correct either the fixture, the schema, or the REST Assured path.
The complete check is a sequence: confirm the HTTP result and content type, validate the raw JSON syntax, assert required paths and collections, apply a schema where a contract exists, and use the actual response body to diagnose any mismatch.