JSON Schema Validation with REST Assured

When exposing REST or HTTP based service APIs it’s important to validate that the API behaves correctly and that the exposed data format is structured in an expected manner. Using REST Assured it has always been easy to validate that the API behaves correctly and returns the expected data values. Validating that the structure of the document is correct has also been easy when it comes to XML.

XML Example

For example given that a service located at http://localhost:8080/car-records returns the following XML:

	    Production Pickup Truck with speed of 271kph
	    Isle of Man
	    Smallest Street-Legal Car at 99cm wide and 59 kg in weight
	    Most Valuable Car at $15 million

Imagine also that you have an Xml Schema in classpath called car-records.xsd that the XML data must conform to:


You can validate this in REST Assured like this:

import org.junit.Test;

import java.io.InputStream;

import static com.jayway.restassured.RestAssured.when;
import static com.jayway.restassured.matcher.RestAssuredMatchers.matchesXsd;

public class CarRecordsITest {

    @Test public void
    validate_car_records_response_conforms_to_the_expected_xsd() throws Exception {
        InputStream xsd = Thread.currentThread().getContextClassLoader().getResourceAsStream("car-records.xsd");

        		body(matchesXsd(xsd)). // (1)
        		body("records.car.find { it.@name == 'HSV Maloo' }.@year", equalTo("2006") // (2)

In (1) we check that the response body matches the Xsd schema and in (2) we assert that the year that the car named HSV Maloo made its record was 2006.

JSON Example

But what about JSON? REST Assured v2.1.0 supports validating the structure of a JSON document using JSON Schemas. For example consider this basic resource located at http://localhost:8080/greeter:

    "greeting": {
        "firstName": ,

Where <firstName> and <lastName> will be replaced by query parameters values. Using jsonschema.net we can generate a JSON schema for this resource and after a few tweaks it ends up like this:

    "type": "object",
    "$schema": "http://json-schema.org/draft-03/schema",
    "title": "Greeting",
    "description": "Will greet you",
    "id": "http://jsonschema.net",
    "required": true,
    "properties": {
        "greeting": {
            "type": "object",
            "id": "http://jsonschema.net/greeting",
            "required": true,
            "properties": {
                "firstName": {
                    "type": "string",
                    "id": "http://jsonschema.net/greeting/firstName",
                    "required": true
                "lastName": {
                    "type": "string",
                    "id": "http://jsonschema.net/greeting/lastName",
                    "required": true

Given this json schema (let’s call it greeter-schema.json) is available in class path we can now do:

import org.junit.Test;

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

public class JsonSchemaValidationITest {

    @Test public void
    greetings_json_resource_conforms_to_the_greeting_schema() {
                param("firstName", "John").
                param("lastName", "Doe").
                body(matchesJsonSchemaInClasspath("greeter-schema.json")). // (1)
                body("greeting.firstName", equalTo("John")). // (2)
                body("greeting.lastName", equalTo("Doe"));   // (3)

In (1) we check that the response body matches the JSON schema and in (2) and (3) we validate that the greeter service actually greeted the expected person.

JSON Schema validator is not part of REST Assured core so in order to use it you need to add the json-schema-validator module to classpath, for example by adding the following Maven dependency:


The json-schema-validator module in REST Assured builds on top of the excellent json-schema-validator project by Francis Galiegue et al. For additional info on the json schema validation support in REST Assured visit the Usage Guide.


As you can see REST Assured makes it easy validate that a JSON response body conforms to a given JSON schema. If you’ve been paying close attention perhaps you saw that the greeter-schema.json that we used in the example was based on the JSON schema draft 3 and not the lastest (currently draft 4) version. But not to worry, REST Assured (thanks to Francis Galiegue’s library) supports both draft 3 and 4.

You can also use REST Assured’s json-schema-validator module without using REST Assured. As long as you have a JSON document represented as a String you can do like this:

import org.junit.Test;
import static com.jayway.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;
import static org.hamcrest.MatcherAssert.assertThat;

public class JsonSchemaValidatorWithoutRestAssuredTest {

    @Test public void
    validates_schema_in_classpath() {
        // Given
        String json = ... // Greeting response

        // Then
        assertThat(json, matchesJsonSchemaInClasspath("greeting-schema.json"));


Visit the REST Assured web site for more info!

This Post Has 25 Comments

  1. Jason

    Hi Johan

    I am a beginner of testing REST using Assured. I have copied your code (carrecorditest) but found equalto with error. I thought I have imported all jar files.
    Could you please teach me?

    Many thanks.

    1. Johan Haleby

      You need to put Hamcrest in the classpath. Download the distribution zip files from the web page and you should be fine.

  2. Pavel

    Hi Johan! I’m trying to validate my JsonString using json-validator(without REST Assured).
    I use this:
    assertThat(jsonString, matchesJsonSchemaInClasspath(“greeting-schema.json”));

    And I have good test result every time, even is jsonString doesnot not right!

    For example: I have scheme on {“isSuccess”:true}, but this jsonString {“isSuccess”:true},{“isFalse”:false} is valid to aacording to my scheme

  3. Malini Rajamanickam

    Hi Johan,

    I am a newbie to this REST Assured. i tried to test a rest API for POST.

    my code looks like this

    contentType( “application/json”).

    when i execute this i get the following error message.

    Exception in thread “main” java.lang.IncompatibleClassChangeError: the number of constructors during runtime and compile time for com.jayway.restassured.internal.RequestSpecificationImpl$PathType do not match. Expected -1 but got 2

    Can you please help me to figure out where i am going wrong?

    1. Johan Haleby

      Probably something wrong with your classpath setup.

  4. Rk

    “enabled”: null,
    “default”: null,
    “setting “: null,
    “in”: {
    “en”: {
    “title”: “XXXX”
    this is the body i want to post ,,, how can i construct json body ,,, until now i was string this in string but as i go further json body is huge ,, is their any solution

    1. Johan Haleby

      You can either pass it as a byte-array or inputstream or use multiPart uploading. Please use the mailing list for asking questions in the future.

  5. Susai Arul Sebastian


    I am getting ” java.lang.IllegalArgumentException: Schema to use cannot be null.”

    My Code is,


    I created example.json file under Project root path. It is discoverable by FileReader.

    Please explain what i am doing wrong here

    1. Johan Haleby

      It needs to be in the root folder in your classpath, not the project root folder.

      1. Susai Arul Sebastian

        Thanks It works.

  6. Susai Arul Sebastian


    My Code is:

    param(“authtoken”, “dc1316914c00688cc4bced2bba604b6d”).

    I am getting the exception:

    java.net.UnknownHostException: https://web-proxy
    at java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method)
    at java.net.InetAddress$1.lookupAllHostAddr(InetAddress.java:883)
    at java.net.InetAddress.getAddressFromNameService(InetAddress.java:1236) and more

    Please guide me.

    1. Susai Arul Sebastian

      I got solved this exception by setting proxy. Thanks Anyway!!!

  7. Szymon

    Hi, could you please let me know if the json schema validator supports local file references? I would like to split the schema across multiple files and link the using $ref, but unfortunately this doesn’t seem to work for me. Could you provide me with some hints if this is supported?

    1. Johan Haleby

      I’m just providing the module that integrates json schema validation to REST Assured. It uses this project to accommodate this. Please have a look at its documentation to see if/how it’s supported.

  8. Szymon

    FYI to use relative references between schemas one should use an absolute uri path for the base schema passed to matchesJsonSchema.

  9. Mosley

    Hi, about this:
    usai Arul Sebastian
    August 16, 2014 at 12:47 / Reply

    I am getting ” java.lang.IllegalArgumentException: Schema to use cannot be null.”

    My Code is,


    I created example.json file under Project root path. It is discoverable by FileReader.

    Please explain what i am doing wrong here

    Johan Haleby
    August 16, 2014 at 13:09 / Reply
    It needs to be in the root folder in your classpath, not the project root folder.
    sorry I dont get what is “root folder in your classpath”, would you explain me that please? thanks in adnvance :)

  10. Sreekanth

    I am using restAssured for our rest api testing.
    Currently initiating JSON schema validation using restAssured.

    The example and doc says that “json schema (let’s call it greeter-schema.json) is available in class path”

    But, how do I add my .json schema file in class path and where should I place the .json schema file in my project.
    One of the answer says “root folder in your classpath”,

    In my classpath I have

    Are these the root folders?
    Should i add the .json schema file in class path something like this?

    Could you please help with in getting this resolved. Thanks in advance.

  11. saby

    Hi Johan,

    I am getting following exception. Can you please help?

    com.jayway.restassured.module.jsv.JsonSchemaValidationException: com.github.fge.jsonschema.core.exceptions.InvalidSchemaException: fatal: invalid JSON Schema, cannot continue
    Syntax errors:
    [ {
    “level” : “error”,
    “message” : “array must have at least one element”,
    “domain” : “syntax”,

    For empty array I have defined in the Json schema as follows

    “RelatedSecurities”: {
    “type”: “array”,
    “items”: []

    This seems to be proper as http://jsonschema.net/#/ and https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3

  12. Juan Sanchez

    Hi Sreekanth, did find out where to put the json schema ?

  13. Amit Patnaik

    Exception in thread “main” com.jayway.restassured.module.jsv.JsonSchemaValidationException: com.fasterxml.jackson.core.JsonParseException: Unexpected character (‘c’ (code 99)): expected a valid value (number, String, array, object, ‘true’, ‘false’ or ‘null’)
    at [Source: java.io.StringReader@21526f6c; line: 1, column: 2]
    at com.jayway.restassured.module.jsv.JsonSchemaValidator.matchesSafely(JsonSchemaValidator.java:233)
    at com.jayway.restassured.module.jsv.JsonSchemaValidator.matchesSafely(JsonSchemaValidator.java:75)
    at org.hamcrest.TypeSafeMatcher.matches(TypeSafeMatcher.java:65)
    at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:12)
    at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:8)
    at RestAssuredEIQ1.SocVueAPI.SocVue_Test1.checkJSONSchema(SocVue_Test1.java:77)
    at RestAssuredEIQ1.SocVueAPI.SocVue_Test1.main(SocVue_Test1.java:34)
    Caused by: com.fasterxml.jackson.core.JsonParseException: Unexpected character (‘c’ (code 99)): expected a valid value (number, String, array, object, ‘true’, ‘false’ or ‘null’)
    at [Source: java.io.StringReader@21526f6c; line: 1, column: 2]
    at com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:1369)
    at com.fasterxml.jackson.core.base.ParserMinimalBase._reportError(ParserMinimalBase.java:532)
    at com.fasterxml.jackson.core.base.ParserMinimalBase._reportUnexpectedChar(ParserMinimalBase.java:453)
    at com.fasterxml.jackson.core.json.ReaderBasedJsonParser._handleUnexpectedValue(ReaderBasedJsonParser.java:1386)
    at com.fasterxml.jackson.core.json.ReaderBasedJsonParser.nextToken(ReaderBasedJsonParser.java:669)
    at com.fasterxml.jackson.databind.MappingIterator.hasNextValue(MappingIterator.java:159)
    at com.github.fge.jackson.JsonNodeReader.readNode(JsonNodeReader.java:142)
    at com.github.fge.jackson.JsonNodeReader.fromReader(JsonNodeReader.java:127)
    at com.github.fge.jackson.JsonLoader.fromReader(JsonLoader.java:179)
    at com.github.fge.jackson.JsonLoader.fromString(JsonLoader.java:192)
    at com.jayway.restassured.module.jsv.JsonSchemaValidator.matchesSafely(JsonSchemaValidator.java:214)

    1. Bharat

      Hello Amit
      Did you get the error resolved? I have same error can you please post the answer here. I appreciate.

  14. Rx

    Hi I am trying to test my controller and the problem is the controller extends another controller which in turn use an interceptor for authentication.Interceptor has code like below
    final RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
    final RequestContext context = (RequestContext)attributes
    .getAttribute(PortalReservedParameters.REQUEST_CONTEXT_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST);
    final Subject subject = context.getSubject();
    final Authentication authentication = new JetspeedAuthentication(subject);

    How do i do authentication in this case
    Please help


  15. Komal Gosavi

    I am providing a json file with invalid arguments but still not getting any error for that.
    Valid json schema :
    “Fault”: “Operation completed successfully”,
    “Username:Password”: “ToolsQA:TestPassword”,
    “Authentication Type”: “Basic”

    And I am passing :
    “Fault”: “18273”,
    “Authentication Type”: “Basic”

  16. Veena


    Hi, I need some to figure out how to add namespace for a rest api.
    What are the packages i need to import to us e it ?Can someone please brief ?

Leave a Reply