Skip to content
Advertisement

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:

JavaScript

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

Advertisement

Answer

The best way is to verify json-schema matching.

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

JavaScript

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

JavaScript

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 –

JavaScript

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:

JavaScript

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

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement