How to test Graph QL API in Rest Assured

 



What is GraphQL APIs?

GraphQL is an open-source query language for APIs and a server-side runtime for executing those queries. It's essentially a protocol that dictates how a client (like a mobile app or website) can request data from a server, providing a more efficient and flexible alternative to traditional API designs like REST.


Core Theory and Concepts

GraphQL is built around a few key theoretical concepts:


1. Schema and Type System

A GraphQL Schema is the central component and acts as a contract between the client and the server. It uses a Strongly-Typed system to precisely define all the data that a client can request.

  • Types: The schema defines the structure of data in terms of Object Types, which are named collections of fields. For example, a User type might have name, email, and posts fields.
  • Fields: These are the units of data that can be requested on a type. Each field has a defined data type (like String, Int, or another custom Object Type). The presence of these types allows for validation of a query before execution and ensures predictable responses.


2. Client-Specified Requests

This is the most significant departure from traditional APIs. In GraphQL, the client declares exactly what data it needs in a single request.
  • Queries: These are used to fetch data. A client sends a query that mirrors the structure of the data it expects to receive. The server then returns a response that contains only the requested fields, which solves the problem of over-fetching (getting more data than you need) common in fixed-endpoint APIs.
  • Mutations: These are used to modify data (create, update, or delete). Like queries, they specify the data that should be changed and the desired data to be returned after the change is complete.
  • Subscriptions: These enable real-time data streams, allowing a client to subscribe to a specific event and receive updates from the server whenever that data changes.

3. Single Endpoint

Unlike a traditional REST API, which may expose many different endpoints (URLs) for different resources (e.g., /users, /posts/123), a GraphQL API typically exposes only a single endpoint. All data fetching and modification requests are sent to this one URL, with the specific operation (query or mutation) and the requested data shape defined in the request body.


4. Resolvers

While the schema defines what data can be fetched, Resolvers define how to actually retrieve that data for each field in the schema.
  • A resolver is a function associated with a specific field on a type.
  • When a client sends a query, the GraphQL server executes the relevant resolver functions for all the requested fields.
  • Resolvers act as the bridge between the GraphQL layer and the underlying data sources (like databases, microservices, or even other REST APIs). They hide the complexity of the back-end from the client, meaning the client only sees a unified "graph" of data.

Key Benefits
  • Efficiency: Clients only get the data they ask for, minimizing data transfer, which is especially beneficial for mobile applications and limited bandwidth.
  • Flexibility: The client controls the data requirements, allowing for rapid front-end changes without requiring the back-end to change fixed endpoints.
  • API Evolution: New fields can be added to the schema without affecting existing clients, allowing the API to evolve without needing disruptive versioning (like v1, v2).

To validate a GraphQL API using Rest Assured in Java, follow these key steps:















Public GraphQL API for Example

We'll use the public GraphQL API from https://countries.trevorblades.com/

Endpointhttps://countries.trevorblades.com/








Example Query (returns name and capital of India):


{
  country(code: "IN") {
    name
    capital
  }
}




Java Code Using Rest Assured

import io.restassured.RestAssured;
import io.restassured.response.Response;
import org.json.JSONObject;

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;

public class GraphQLApiTest {

    public static void main(String[] args) {

        // GraphQL query as string
        String query = "{ country(code: \"IN\") { name capital } }";

        // Prepare the JSON body
        JSONObject requestBody = new JSONObject();
        requestBody.put("query", query);

        // Set base URI
        RestAssured.baseURI = "https://countries.trevorblades.com/";

        // Send POST request and validate response
        given()
            .header("Content-Type", "application/json")
            .body(requestBody.toString())
        .when()
            .post()
        .then()
            .statusCode(200)
            .body("data.country.name", equalTo("India"))
            .body("data.country.capital", equalTo("New Delhi"));
    }
}



Code explanation: 

(a) Define Graph ql query in string form
(b) Define json body by using JSONObject class
(c) Define base URI
(d) Set POST request
(e) Get response and validate response.


Validations Performed

  • HTTP status code = 200

  • Country name = "India"

  • Capital = "New Delhi"



Maven Dependencies:

<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>rest-assured</artifactId>
    <version>5.3.0</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20210307</version>
</dependency>


Suggested Posts:

1. Test Basic Authentication of API in RestAssured
2. Validate Request and Response by POJO in RestAssured
3. Extract Response by JSONPath in RestAssured
4. Validate Keys in API in RestAssured
5. How to Test SOAP API in RestAssured

