Showing posts with label API Testing Best Practices. Show all posts
Showing posts with label API Testing Best Practices. Show all posts

How to validate Response by Matchers API in Rest Assured

  



How to Use Hamcrest Matchers in GET API via Rest Assured

Hamcrest is a framework for writing matcher objects, which allow 'match' rules to be defined declaratively. In Rest Assured, we use Hamcrest matchers to write expressive assertions for validating the API response.


We can use the Hamcrest Matchers API in a GET API test by employing the assertThat assertion within your testing framework (like JUnit or TestNG), where the actual value is an element extracted from the API's response body or headers, and the matcher defines the specific expectation.

The entire process follows three theoretical steps: Execute, Extract, and Assert.

You use the Hamcrest Matchers API in a GET API test by employing the assertThat assertion within your testing framework (like JUnit or TestNG), where the actual value is an element extracted from the API's response body or headers, and the matcher defines the specific expectation.

The entire process follows three theoretical steps: Execute, Extract, and Assert.


1. Execute the GET Request

First, your testing tool performs the GET request to the target API endpoint. The result of this execution is the API Response, which contains:
  • Status Line: The HTTP Status Code (example: 200 OK).
  • Headers: Metadata about the response (e.g., Content-Type, Date).
  • Body: The payload, usually in JSON or XML format.

2. Extract the Actual Value

This step involves parsing the response and pulling out the specific piece of data you want to validate.
  • Extraction from the Body: If the response body is JSON (which is common), you use a JSONPath or XPath expression (depending on the testing library, like REST Assured) to navigate the structure and isolate the required value.
Example: Extracting a product name from a nested JSON object.
  • Extraction from Headers: You extract a specific header value directly.
Example: Extracting the value of the Content-Type header.
  • Extraction of Status Code: You get the numeric HTTP status code.
This extracted data becomes the actual value (actual_value) for your Hamcrest assertion.


3. Assert with Hamcrest Matchers

The final step is the assertion, where the extracted value is verified against the expected condition using the Hamcrest syntax: assertThat(actual_value,matcher).











Maven Dependencies:

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

    <!-- Hamcrest -->
    <dependency>
        <groupId>org.hamcrest</groupId>
        <artifactId>hamcrest</artifactId>
        <version>2.2</version>
        <scope>test</scope>
    </dependency>
</dependencies>


Commonly Used Hamcrest Matchers

MatcherDescription
equalTo(value)Check equality
hasItem(value)Check if a list contains item
hasItems(val1, val2)Check if list contains multiple items
not(value)Asserts the opposite
containsString(str)Check substring match
startsWith(str)Check if string starts with



API to be tested:

https://reqres.in/api/users?page=2



API Response of above API











Java Code:

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

public class GetApiHamcrestExample {
    public static void main(String[] args) {

        // Set base URI
        RestAssured.baseURI = "https://reqres.in";

        // GET Request with Hamcrest matchers for assertions
        given()
            .log().all()
        .when()
            .get("/api/users?page=2")
        .then()
            .log().all()
            .statusCode(200)
            .body("page", equalTo(2))  // validate page number
            .body("data.id", hasItems(7, 8, 9))  // check if certain user IDs are present
            .body("data.first_name", hasItem("Michael"))  // check first_name list contains value
            .body("support.url", containsString("reqres.in"))  // substring match
            .body("data.email[0]", startsWith("michael"));  // starts with
    }
}



Code Explanation:

(a) Set the base URI
(b) Send the API request
(c) Get the API response nd log on console
(d) Validate API response by Matchers API methods like equalTo(), hasItems(), hasItem(), etc.



Output:

Got 200 server code response as shown below in the response. The validated data from Matcher's API is also mentioned below.

Request:
GET https://reqres.in/api/users?page=2

Response:
200 OK
...
Assertions:
page == 2
data.id contains 7, 8, 9
data.first_name contains "Michael"
support.url contains "reqres.in"
data.email[0] startsWith "michael"


Suggested Posts:

1. Test Basic Authentication in RestAssured
2. Test Preemptive Authentication in RestAssured
3. Test Form Authentication in RestAssured
4. Validate Keys in API in RestAssured
5. Validate XML Schema in RestAssured

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

How to Test a POST API by Rest Assured

 



What is a POST API?

  • A POST API is an HTTP endpoint that allows a client to send data to the server.
  • The data is usually sent in the request body in formats like JSON, XML, or form data.
  • Common uses of POST APIs:

Creating a new resource (e.g., creating a new user in a system).
Submitting forms (login, registration, etc.).
Sending files or data for processing.


How to Test a POST API in Rest Assured

When testing a POST API in Rest Assured, you typically perform these steps:

1. Set the Base URI
  • Define the API host (e.g., https://reqres.in).
2. Define the Request Body
  • Prepare the JSON (or other format) data that you want to send.
3. Send the POST Request
  • Use Rest Assured to send the request to the endpoint (e.g., /api/users).
4. Validate Response Status Code
  • Check if the response code is correct (usually 201 Created for a successful POST).
5. Verify Response Body
  • Ensure the response contains the expected data (like the new id or confirmation message).
6. Check Response Headers (Optional)
  • Validate Content-Type, Location, etc., to ensure proper response formatting.


To test a POST API using Rest Assured with a JSONObject in Java, follow these steps:










Step-by-Step Implementation

1. Add Rest Assured Dependency

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

    <!-- JSON Library -->
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20230618</version>
    </dependency>
</dependencies>


API to be tested: 

POST https://reqres.in/api/users


















Sample request body:

{
  "name": "Himanshu",
  "job": "QA Engineer"
}



Expected response (201 Created):

{
  "name": "Himanshu",
  "job": "QA Engineer",
  "id": "123",
  "createdAt": "2025-07-28T..."
}



3. Java Code to Test POST API using JSONObject

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

public class PostAPITest {

    public static void main(String[] args) {

        // Step 1: Set Base URI
        RestAssured.baseURI = "https://reqres.in/api";

        // Step 2: Create Request Payload using JSONObject
        JSONObject requestBody = new JSONObject();
        requestBody.put("name", "Himanshu");
        requestBody.put("job", "QA Engineer");

        // Step 3: Make POST Request
        Response response = RestAssured
            .given()
                .contentType(ContentType.JSON)
                .body(requestBody.toString())
                .log().all()
            .when()
                .post("/users")
            .then()
                .log().all()
                .statusCode(201)
                .extract().response();

        // Step 4: Print Response Fields
        System.out.println("ID: " + response.jsonPath().getString("id"));
        System.out.println("Created At: " + response.jsonPath().getString("createdAt"));
    }
}



Code Explanation:

LinePurpose
RestAssured.baseURISets the base URL.
JSONObjectBuilds the JSON body using key-value pairs.
given().contentType().body()Prepares the request with headers and body.
post("/users")Sends POST request to the endpoint.
statusCode(201)Verifies the response status.
response.jsonPath()Extracts values from JSON response.



Sample Output:

Request method:	POST
Request URI:	https://reqres.in/api/users
Request body:
{
    "name": "Himanshu",
    "job": "QA Engineer"
}
Response Status Code: 201
Response body:
{
    "name": "Himanshu",
    "job": "QA Engineer",
    "id": "867",
    "createdAt": "2025-07-28T14:30:55.098Z"
}


Suggested Posts:

1. Test Digest Auth by RestAssured
2. How to extract Response in Rest Assured by JSONPath
3. Test PUT API in RestAssured
4. Overview of RestAssured Framework
5. How to Test Basic Authentication in RestAssured