Monday, November 30, 2026

Rest Assured API Testing – Complete Java Guide with Examples

Rest Assured API Testing – Complete Java Guide with Examples and Output

Rest Assured is a Java library used to automate REST API testing. It allows testers to send HTTP requests such as GET, POST, PUT, PATCH and DELETE, validate API responses, verify JSON/XML data, perform authentication, and integrate API tests with TestNG, JUnit, Maven and CI/CD pipelines.

This guide covers Rest Assured from beginner to advanced level with practical examples, code, and expected outputs.

Rest Assured API Testing – Complete Java Guide with Examples and Output


1. What is Rest Assured?

Rest Assured is a Java-based library for REST API automation testing.

BDD-style syntax: given() – when() – then()

Example

given()
    .baseUri("https://reqres.in")
.when()
    .get("/api/users/2")
.then()
    .statusCode(200);

Why use Rest Assured?

  • Easy-to-understand BDD syntax.
  • Supports GET, POST, PUT, PATCH and DELETE.
  • JSON and XML response validation.
  • Authentication and authorization.
  • JSONPath and XMLPath support.
  • Request and response logging.
  • Schema validation.
  • API request chaining.
  • Integration with TestNG, JUnit and Maven.
  • Supports API mocking and CI/CD execution.

2. Rest Assured Architecture

Execution Flow

  1. Java automation script prepares an API request.
  2. Rest Assured sends the HTTP request.
  3. API server processes the request.
  4. Server returns an HTTP response.
  5. Rest Assured validates status code, headers and response body.
  6. TestNG/JUnit reports PASS or FAIL.

3. HTTP Methods in Rest Assured

Method Purpose Example
GETRetrieve dataGet user
POSTCreate dataCreate user
PUTReplace/update dataUpdate user
PATCHPartially update dataUpdate user name
DELETEDelete dataDelete user
HEADRetrieve response headersCheck resource
OPTIONSCheck supported methodsAPI capabilities

4. Maven Project Setup

Create a Maven project in IntelliJ IDEA or Eclipse.

Project Structure

RestAssuredProject
│
├── pom.xml
│
└── src
    └── test
        └── java
            ├── tests
            │   ├── GetUserTest.java
            │   ├── PostUserTest.java
            │   ├── PutUserTest.java
            │   └── DeleteUserTest.java
            │
            └── utils
                └── TestData.java

Add Dependencies in pom.xml

<dependencies>

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

    <!-- TestNG -->
    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>7.11.0</version>
        <scope>test</scope>
    </dependency>

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

</dependencies>

After adding dependencies, reload Maven.

5. Understanding given(), when(), then()

Rest Assured follows a BDD-style structure.

Keyword Description
given()Prepare request specification
when()Send HTTP request
then()Validate response

Example

import static io.restassured.RestAssured.*;

public class GetUserTest {

    public static void main(String[] args) {

        given()
            .baseUri("https://reqres.in")

        .when()
            .get("/api/users/2")

        .then()
            .statusCode(200)
            .log().all();
    }
}

Expected Response (Illustrative)

{
  "data": {
    "id": 2,
    "email": "janet.weaver@reqres.in",
    "first_name": "Janet",
    "last_name": "Weaver"
  }
}

Expected result: PASS

Status code: 200 OK.

Note: Public demo APIs may require an API key or change their response data. Treat this as a response example, not a guarantee of live data.

6. GET Request – Retrieve User Details

GET is used to retrieve information from an API.

Example

import static io.restassured.RestAssured.*;

import org.testng.annotations.Test;

public class GetUserTest {

    @Test
    public void getUser() {

        given()
            .baseUri("https://reqres.in")
            .header("x-api-key", "reqres-free-v1")

        .when()
            .get("/api/users/2")

        .then()
            .statusCode(200)
            .log().all();
    }
}

Expected Output

{
  "data": {
    "id": 2,
    "email": "janet.weaver@reqres.in",
    "first_name": "Janet",
    "last_name": "Weaver"
  }
}

TestNG Console

PASSED: getUser

================================
Tests run: 1
Passed: 1
Failed: 0
================================

7. POST Request – Create a New User

POST is used to create a new resource.

Example

import static io.restassured.RestAssured.*;

import org.testng.annotations.Test;

public class PostUserTest {

