For DevelopersFebruary 15, 2024

Managing Payload and Response Without Java POJOs in Rest-Assured

Simplify your testing process with this method.

When testing REST APIs in Java, we often rely on Rest-Assured, a powerful library for API testing. Many tutorials suggest using Plain Old Java Objects (POJOs) to manage request payloads and responses, but that approach isn’t always necessary. In this guide, I'll show you how we can interact with APIs in Rest-Assured without POJOs. This method simplifies testing, reduces boilerplate code, and gives us more flexibility.


Why Avoid POJOs in Rest-Assured?

Using POJOs might seem like a structured way to test APIs, but it has some downsides:

  1. Extra Code: We have to create and maintain Java classes for every API request and response.
  2. Less Flexibility: APIs might return dynamic or complex responses that don’t fit into predefined POJOs.
  3. Slower Iterations: When APIs change frequently, updating POJOs every time can be tedious.
  4. Unnecessary Dependencies: We may need extra libraries for serialization and deserialization, adding overhead to simple test cases.

Avoiding POJOs allows us to test APIs more dynamically and efficiently.


Alternative Approaches to Handling API Payloads and Responses

1. Using JSON Strings for Requests

Instead of mapping request payloads to Java objects, we can define JSON payloads as strings and pass them directly.

import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import static io.restassured.RestAssured.given;

public class APITest {
    public static void main(String[] args) {
        RestAssured.baseURI = "https://jsonplaceholder.typicode.com";

        String requestBody = """
        {
            "title": "foo",
            "body": "bar",
            "userId": 1
        }
        """;

        Response response = given()
                .contentType(ContentType.JSON)
                .body(requestBody)
                .when()
                .post("/posts")
                .then()
                .statusCode(201)
                .extract()
                .response();

        System.out.println("Response: " + response.asString());
    }
}

With this approach, we don’t need extra Java classes. It also makes modifying payloads easier.


2. Using Maps for Dynamic Requests

If we want more flexibility, we can use a Map<String, Object> instead of a POJO.

import java.util.HashMap;
import java.util.Map;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import static io.restassured.RestAssured.given;

public class DynamicRequest {
    public static void main(String[] args) {
        RestAssured.baseURI = "https://jsonplaceholder.typicode.com";

        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("title", "foo");
        requestBody.put("body", "bar");
        requestBody.put("userId", 1);

        Response response = given()
                .contentType(ContentType.JSON)
                .body(requestBody)
                .when()
                .post("/posts")
                .then()
                .statusCode(201)
                .extract()
                .response();

        System.out.println("Response: " + response.asString());
    }
}

This method makes it easy to modify payloads dynamically without worrying about POJOs.


3. Parsing JSON Responses without POJOs

Instead of mapping responses to Java objects, we can parse them directly using JsonPath.

import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;

public class ResponseParsing {
    public static void main(String[] args) {
        Response response = given()
                .when()
                .get("https://jsonplaceholder.typicode.com/posts/1")
                .then()
                .statusCode(200)
                .extract()
                .response();

        JsonPath jsonPath = new JsonPath(response.asString());
        String title = jsonPath.getString("title");
        int userId = jsonPath.getInt("userId");

        System.out.println("Title: " + title);
        System.out.println("User ID: " + userId);
    }
}

This is a simple way to extract data from API responses without needing a POJO.


4. Using List<Map<String, Object>> for Array Responses

If an API returns an array of objects, we can parse it into a list of maps.

import io.restassured.response.Response;
import java.util.List;
import java.util.Map;

public class ArrayResponseHandling {
    public static void main(String[] args) {
        Response response = given()
                .when()
                .get("https://jsonplaceholder.typicode.com/posts")
                .then()
                .statusCode(200)
                .extract()
                .response();

        List<Map<String, Object>> posts = response.jsonPath().getList("$");
        
        for (Map<String, Object> post : posts) {
            System.out.println("Post ID: " + post.get("id") + ", Title: " + post.get("title"));
        }
    }
}

This approach works well for APIs that return lists of objects, without requiring extra classes.


Conclusion

Rest-Assured is a powerful tool for API testing, and we don’t always need POJOs. By using JSON strings, maps, JsonPath, and lists, we can simplify our tests, make them more flexible, and speed up development.

If we’re working on a large project where strict type safety is important, POJOs might still be useful. But for quick, dynamic testing, these approaches are much easier to manage.

Want more examples or advanced techniques? Let me know in the comments!

Share

Mehmet  Serhat OzdursunMehmet Serhat Ozdursunauthor

Related Articles

For DevelopersTop 10 Java Algorithms Every Developer Needs (But Most Skip)
JavaProgramming
Most Java developers write code—but few understand the algorithms that make it fast, scalable, and production-ready. This guide breaks down 10 core Java algorithms—Kadane's, Union-Find, MST, LRU Cache, and more—showing exactly why they matter and when to use them.
Alexandr FrunzaAlexandr FrunzaBackend Developer
For EmployersTop 6 Platforms to Hire Java Developers in the USA
Tech HiringAlternative Tools
Hiring Java developers is hard because speed and skill rarely show up together. This guide breaks down the top platforms that deliver reliable Java talent in the USA. You’ll learn when to use each one so you avoid slow hires and expensive misfires.
Diyor IslomovDiyor IslomovSenior Account Executive