How to validate JSON Schema in Rest Assured

 



What is JSON Schema?

  • JSON Schema is a specification that defines the structure of a JSON document.
  • It is used to validate that a given JSON response (or request) follows a predefined format.

A JSON Schema defines:

  • Data types (string, number, object, array, boolean, null)
  • Required vs optional fields
  • Field constraints (min/max length, patterns, ranges, enum values, etc.)
  • Nested objects and arrays

Why validate JSON Schema?
  • To check that API responses always follow the contract agreed between client and server.
  • To avoid breaking changes when backend updates occur.
  • To make automated testing more robust and reliable.

How to validate JSON Schema in Rest Assured

Rest Assured provides built-in support for JSON Schema validation using the json-schema-validator library.

This includes:

1. Prepare a JSON Schema file
  • Create a .json file that defines the expected schema of the API response.
  • Example: define required fields, their data types, and structure.

2. Add JSON Schema Validator dependency
  • Rest Assured integrates with the json-schema-validator library, which enables schema-based validation.

3. Call the API using Rest Assured
  • Perform a request (GET/POST/etc.) to get the API response.

4. Validate Response against JSON Schema
  • Use Rest Assured’s built-in schema validator methods to check whether the actual JSON response matches the schema.
  • If the response matches → test passes.
  • If not → test fails with details about what part of the schema is violated.

In short:

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>


Just visit this page to create JSON schema or use existing below schema for API:
https://reqres.in/api/users?page=2



2. Create JSON Schema File

We can create schema from any json schema creator website. One of the best website is: http://json-schema.org/




















Create a json schema file named as users-schema.json for GET API: https://reqres.in/api/users?page=2 and placed 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.");
    }
}



Code explanation:

(a) Define the base URI
(b) Send request for GET API as mentioned in code and get response
(c) validate response from JSON schema validator by this method matchesJsonSchemaInClasspath("users-schema.json")


Suggested Posts:

1. Test Preemptive Authentication in RestAssured
2. Test Form Authentication in RestAssured
3. Test DELETE API in RestAssured
4. Validate Response by Matchers API in RestAssured
5. Validate API Response from Database in RestAssured

How to test a SOAP API by Rest Assured



What is SOAP API?

  • SOAP (Simple Object Access Protocol) is a protocol for exchanging structured data between systems over a network.
  • It uses XML as the message format and typically runs over HTTP/HTTPS.
  • SOAP APIs are often used in enterprise applications (like banking, telecom, insurance) because they enforce strict standards for security, structure, and messaging.

Key Features of SOAP API:
  • Message format → Always XML (not JSON).
  • Transport → Usually HTTP/HTTPS (but can also use SMTP, TCP, etc.).
  • WSDL (Web Services Description Language) → An XML document that describes the service (endpoints, operations, request/response structure).
  • Highly standardized → Supports security (WS-Security), transactions, and reliable messaging.

Testing a SOAP API GET request using Rest Assured is possible but requires understanding how SOAP works. However, SOAP typically uses POST, not GET, because it sends a full XML envelope in the body. But if the SOAP service is exposed via GET (rare, usually for testing or WSDL fetching), we can use RestAssured.get().


How to Test a SOAP API in Rest Assured

When using Rest Assured to test a SOAP API:

1. Understand the WSDL/Endpoint
  • Get the SOAP endpoint URL and know which operations are available.
  • Review the WSDL (it defines the request/response XML structure).
2. Prepare the SOAP Request Body (XML)
  • Create the SOAP envelope (the wrapper XML with <Envelope>, <Header>, and <Body> tags).
  • Add the operation and required parameters inside <Body>.
3. Send the request with Rest Assured
  • Use an HTTP method (usually POST) to send the SOAP envelope as the request body.
  • Set the appropriate headers (like Content-Type: text/xml or application/soap+xml).
4. Receive and parse the SOAP response
  • The server returns a SOAP response envelope in XML.
  • Extract values using XMLPath (similar to JSONPath but for XML).
5. Assertions/Validation
  • Verify status code (e.g., 200 OK).
  • Check that the SOAP response contains expected elements and values.










Key Concepts:

  • SOAP (Simple Object Access Protocol) is a protocol for exchanging structured XML data.

  • WSDL (Web Services Description Language) is used to describe SOAP services.

  • SOAP API is generally tested using POST, but for some services (like fetching WSDL), GET is used.


Example SOAP GET Use Case:

Fetch the WSDL file or perform a test GET to an endpoint.

Let’s use this public SOAP service for currency conversion WSDL (GET example):
http://www.dneonline.com/calculator.asmx?WSDL

This WSDL can be fetched using a GET request.











Step-by-step: Testing SOAP GET using Rest Assured:


Maven Dependency:

<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>rest-assured</artifactId>
    <version>5.3.1</version>
    <scope>test</scope>
</dependency>



Java code:

import io.restassured.RestAssured;
import io.restassured.response.Response;

public class SoapGetTest {
    public static void main(String[] args) {
        // Base URI for the SOAP service
        String url = "http://www.dneonline.com/calculator.asmx?WSDL";

        // Send GET request
        Response response = RestAssured
                .given()
                .when()
                .get(url)
                .then()
                .extract()
                .response();

        // Print status code and response
        System.out.println("Status Code: " + response.getStatusCode());
        System.out.println("Content-Type: " + response.getContentType());
        System.out.println("Response Body:\n" + response.getBody().asString());
    }
}


Code explanation:

  • Set the base URI
  • Send GET request
  • Print status code and response on console


We can assert response also by below code.

Optional: Add Test Assertion

import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;

public class SoapGetTest {
    public static void main(String[] args) {
        given()
        .when()
            .get("http://www.dneonline.com/calculator.asmx?WSDL")
        .then()
            .statusCode(200)
            .contentType("text/xml; charset=utf-8")
            .body(containsString("definitions"));
    }
}


Suggested Posts:

1. Validate Keys of API in RestAssured
2. Test Form Authentication in RestAssured
3. Test DELETE API in RestAssured
4. First RestAssured Code to Test API
5. Validate API Response from Database in RestAssured