    @Test
    public void createUser() {

        String requestBody = """
        {
            "name": "Sumit",
            "job": "Automation Tester"
        }
        """;

        given()
            .baseUri("https://reqres.in")
            .header("x-api-key", "reqres-free-v1")
            .contentType("application/json")
            .body(requestBody)

        .when()
            .post("/api/users")

        .then()
            .statusCode(201)
            .body("name", org.hamcrest.Matchers.equalTo("Sumit"))
            .body("job", org.hamcrest.Matchers.equalTo("Automation Tester"))
            .log().all();
    }
}

Expected Output

{
    "name": "Sumit",
    "job": "Automation Tester",
    "id": "123",
    "createdAt": "2026-11-30T..."
}

Expected result: PASS

A successful POST request generally returns HTTP 201 Created.

8. PUT Request – Update Complete Resource

PUT is used to replace or update a resource.

@Test
public void updateUser() {

    String requestBody = """
    {
        "name": "Sumit Kumar",
        "job": "Senior QA Automation Engineer"
    }
    """;

    given()
        .baseUri("https://reqres.in")
        .header("x-api-key", "reqres-free-v1")
        .contentType("application/json")
        .body(requestBody)

    .when()
        .put("/api/users/2")

    .then()
        .statusCode(200)
        .body("name",
            org.hamcrest.Matchers.equalTo("Sumit Kumar"))
        .log().all();
}

Expected Response

{
    "name": "Sumit Kumar",
    "job": "Senior QA Automation Engineer",
    "updatedAt": "2026-11-30T..."
}

9. PATCH Request – Partial Resource Update

PATCH is used when you want to update only selected fields.

@Test
public void patchUser() {

    String requestBody = """
    {
        "job": "QA Lead"
    }
    """;

    given()
        .baseUri("https://reqres.in")
        .header("x-api-key", "reqres-free-v1")
        .contentType("application/json")
        .body(requestBody)

    .when()
        .patch("/api/users/2")

    .then()
        .statusCode(200)
        .body("job",
            org.hamcrest.Matchers.equalTo("QA Lead"))
        .log().all();
}

Expected Response

{
    "job": "QA Lead",
    "updatedAt": "2026-11-30T..."
}

10. DELETE Request – Delete a Resource

DELETE is used to delete an existing resource.

@Test
public void deleteUser() {

    given()
        .baseUri("https://reqres.in")
        .header("x-api-key", "reqres-free-v1")

    .when()
        .delete("/api/users/2")

    .then()
        .statusCode(204)
        .log().all();
}

Expected Output

HTTP/1.1 204 No Content

Test Status: PASS

A 204 response normally has no response body.

11. Request Parameters in Rest Assured

There are two commonly used types of request parameters.

A. Query Parameter

Query parameters are passed in the URL after ?.

Example URL

https://example.com/api/users?page=2

Java Code

given()
    .baseUri("https://example.com")
    .queryParam("page", 2)

.when()
    .get("/api/users")

.then()
    .statusCode(200)
    .log().all();

B. Path Parameter

Path parameters are part of the URL path.

Example URL

https://example.com/api/users/10

Java Code

given()
    .baseUri("https://example.com")
    .pathParam("id", 10)

.when()
    .get("/api/users/{id}")

.then()
    .statusCode(200)
    .log().all();

Difference Between queryParam() and pathParam()

queryParam() pathParam()
Filters or searches resourcesIdentifies a resource
Usually follows ?Appears in URL path
?page=2/users/10
Multiple query parameters use &Values replace path placeholders

12. Request Headers Validation

Headers provide additional information about an API request.

Common Headers

Header Purpose
Content-TypeRequest body format
AcceptExpected response format
AuthorizationAuthentication
User-AgentClient information
x-api-keyAPI key

Example

given()
    .baseUri("https://example.com")
    .header("Content-Type", "application/json")
    .header("Accept", "application/json")
    .header("Authorization", "Bearer token123")

.when()
    .get("/api/users")

.then()
    .statusCode(200);

Multiple Headers

given()
    .headers(
        "Content-Type", "application/json",
        "Accept", "application/json"
    )
.when()
    .get("/api/users")
.then()
    .statusCode(200);

13. Response Validation Using then()

This is one of the most important topics in Rest Assured interviews.

You can validate:

  • Status code
  • Response body
  • Response headers
  • Response time
  • Content type
  • JSON values
  • XML values

A. Validate Status Code

given()
    .baseUri("https://reqres.in")
    .header("x-api-key", "reqres-free-v1")

