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:

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:

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:

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:

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

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.

Conclusion

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:

Visit the REST Assured web site for more info!

This Post Has 25 Comments

  1. 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. You need to put Hamcrest in the classpath. Download the distribution zip files from the web page and you should be fine.

  2. 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. Hi Johan,

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

    my code looks like this

    given().
    contentType( “application/json”).
    when().
    post(“/proxy/service/login”).
    then().
    statusCode(200);

    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. Probably something wrong with your classpath setup.

  4. {
    “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. 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. Hi,

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

    My Code is,

    get(“/service/single-user”).then().assertThat().body(matchesJsonSchemaInClasspath(“example.json”));

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

    Please explain what i am doing wrong here

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

      1. Thanks It works.

  6. Hi

    My Code is:

    given().
    param(“authtoken”, “dc1316914c00688cc4bced2bba604b6d”).
    when().
    get(“https://invoice.zoho.com/api/v3/organizations”).
    then().assertThat().statusCode(200);

    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. I got solved this exception by setting proxy. Thanks Anyway!!!

  7. 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. 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. FYI to use relative references between schemas one should use an absolute uri path for the base schema passed to matchesJsonSchema.

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

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

    My Code is,

    get(“/service/single-user”).then().assertThat().body(matchesJsonSchemaInClasspath(“example.json”));

    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. Hi,
    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. 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. Hi Sreekanth, did find out where to put the json schema ?

  13. 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. Hello Amit
      Did you get the error resolved? I have same error can you please post the answer here. I appreciate.

  14. 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);
    SecurityContextHolder.getContext().setAuthentication(authentication);

    How do i do authentication in this case
    Please help

    Thanks,
    Rx

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

    And I am passing :
    {
    “FaultId”: “OPERATION_SUCCESS”,
    “Fault”: “18273”,
    “Authentication Type”: “Basic”
    }

  16. twyeuywui

    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

Close Menu