How to Validate JSON Schema in REST Assured?
Here are the steps:
Step 1: Transform JSON to JSON Schema, using tool https://transform.tools/json-to-json-schema
JSON
{
"name": "morpheus",
"job": "leader"
}
JSON Schema
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Generated schema for Root",
"type": "object",
"properties": {
"name": {
"type": "string"
},
"job": {
"type": "string"
}
},
"required": [
"name",
"job"
]
}
Step 2: Paste JSON schema to .json file inside src/test/resources. I have pasted it to schema/reqres/createuser.json
Step 3: Add JSON Schema validator dependency
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-schema-validator</artifactId>
<version>5.4.0</version>
</dependency>
Step 4: Import matcher
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;
Step 5: Call Matcher in response body
@Test
public void JSONSchemaValidator()
{
RestAssured.baseURI = "https://reqres.in/";
RestAssured.basePath = "/api/";
User userObj = new User("Ram", "QA");
given()
.header("Content-Type","application/json")
.body(userObj)
.when()
.post("/users")
.then()
.body(matchesJsonSchemaInClasspath("schema/reqres/createuser.json"));
}