.when()
    .get("/api/users/2")

.then()
    .statusCode(200);

B. Validate Response Body

given()
    .baseUri("https://reqres.in")
    .header("x-api-key", "reqres-free-v1")

.when()
    .get("/api/users/2")

.then()
    .body("data.id",
        org.hamcrest.Matchers.equalTo(2))
    .body("data.first_name",
        org.hamcrest.Matchers.equalTo("Janet"))
    .body("data.last_name",
        org.hamcrest.Matchers.equalTo("Weaver"));

C. Validate Response Header

given()
    .baseUri("https://reqres.in")
    .header("x-api-key", "reqres-free-v1")

.when()
    .get("/api/users/2")

.then()
    .statusCode(200)
    .header("Content-Type",
        org.hamcrest.Matchers.containsString("application/json"));

D. Validate Response Time

given()
    .baseUri("https://reqres.in")
    .header("x-api-key", "reqres-free-v1")

.when()
    .get("/api/users/2")

.then()
    .statusCode(200)
    .time(
        org.hamcrest.Matchers.lessThan(5000L)
    );

5000L means 5000 milliseconds. This is a basic response-time assertion, not a complete performance test.

E. Validate Content Type

given()
.when()
    .get("https://reqres.in/api/users/2")
.then()
    .contentType("application/json");

14. JSONPath in Rest Assured

JSONPath is used to extract values from JSON responses.

Example JSON

{
    "id": 101,
    "name": "Sumit",
    "job": "QA Automation",
    "address": {
        "city": "Bangalore",
        "country": "India"
    }
}

Extract Individual Values

Response response =
    given()
        .baseUri("https://example.com")

    .when()
        .get("/api/users/101");

int id = response.jsonPath().getInt("id");

String name = response.jsonPath().getString("name");

String job = response.jsonPath().getString("job");

String city = response.jsonPath().getString("address.city");

System.out.println(id);
System.out.println(name);
System.out.println(job);
System.out.println(city);

Output

101
Sumit
QA Automation
Bangalore

JSONPath Commonly Used Methods

Method Purpose
getInt()Extract integer
getString()Extract string
getBoolean()Extract boolean
getList()Extract list
getMap()Extract map
get()Extract generic value

Extract Array Values

{
    "employees": [
        {"id": 1, "name": "Sumit"},
        {"id": 2, "name": "Rahul"},
        {"id": 3, "name": "Amit"}
    ]
}

Java Code

Response response =
    given()
        .get("https://example.com/api/employees");

List<String> names =
    response.jsonPath().getList("employees.name");

System.out.println(names);

Output

[Sumit, Rahul, Amit]

Find a Specific Value from an Array

String employeeName = response.jsonPath()
    .getString("employees.find { it.id == 2 }.name");

System.out.println(employeeName);

Output:

Rahul

15. XMLPath in Rest Assured

XMLPath is used to extract values from XML responses.

Example XML

<employees>
    <employee>
        <id>101</id>
        <name>Sumit</name>
        <salary>50000</salary>
    </employee>
    <employee>
        <id>102</id>
        <name>Rahul</name>
        <salary>60000</salary>
    </employee>
</employees>

Java Code

import io.restassured.path.xml.XmlPath;

String xmlResponse = """
<employees>
    <employee>
        <id>101</id>
        <name>Sumit</name>
        <salary>50000</salary>
    </employee>
    <employee>
        <id>102</id>
        <name>Rahul</name>
        <salary>60000</salary>
    </employee>
</employees>
""";

XmlPath xmlPath = new XmlPath(xmlResponse);

String name = xmlPath.getString(
    "employees.employee[0].name"
);

String salary = xmlPath.getString(
    "employees.employee[1].salary"
);

System.out.println(name);
System.out.println(salary);

Output

Sumit
60000

Extract All Employee Names

List<String> names = xmlPath.getList(
    "employees.employee.name"
);

System.out.println(names);

Output:

[Sumit, Rahul]

16. Response Extraction Using extract()

You can extract the entire API response or selected response information.

Response response =

    given()
        .baseUri("https://reqres.in")
        .header("x-api-key", "reqres-free-v1")

    .when()
        .get("/api/users/2")

    .then()
        .statusCode(200)
        .extract()
        .response();

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

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

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

Output

200
application/json

{
  "data": {
    "id": 2,
    "first_name": "Janet"
  }
}

