How to validate JSON Schema in Rest Assured

 

To validate a JSON schema using Rest Assured in a GET API response, you can use the JsonSchemaValidator provided by Rest Assured. It helps ensure that the structure of the JSON returned from the API matches an expected schema.


Steps to Use JSON Schema Validation in Rest Assured



1. Add Dependencies


<dependencies>
    <!-- Rest Assured -->
    <dependency>
        <groupId>io.rest-assured</groupId>
        <artifactId>rest-assured</artifactId>
        <version>5.4.0</version>
        <scope>test</scope>
    </dependency>

    <!-- JSON Schema Validator -->
    <dependency>
        <groupId>io.rest-assured</groupId>
        <artifactId>json-schema-validator</artifactId>
        <version>5.4.0</version>
        <scope>test</scope>
    </dependency>
</dependencies>





2. Create JSON Schema File

Create a file users-schema.json in the src/test/resources directory.


{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "properties": {
    "page": { "type": "integer" },
    "per_page": { "type": "integer" },
    "total": { "type": "integer" },
    "total_pages": { "type": "integer" },
    "data": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "id": { "type": "integer" },
          "email": { "type": "string" },
          "first_name": { "type": "string" },
          "last_name": { "type": "string" },
          "avatar": { "type": "string" }
        },
        "required": ["id", "email", "first_name", "last_name", "avatar"]
      }
    },
    "support": {
      "type": "object",
      "properties": {
        "url": { "type": "string" },
        "text": { "type": "string" }
      },
      "required": ["url", "text"]
    }
  },
  "required": ["page", "per_page", "total", "total_pages", "data", "support"]
}





3. Java Code to Validate Schema


import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;
import static io.restassured.RestAssured.*;

public class JsonSchemaValidationTest {

    public static void main(String[] args) {

        RestAssured.baseURI = "https://reqres.in";

        given()
            .contentType(ContentType.JSON)
        .when()
            .get("/api/users?page=2")
        .then()
            .assertThat()
            .statusCode(200)
            .body(matchesJsonSchemaInClasspath("users-schema.json"));

        System.out.println("Schema validated successfully.");
    }
}

No comments:

Post a Comment