How to validate Request and Response by using POJO in Rest Assured

 



What is Request Validation?

  • Request Validation means verifying that the data you are sending to the API in the request (body, headers, parameters) is correct, structured properly, and matches the expected API contract.
  • Example: If an API expects a User object with fields {id, name, email}, your request body should have exactly these fields, with valid values.


When using POJO:
  • You first create a Java POJO class (Plain Old Java Object) with fields like id, name, email.
  • You create an object of this POJO and send it as a request body.
  • Since the POJO defines structure and types, it automatically validates that the request matches the expected schema before sending.

When using POJO:
  • You can map the API response directly into a POJO object.
  • Then validate fields using assertions.
  • If the API response is missing a field or has the wrong type, the mapping will fail or the assertions won’t match — this helps you ensure the response contract is correct.

What is Response Validation?
  • Response Validation means verifying that the API response you get back has the correct structure, keys, and values as per the expected contract.
  • Example: If the response should return a User object {id, name, email}, you validate whether the API actually returned all these fields with correct types and expected values.

How to Validate Request & Response using POJO in Rest Assured

1. Define POJO Classes
  • Create Java classes representing request and response objects.
  • Each class has private fields, constructors, getters, and setters.

2. Request Validation
  • Create an object of the Request POJO.
  • Populate it with required values.
  • Pass it to the Rest Assured request body.
  • The POJO ensures the structure of the request matches what the API expects.

3. Send Request
  • Rest Assured converts the POJO into JSON and sends it to the API.

4. Response Validation
  • Deserialize the API response back into the Response POJO.
  • Validate fields by comparing actual values against expected ones.
  • If a key is missing or data type mismatches, deserialization or assertion will fail.

Here’s how you can create a POJO classsend a POST request to https://reqres.in/api/users, and validate the response and status code using Rest Assured in Java.









1. POJO Class for Request

Below is POJO class of API request, having two attributes that are name and job. In POJO class below, we have parameterized constructor of the class and respective getter and setter methods for the attributes.

public class User {
    private String name;
    private String job;

    public User() {}

    public User(String name, String job) {
        this.name = name;
        this.job = job;
    }

    // Getters and Setters
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getJob() {
        return job;
    }

    public void setJob(String job) {
        this.job = job;
    }
}



2. POJO Class for Response

Below is POJO class of API response, having four attributes that are name, job, id and createdAt. In POJO class below, we have respective getter and setter methods for the attributes.

public class UserResponse {
    private String name;
    private String job;
    private String id;
    private String createdAt;

    public UserResponse() {}

    // Getters and Setters
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getJob() {
        return job;
    }

    public void setJob(String job) {
        this.job = job;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(String createdAt) {
        this.createdAt = createdAt;
    }
}


 
3. Rest Assured Test Code

import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import static org.hamcrest.Matchers.*;
import static io.restassured.RestAssured.*;

public class PostUserTest {
    public static void main(String[] args) {
        // Base URI
        RestAssured.baseURI = "https://reqres.in/api";

        // Request Body
        User user = new User("Himanshu", "Engineer");

        // POST Request
        Response response = given()
                .contentType(ContentType.JSON)
                .body(user)
            .when()
                .post("/users")
            .then()
                .statusCode(201)
                .body("name", equalTo("Himanshu"))
                .body("job", equalTo("Engineer"))
                .extract().response();

        // Deserialize Response to POJO
        UserResponse userResp = response.as(UserResponse.class);

        // Print Response Fields
        System.out.println("ID: " + userResp.getId());
        System.out.println("Created At: " + userResp.getCreatedAt());
    }
}



Code explanation:

(a) Set base URI of the API.
(b) Create object of request POJO class User.java, by putting values  - Himanshu, Engineer in User constructor.
(c) Set POST request to the API
(d) De serialize response to the POJO class
(e) Print response fields on console.



Maven Dependencies

<dependencies>
    <dependency>
        <groupId>io.rest-assured</groupId>
        <artifactId>rest-assured</artifactId>
        <version>5.3.2</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.16.1</version>
    </dependency>
</dependencies>


Suggested Posts:

1. Test Basic Authentication of API in RestAssured
2. Validate JSON Schema in RestAssured
3. Extract Response by JSONPath in RestAssured
4. Validate Keys in API in RestAssured
5. How to Test SOAP API in RestAssured