Extract Response Value Directly

String firstName =

    given()
        .baseUri("https://reqres.in")
        .header("x-api-key", "reqres-free-v1")

    .when()
        .get("/api/users/2")

    .then()
        .statusCode(200)
        .extract()
        .path("data.first_name");

System.out.println(firstName);

Output:

Janet

17. Authentication in Rest Assured

Authentication is used to verify the identity of an API consumer.

Rest Assured supports multiple authentication mechanisms.

A. Basic Authentication

given()
    .auth()
    .basic("username", "password")

.when()
    .get("https://example.com/api/users")

.then()
    .statusCode(200);

B. Preemptive Basic Authentication

Sends credentials before receiving an authentication challenge.

given()
    .auth()
    .preemptive()
    .basic("username", "password")

.when()
    .get("https://example.com/api/users")

.then()
    .statusCode(200);

C. Bearer Token Authentication

Commonly used with OAuth 2.0 and JWT tokens.

String token = "your_access_token";

given()
    .header("Authorization", "Bearer " + token)

.when()
    .get("https://example.com/api/users")

.then()
    .statusCode(200);

D. OAuth 2.0

given()
    .auth()
    .oauth2("your_access_token")

.when()
    .get("https://example.com/api/users")

.then()
    .statusCode(200);

E. API Key Authentication

given()
    .queryParam("api_key", "your_api_key")

.when()
    .get("https://example.com/api/users")

.then()
    .statusCode(200);

The API key can also be passed in a header if that is what the API contract requires.

18. Serialization and Deserialization

Serialization converts a Java object into JSON.

Deserialization converts JSON into a Java object.

A. Serialization – Java Object to JSON

Create a POJO class:

public class User {

    private String name;
    private String job;

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

    public String getName() {
        return name;
    }

    public String getJob() {
        return job;
    }
}

Send the Object

User user = new User(
    "Sumit",
    "Automation Tester"
);

given()
    .contentType("application/json")
    .body(user)

.when()
    .post("https://example.com/api/users")

.then()
    .statusCode(201)
    .log().body();

Expected Request JSON

{
    "name": "Sumit",
    "job": "Automation Tester"
}

B. Deserialization – JSON to Java Object

UserResponse response =

    given()
        .get("https://example.com/api/users/101")

    .then()
        .statusCode(200)
        .extract()
        .as(UserResponse.class);

A corresponding UserResponse POJO must have fields and compatible getters/setters matching the response structure.

19. Logging in Rest Assured

Logging helps debug API requests and responses.

Log All Request Details

given()
    .log().all()

.when()
    .get("https://example.com/api/users")

.then()
    .log().all();

Log Only Request Headers

given()
    .log().headers()

.when()
    .get("https://example.com/api/users");

Log Only Response Body

given()

.when()
    .get("https://example.com/api/users")

.then()
    .log().body();

Log Only When Validation Fails

given()

.when()
    .get("https://example.com/api/users")

.then()
    .log().ifValidationFails()
    .statusCode(200);

This is useful in CI/CD pipelines because it avoids excessive logs for successful requests.

20. RequestSpecification and ResponseSpecification

These specifications help avoid duplicate code across multiple test cases.

RequestSpecification

import io.restassured.builder.RequestSpecBuilder;
import io.restassured.specification.RequestSpecification;

RequestSpecification requestSpec =
    new RequestSpecBuilder()
        .setBaseUri("https://reqres.in")
        .addHeader("x-api-key", "reqres-free-v1")
        .setContentType("application/json")
        .build();

Usage

given()
    .spec(requestSpec)

.when()
    .get("/api/users/2")

.then()
    .statusCode(200);

ResponseSpecification

import io.restassured.builder.ResponseSpecBuilder;
import io.restassured.specification.ResponseSpecification;

ResponseSpecification responseSpec =
    new ResponseSpecBuilder()
        .expectStatusCode(200)
        .expectContentType("application/json")
        .build();

Usage

given()
    .spec(requestSpec)

.when()
    .get("/api/users/2")

.then()
    .spec(responseSpec);

Advantages

  • Reusable base URL.
  • Centralized headers.
  • Common authentication.
  • Reusable status-code validation.
  • Cleaner test scripts.

21. JSON Schema Validation

JSON Schema validation checks whether the API response follows the expected JSON structure and data types.

Add the json-schema-validator dependency from the Maven setup.

