First Program - RestAssured


package tests;

import org.testng.Assert;
import org.testng.annotations.Test;

import static io.restassured.RestAssured.*;
import io.restassured.response.Response;
import static io.restassured.matcher.RestAssuredMatchers.*;
import static org.hamcrest.Matchers.*;

public class TestsExamples {

    @Test
    public void test_1() {

        Response response = get("https://reqres.in/api/users?page=2");

        System.out.println(response.getStatusCode());
        System.out.println(response.getTime());
        System.out.println(response.getBody().asString());
        System.out.println(response.getStatusLine());
        System.out.println(response.getHeader("content-type"));

        int statusCode = response.getStatusCode();

        Assert.assertEquals(statusCode, 200);

    }

    @Test
    public void test_2() {

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

        given().
            get("/users?page=2").
        then().
            statusCode(200).
            body("data[1].id", equalTo(8)).
            log().all();

    }

}

Let's understand a basic REST Assured test class that demonstrates two different ways of validating a REST API response using TestNG.


Package Declaration

package tests;

This line specifies that the class belongs to the tests package. Organizing test classes into packages improves project structure and maintainability.


Import Statements

import org.testng.Assert;
import org.testng.annotations.Test;

These imports are from TestNG:

  • @Test marks a method as a test case.
  • Assert is used to validate expected results.
import static io.restassured.RestAssured.*;

Imports all the commonly used REST Assured methods such as:

  • given()
  • get()
  • baseURI

This allows us to use these methods directly without prefixing them with RestAssured..

import io.restassured.response.Response;

The Response class stores the complete HTTP response returned by the API, including:

  • Status Code
  • Headers
  • Response Body
  • Response Time
  • Cookies
import static org.hamcrest.Matchers.*;

Imports Hamcrest matchers such as:

  • equalTo()
  • containsString()
  • hasSize()

These are commonly used for validating JSON responses.


Test Method 1

@Test
public void test_1()

This tells TestNG that test_1() is an executable test case.


Sending a GET Request

Response response = get("https://reqres.in/api/users?page=2");

This sends a GET request to the API endpoint.

The returned response is stored in the response object, which can be used to retrieve various response details.


Printing the Status Code

System.out.println(response.getStatusCode());

Example Output:

200

A status code of 200 indicates that the request was processed successfully.


Printing the Response Time

System.out.println(response.getTime());

Example Output:

310 ms

Response time helps measure the API's performance.


Printing the Response Body

System.out.println(response.getBody().asString());

This prints the complete JSON response received from the server.

Example:

{
   "page":2,
   "data":[
      {
         "id":7,
         "email":"..."
      }
   ]
}

This is useful for debugging and understanding the API response structure.


Printing the Status Line

System.out.println(response.getStatusLine());

Example Output:

HTTP/1.1 200 OK

The status line contains:

  • HTTP Version
  • Status Code
  • Status Message

Printing a Header

System.out.println(response.getHeader("content-type"));

Example Output:

application/json; charset=utf-8

Headers provide metadata about the response, such as content type, caching information, and server details.


Validating the Status Code

int statusCode = response.getStatusCode();

Assert.assertEquals(statusCode, 200);

This assertion verifies that the API returned the expected HTTP status code.

If the expected value is 200, the test passes. Otherwise, TestNG marks the test as failed.


Test Method 2

The second test demonstrates the BDD (Behavior-Driven Development) style supported by REST Assured.

@Test
public void test_2()

Setting the Base URI

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

Instead of repeating the complete URL in every request, we define a common base URI.

This makes the code cleaner and easier to maintain.


Understanding the BDD Syntax

given().
    get("/users?page=2").
then().

REST Assured follows the Given–When–Then pattern.

given()

Represents the request setup.

This is where you would normally specify:

  • Headers
  • Authentication
  • Query Parameters
  • Path Parameters
  • Request Body

In this example, no additional request configuration is required.


get()

get("/users?page=2")

Sends the HTTP GET request to:

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

then()

Represents the response validation section.

This is where we verify that the API behaves as expected.


Validating the Status Code

statusCode(200)

Checks that the server returned HTTP Status Code 200 (OK).


Validating JSON Response

body("data[1].id", equalTo(8))

Let's break this down.

Suppose the API response is:

"data": [
  {
    "id": 7
  },
  {
    "id": 8
  }
]

Here:

  • data is a JSON array.
  • data[1] refers to the second object in the array (arrays use zero-based indexing).
  • .id accesses the id field of that object.

The assertion verifies that the second user's ID is 8.


Logging the Response

log().all();

This prints the complete request and response details to the console, including:

  • Request URL
  • Headers
  • Status Code
  • Response Body

Logging is extremely useful for debugging failed API tests.


Difference Between test_1() and test_2()

test_1()test_2()
Uses the Response object to manually retrieve response details.Uses REST Assured's BDD syntax for fluent validation.
Assertions are written using TestNG.Assertions are written directly using REST Assured and Hamcrest matchers.
More suitable when response values need to be reused later in the test.More concise and readable for straightforward API validations.

Key REST Assured Concepts Covered

This example introduces several fundamental REST Assured concepts:

  • Sending a GET request
  • Capturing the API response
  • Reading the status code
  • Measuring response time
  • Printing the response body
  • Reading response headers
  • Validating HTTP status codes
  • Validating JSON response fields
  • Using Hamcrest matchers
  • Writing tests with TestNG
  • Using the BDD (given(), when(), then()) style
  • Logging request and response details

Conclusion

This example is an excellent starting point for learning REST Assured. The first test demonstrates how to capture and inspect an API response using the Response object, while the second test introduces REST Assured's fluent BDD syntax for concise and readable assertions.

As you advance, you can extend these concepts to perform more complex API testing scenarios, such as sending POST, PUT, and DELETE requests, validating response headers, extracting values from JSON responses, handling authentication, and building reusable API test frameworks.