Skip to content

RestAssured – want to verify the body structure of JSON response in RestAssured

When i request for GET request, I’m getting the JSON response, but here my requirement is to validate the structure of response body.

For example:

{
   "lotto":{
      "lottoId":5,
      "winning-numbers":[2,45,34,23,7,5,3],
      "winners":[
         {
            "winnerId":23,
            "numbers":[2,45,34,23,3,5]
         },
         {
            "winnerId":54,
            "numbers":[52,3,12,11,18,22]
         }
      ]
   }
}

The above response having structure, so i need to validate structure instead of one key value pair, how i can achieve this?

Answer

The best way is to verify json-schema matching.

Firstly, you need to add this dependency to your pom.xml

<!-- https://mvnrepository.com/artifact/io.rest-assured/json-schema-validator -->
<dependency>
  <groupId>io.rest-assured</groupId>
  <artifactId>json-schema-validator</artifactId>
  <version>3.3.0</version>
  <scope>test</scope>
</dependency>

Then you need to create a file json-schema-your-name.json with structure like that:

{
  "type": "object",
  "properties": {
    "data": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "flow_id": {
            "type": "string",
            "minLength": 36,
            "maxLength": 36
          },
          "flow_org_id": {
            "type": "string"
          }
        },
        "required": [ "flow_id", "flow_org_id" ]
      }
    }
  }
}

There are a bunch of services which generate schemas based on json – eg – this one

Once schema file is ready, you need to provide a path to your file in a String format – eg –

private static final String GET_SUBSCRIPTION_JSON_SCHEMA_PATH =
    "json/schemas/GetSubscriptionByIdSchema.json";

And invoke matchesJsonSchemaInClasspath("your/path/to/json-schema") method for assertion.

UPD:

So the flow will basically be like:

  • you have a schema file somewhere in project dir (and know its path)
  • you hit the endpoint in some test method
  • you match the response you’ve received with the schema file

Practically, it will look following:

  @Test
  public void someTestMethod() {
    Response responseToValidate = // here you should assign and store returned response
    
    responseToValidate
      .assertThat()      
      .statusCode(200)
      .body("json.path.to.needed.key", equalTo("123"))

.body(matchesJsonSchemaInClasspath(“path/to/your/schema/in/string/format”)); }