Create a File

src/test/resources/user-schema.json

{
  "type": "object",
  "properties": {
    "data": {
      "type": "object",
      "properties": {
        "id": {
          "type": "integer"
        },
        "email": {
          "type": "string"
        },
        "first_name": {
          "type": "string"
        }
      },
      "required": [
        "id",
        "email",
        "first_name"
      ]
    }
  },
  "required": ["data"]
}

Java Code

import static io.restassured.RestAssured.*;
import static io.restassured.module.jsv.JsonSchemaValidator.*;

@Test
public void validateJsonSchema() {

    given()
        .baseUri("https://reqres.in")
        .header("x-api-key", "reqres-free-v1")

    .when()
        .get("/api/users/2")

    .then()
        .statusCode(200)
        .body(matchesJsonSchemaInClasspath("user-schema.json"));
}

Expected Output

JSON Schema Validation: PASS
Status Code: 200
Test Status: PASSED

22. Data-Driven Testing Using TestNG DataProvider

Data-driven testing executes the same API test with multiple sets of test data.

Example: Verify multiple user IDs.

import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import static io.restassured.RestAssured.*;

public class DataDrivenApiTest {

    @DataProvider(name = "userData")
    public Object[][] userData() {

        return new Object[][] {
            {2, "Janet"},
            {3, "Emma"},
            {4, "Eve"}
        };
    }

    @Test(dataProvider = "userData")
    public void verifyUser(int id, String expectedName) {

        given()
            .baseUri("https://reqres.in")
            .header("x-api-key", "reqres-free-v1")
            .pathParam("id", id)

        .when()
            .get("/api/users/{id}")

        .then()
            .statusCode(200)
            .body(
                "data.first_name",
                org.hamcrest.Matchers.equalTo(expectedName)
            );
    }
}

Expected Output

PASSED: verifyUser(2, "Janet")
PASSED: verifyUser(3, "Emma")
PASSED: verifyUser(4, "Eve")

Tests run: 3
Passed: 3
Failed: 0

The expected names are illustrative test data; always confirm them against the current API response.

23. API Chaining – Pass Response from One API to Another

API chaining is an important real-time automation scenario.

  1. Create a user.
  2. Extract the generated user ID.
  3. Pass the ID into the GET request.
  4. Validate the user details.

Java Example

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

@Test
public void apiChaining() {

    // Step 1: Create user

    Response postResponse =

        given()
            .baseUri("https://reqres.in")
            .header("x-api-key", "reqres-free-v1")
            .contentType("application/json")
            .body("""
                {
                    "name": "Sumit",
                    "job": "QA Engineer"
                }
            """)

        .when()
            .post("/api/users")

        .then()
            .statusCode(201)
            .extract()
            .response();

    // Step 2: Extract generated ID

    String userId = postResponse.jsonPath().getString("id");

    System.out.println("Created User ID: " + userId);

    // Step 3: Pass ID to another API

    given()
        .baseUri("https://reqres.in")
        .header("x-api-key", "reqres-free-v1")
        .pathParam("id", userId)

    .when()
        .get("/api/users/{id}")

    .then()
        .log().all();
}

Important: ReqRes simulates creation and does not necessarily persist newly created users for subsequent GET requests. For a genuine end-to-end chaining test, use an API that persists created records.

24. Cookies Handling

Cookies are often used for session management.

Get Cookies

Response response =
    given()
        .get("https://example.com/api/users");

Map<String, String> cookies = response.getCookies();

System.out.println(cookies);

Send Cookies

given()
    .cookie("sessionId", "abc123")

.when()
    .get("https://example.com/api/profile")

.then()
    .statusCode(200);

Send Multiple Cookies

given()
    .cookies(
        "sessionId", "abc123",
        "userType", "admin"
    )

.when()
    .get("https://example.com/api/profile")

.then()
    .statusCode(200);

25. File Upload Using Rest Assured

Rest Assured supports multipart file uploads.

import java.io.File;

@Test
public void uploadFile() {

    File file = new File("src/test/resources/sample.pdf");

    given()
        .multiPart("file", file)
        .accept("application/json")

    .when()
        .post("https://example.com/api/upload")

    .then()
        .statusCode(200)
        .log().all();
}

Expected Response (Example)

{
    "message": "File uploaded successfully",
    "fileName": "sample.pdf"
}

The API must support multipart uploads, and the multipart field name must match its contract.

26. File Download Using Rest Assured

You can retrieve binary data from an API response.

import java.io.FileOutputStream;
import io.restassured.response.Response;

@Test
public void downloadFile() throws Exception {

    Response response =
        given()
            .get("https://example.com/files/sample.pdf");

    byte[] fileData = response.asByteArray();

    try (FileOutputStream output =
            new FileOutputStream("downloaded.pdf")) {

        output.write(fileData);
    }

    System.out.println("File downloaded successfully");
}

Expected Output

File downloaded successfully

In production tests, also validate the HTTP status, content type and downloaded file size.

27. Negative API Testing

Negative testing validates how an API behaves when invalid input or unauthorized access is provided.

Common Scenarios

Scenario Expected Status
Invalid endpoint404
Missing authentication401
Insufficient permissions403
Invalid request body400
Unsupported HTTP method405
Invalid media type415
Server error500

These are common conventions; the actual status codes depend on the API contract.

Example 1: Invalid User ID

@Test
public void invalidUser() {

    given()
        .baseUri("https://reqres.in")
        .header("x-api-key", "reqres-free-v1")

    .when()
        .get("/api/users/99999")

    .then()
        .statusCode(404);
}

Example 2: Missing Authentication

@Test
public void unauthorizedRequest() {

    given()
        .baseUri("https://example.com")

    .when()
        .get("/api/secure/users")

    .then()
        .statusCode(401);
}

Example 3: Invalid Request Body

@Test
public void invalidRequest() {

    String body = """
    {
        "name": "",
        "email": "invalid-email"
    }
    """;

    given()
        .baseUri("https://example.com")
        .contentType("application/json")
        .body(body)

    .when()
        .post("/api/users")

    .then()
        .statusCode(400)
        .log().all();
}

28. Hamcrest Matchers for API Assertions

Hamcrest provides reusable matchers for validating API responses.

import static org.hamcrest.Matchers.*;

Common Matchers

Matcher Purpose
equalTo()Exact equality
not()Negation
greaterThan()Greater than
lessThan()Less than
containsString()Contains text
hasItem()Contains an item
hasItems()Contains multiple items
notNullValue()Value is not null
is()Wraps another matcher
empty()Empty collection/string

Example

given()
    .baseUri("https://reqres.in")
    .header("x-api-key", "reqres-free-v1")

.when()
    .get("/api/users/2")

.then()
    .statusCode(200)
    .body("data.id", equalTo(2))
    .body("data.email", containsString("@"))
    .body("data.first_name", notNullValue());

29. Reusable API Framework Using TestNG

In real-time projects, we generally avoid writing the base URL, headers and common request configuration repeatedly.

Framework Structure

RestAssuredFramework
│
├── src/test/java
│   ├── base
│   │   └── BaseTest.java
│   │
│   ├── tests
│   │   ├── UserGetTest.java
│   │   ├── UserPostTest.java
│   │   └── UserDeleteTest.java
│   │
│   └── utils
│       └── ConfigReader.java
│
├── src/test/resources
│   └── config.properties
│
└── pom.xml

Step 1: config.properties

baseUrl=https://reqres.in
apiKey=reqres-free-v1

Step 2: BaseTest.java

import io.restassured.RestAssured;
import org.testng.annotations.BeforeClass;

public class BaseTest {

    @BeforeClass
    public void setup() {

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

        RestAssured.requestSpecification =
            RestAssured.given()
                .header("x-api-key", "reqres-free-v1")
                .header("Accept", "application/json");
    }
}

For a production framework, read these values from config.properties rather than hardcoding them.

Step 3: UserGetTest.java

import org.testng.annotations.Test;
import static io.restassured.RestAssured.*;

public class UserGetTest extends BaseTest {

    @Test
    public void getUser() {

        given()

        .when()
            .get("/api/users/2")

        .then()
            .statusCode(200)
            .body("data.id",
                org.hamcrest.Matchers.equalTo(2))
            .log().ifValidationFails();
    }
}

Step 4: Execute Using Maven

mvn clean test

Expected Output

[INFO] Running tests.UserGetTest
[INFO] Tests run: 1, Failures: 0, Errors: 0

[INFO] BUILD SUCCESS

Note: RestAssured.requestSpecification is global static configuration. For parallel execution, prefer a thread-safe, per-test or per-thread specification instead of sharing mutable global state.

30. TestNG Parallel Execution

You can run API test classes in parallel using TestNG.

Create testng.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE suite SYSTEM
"https://testng.org/testng-1.0.dtd">

<suite name="API Test Suite" parallel="classes" thread-count="3">

    <test name="API Tests">

        <classes>
            <class name="tests.UserGetTest"/>
            <class name="tests.UserPostTest"/>
            <class name="tests.UserDeleteTest"/>
        </classes>

    </test>

</suite>

Run

mvn clean test

Expected Output

Running UserGetTest
Running UserPostTest
Running UserDeleteTest

Tests run: 3
Passed: 3
Failed: 0

The three test classes can execute concurrently.

31. Filters in Rest Assured

Filters allow you to intercept and modify requests and responses.

Example

import io.restassured.filter.Filter;
import io.restassured.filter.FilterContext;
import io.restassured.response.Response;
import io.restassured.specification.FilterableRequestSpecification;
import io.restassured.specification.FilterableResponseSpecification;

public class CustomFilter implements Filter {

    @Override
    public Response filter(
        FilterableRequestSpecification requestSpec,
        FilterableResponseSpecification responseSpec,
        FilterContext context) {

        System.out.println("Request URL: " + requestSpec.getURI());

        Response response = context.next(requestSpec, responseSpec);

        System.out.println("Status: " + response.statusCode());

        return response;
    }
}

Usage

given()
    .filter(new CustomFilter())

.when()
    .get("https://example.com/api/users")

.then()
    .statusCode(200);

Expected Output

Request URL: https://example.com/api/users
Status: 200

Filters are useful for logging, reporting, authentication and request/response monitoring.

32. Rest Assured with Allure / Extent Reports

In automation projects, we need execution reports containing:

  • Test case name.
  • API endpoint.
  • HTTP method.
  • Request payload.
  • Response body.
  • Status code.
  • Execution time.
  • Pass/fail details.

You can integrate Rest Assured with Extent Reports.

Add Extent Reports Dependency

<dependency>
    <groupId>com.aventstack</groupId>
    <artifactId>extentreports</artifactId>
    <version>5.1.2</version>
    <scope>test</scope>
</dependency>

Basic Reporting Example

import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.reporter.ExtentSparkReporter;

public class ApiReport {

    public static void main(String[] args) {

        ExtentSparkReporter reporter =
            new ExtentSparkReporter("reports/APIReport.html");

        ExtentReports extent = new ExtentReports();

        extent.attachReporter(reporter);

        ExtentTest test =
            extent.createTest("GET User API Test");

        test.info("Sending GET request");

        test.pass("Status code validated successfully");

        extent.flush();
    }
}

Generated Report

reports/
    APIReport.html

33. API Testing in CI/CD Using Jenkins

Rest Assured tests can be executed automatically through Jenkins pipelines.

Example Jenkinsfile

pipeline {

    agent any

    stages {

        stage('Checkout') {
            steps {
                git 'https://github.com/username/api-tests.git'
            }
        }

        stage('Build') {
            steps {
                bat 'mvn clean compile'
            }
        }

        stage('API Testing') {
            steps {
                bat 'mvn test'
            }
        }

        stage('Publish Reports') {
            steps {
                archiveArtifacts artifacts: 'test-output/**',
                                 allowEmptyArchive: true
            }
        }
    }
}

For Linux Jenkins agents, replace bat with sh.

Pipeline Execution Flow

  1. Checkout source code from GitHub.
  2. Compile Maven project.
  3. Execute Rest Assured API tests.
  4. Generate test reports.
  5. Archive test results.

34. Commonly Used Rest Assured Methods

Method Description
given()Prepare request
when()Execute request
then()Validate response
get()GET request
post()POST request
put()PUT request
patch()PATCH request
delete()DELETE request
queryParam()Add query parameter
pathParam()Add path parameter
header()Add request header
headers()Add multiple headers
body()Set request body
contentType()Set content type
accept()Set accepted response type
auth()Configure authentication
cookie()Add cookie
cookies()Add multiple cookies
multiPart()Upload file
extract()Extract response
jsonPath()Read JSON response
xmlPath()Read XML response
log()Log request/response
statusCode()Validate HTTP status
response()Get complete response

35. Important Interview Questions and Answers

1. What is Rest Assured?

Rest Assured is a Java library used for automating REST API testing. It supports HTTP methods, authentication, JSON/XML validation and response assertions.

2. What is the difference between POST and PUT?

  • POST generally creates a new resource.
  • PUT generally replaces or updates a resource.
  • PUT is typically idempotent; POST is not necessarily idempotent.

3. What is the difference between PUT and PATCH?

  • PUT generally replaces the complete resource representation.
  • PATCH updates selected fields.

4. What is the difference between JSONPath and XMLPath?

  • JSONPath extracts information from JSON responses.
  • XMLPath extracts information from XML responses.

5. What is serialization?

Converting Java objects into JSON or XML representations.

6. What is deserialization?

Converting JSON or XML responses into Java objects.

7. What is the difference between queryParam and pathParam?

  • Query parameter filters or searches resources.
  • Path parameter identifies a particular resource.

8. What is RequestSpecification?

It is used to create reusable request configurations such as base URL, headers, authentication and content type.

9. What is ResponseSpecification?

It defines reusable response validations such as status code, content type and response expectations.

10. How do you validate response time?

Using the time() method with a Hamcrest matcher.

11. How do you validate JSON schema?

Using the Rest Assured JSON Schema Validator module.

12. How do you perform API chaining?

Extract data from one API response and pass it as input to another API request.

13. What is the difference between 401 and 403?

  • 401: Authentication is missing or invalid.
  • 403: The client is authenticated but does not have permission.

14. What is the difference between 200 and 201?

  • 200: Request successfully processed.
  • 201: Resource successfully created.

15. How do you execute Rest Assured tests in parallel?

Using TestNG's parallel execution configuration or another parallel test runner, with isolated test data and thread-safe request configurations.

16. How do you validate dynamic response values?

Extract the values using JSONPath and compare them with expected values or other API responses.

17. How do you handle authentication tokens?

Extract the token from the login response and pass it through the Authorization header in subsequent API requests.

18. How do you test APIs without a database?

Use API responses, mocks, stubs and contract validation. Database validation is optional and depends on the test requirements.

19. How do you validate a response array?

Use JSONPath with getList(), Hamcrest hasItem() or hasItems().

20. How do you handle environment-specific URLs?

Use configuration files, environment variables or Maven profiles for QA, staging and production environments.

36. Real-Time API Automation Scenarios

These are particularly useful for experienced automation testers.

Scenario What to Validate
Login APIToken generation
User APIUser details
Create order APIOrder ID
Payment APITransaction status
Shipment APITracking number
Search APISearch results
Update APIUpdated values
Delete APIResource deletion
Authorization APIAccess control
File upload APIFile metadata
Bulk APIMultiple records
Pagination APIPage number and records
Rate limitingHTTP 429
IdempotencyDuplicate request handling

Shipment API Automation Workflow

An example automation sequence would be:

  1. Create shipment – POST

    Validate shipment creation and shipment ID.

  2. Generate shipping label – POST

    Validate label URL and tracking number.

  3. Get shipment – GET

    Validate shipment details and tracking information.

  4. Update shipment – PATCH

    Validate shipment status changes.

  5. Validate tracking – GET

    Validate downstream tracking status.

  6. Cancel shipment – DELETE/POST

    Validate cancellation according to the API contract.

This is a useful example of combining API chaining, JSONPath, positive and negative testing, and database validation.

37. Recommended Learning Roadmap

Rest Assured Learning Roadmap

  1. Java Fundamentals

    Collections, OOP, interfaces, exceptions, streams.

  2. HTTP Fundamentals

    Methods, status codes, headers, request and response.

  3. Rest Assured Basics

    given(), when(), then(), GET, POST, PUT, PATCH, DELETE.

  4. Response Validation

    JSONPath, XMLPath, Hamcrest, response extraction.

  5. Advanced API Testing

    Authentication, schema, cookies, multipart, filters.

  6. Framework Development

    Maven, TestNG, POJO, specifications, utilities.

  7. Advanced Automation

    Chaining, DataProvider, parallel execution, reporting.

  8. CI/CD

    GitHub Actions, Jenkins, Docker.

38. Useful Official Resources

Conclusion

After learning the individual HTTP methods, build one complete Rest Assured + Java + Maven + TestNG framework with authentication, reusable specifications, JSON/XML validation, API chaining, Extent Reports and Jenkins integration.

This will give you practical experience with the architecture expected in automation testing roles.

No comments:

Post a Comment