Showing posts with label API Automation. Show all posts
Showing posts with label API Automation. Show all posts

Test API using POJO Class in Playwright


















What Is a POJO Class? Complete Guide to Testing APIs with POJO in Playwright Java

When working with REST APIs in Java automation frameworks, one of the most important concepts you’ll encounter is the POJO class. If you are performing API testing using Playwright Java, understanding POJOs can significantly improve your test structure, readability, and maintainability.

In this detailed, SEO-optimized guide, you will learn:

  • What a POJO class is

  • Why POJOs are important in API testing

  • How to use POJO classes in Playwright Java

  • How serialization and deserialization work

  • Step-by-step example with complete code

  • Best practices for scalable API automation

This article is written in a clear, human-friendly style to help both beginners and experienced automation engineers.


1. What Is a POJO Class?

POJO stands for Plain Old Java Object.

A POJO is a simple Java class that:

  • Does not extend special framework classes

  • Does not implement framework-specific interfaces

  • Contains fields (variables)

  • Contains constructors

  • Contains getter and setter methods

In simple terms, a POJO is just a normal Java class used to represent data.

Example of a Simple POJO

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; } public void setName(String name) { this.name = name; } public void setJob(String job) { this.job = job; } }

This class represents structured data.


2. Role of POJO in API Testing

In API automation testing, especially REST API testing, data is usually transferred in:

  • JSON format

  • XML format

When testing APIs in Java, we often need to:

  • Send request payloads

  • Read response payloads

  • Validate response fields

Instead of writing raw JSON strings inside test code, we use POJOs to represent structured data.

For example:

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

Instead of writing the JSON manually, we can create a User POJO and convert it to JSON.

This approach makes test automation:

  • Cleaner

  • More readable

  • Easier to maintain


3. Why Use POJO in API Testing?

Using POJO classes in API testing provides multiple benefits.

1. Readable and Maintainable Code

Working with Java objects is much easier than handling raw JSON strings.

Instead of:

String json = "{ \"name\": \"Himanshu\", \"job\": \"QA Engineer\" }";

You can write:

User user = new User("Himanshu", "QA Engineer");

This improves clarity.


2. Reusability

The same POJO class can be reused:

  • Across multiple test cases

  • For POST and PUT requests

  • For response validation

If the API structure changes, you only update the POJO class instead of editing JSON in multiple tests.


3. Serialization and Deserialization

Libraries like:

  • Gson

  • Jackson

Allow you to:

  • Convert POJO → JSON (Serialization)

  • Convert JSON → POJO (Deserialization)

This automatic conversion makes API testing powerful and structured.


4. Strong Typing

When you deserialize JSON into a POJO:

  • You get compile-time type checking

  • You avoid runtime JSON parsing errors

  • You can directly access fields using getters

Example:

responsePojo.getName();

Instead of manually parsing JSON.


4. Using POJO in Playwright Java for API Testing

Playwright is primarily known for browser automation, but it also provides API testing support through APIRequestContext.

When testing APIs in Playwright Java:

  1. Define POJO class

  2. Serialize POJO to JSON

  3. Send API request

  4. Deserialize response

  5. Perform assertions

Let’s understand this step-by-step.


5. Steps to Test an API with POJO in Playwright Java

Step 1: Add Maven Dependencies

<dependencies> <dependency> <groupId>com.microsoft.playwright</groupId> <artifactId>playwright</artifactId> <version>1.44.0</version> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.10.1</version> </dependency> </dependencies>

These dependencies allow:

  • Playwright API testing

  • JSON serialization using Gson


6. Example API Scenario

We will test the following endpoint:

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

Payload

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

This API is provided by ReqRes, a free REST API for testing.


7. Step 1: Create 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; } public void setName(String name) { this.name = name; } public void setJob(String job) { this.job = job; } }

This class represents the request structure.


8. Step 2: Main Test Code Using Playwright

import com.microsoft.playwright.*; import com.google.gson.Gson; import com.microsoft.playwright.options.*; public class PostApiTest { public static void main(String[] args) { try (Playwright playwright = Playwright.create()) { APIRequestContext request = playwright.request().newContext(); // Create POJO object User user = new User("Himanshu", "QA Engineer"); // Convert POJO to JSON Gson gson = new Gson(); String jsonBody = gson.toJson(user); // Send POST request APIResponse response = request.post("https://reqres.in/api/users", RequestOptions.create() .setHeader("Content-Type", "application/json") .setData(jsonBody) ); // Validate response System.out.println("Status: " + response.status()); System.out.println("Response Body: " + response.text()); if (response.status() == 201) { System.out.println("POST request successful!"); } else { System.out.println("POST request failed!"); } } } }


9. Code Explanation (Detailed)

(a) Create Playwright Object

Playwright playwright = Playwright.create();

Initializes Playwright environment.


(b) Create APIRequestContext

APIRequestContext request = playwright.request().newContext();

This acts as an HTTP client for sending API requests.


(c) Create POJO Object

User user = new User("Himanshu", "QA Engineer");

Instead of writing JSON manually, we use Java object.


(d) Serialize POJO to JSON

Gson gson = new Gson(); String jsonBody = gson.toJson(user);

Converts Java object into JSON string.


(e) Send POST Request

request.post(...)

We attach:

  • Content-Type header

  • JSON request body


(f) Validate Response

We check:

  • Status code (201 Created)

  • Response body


10. Expected Output

Status: 201 Response Body: { "name": "Himanshu", "job": "QA Engineer", "id": "734", "createdAt": "2025-07-28T10:52:45.108Z" } POST request successful!

A 201 status confirms successful resource creation.


11. Deserializing Response into POJO (Advanced)

Instead of printing raw JSON, you can create a response POJO:

public class UserResponse { private String name; private String job; private String id; private String createdAt; // getters and setters }

Then:

UserResponse responseObj = gson.fromJson(response.text(), UserResponse.class); System.out.println(responseObj.getId());

This is called deserialization.

Benefits:

  • Direct field access

  • Strong validation

  • Cleaner assertions


12. Advantages of Using POJO in Playwright API Testing

Cleaner Test Code

No messy JSON strings.


Reusable Models

Same POJO works across:

  • POST tests

  • PUT tests

  • Response validation


Strong Validation

Fields are validated at compile-time.


Easy Maintenance

If API adds a new field:

  • Just update POJO

  • No need to edit all test files


Scalable Framework

In large enterprise projects:

  • Hundreds of APIs

  • Complex nested JSON

POJOs make framework scalable and structured.


13. Best Practices for POJO-Based API Testing

1. Separate Request and Response POJOs

Avoid mixing request and response models.


2. Use Builder Pattern for Complex Payloads

For large JSON structures, consider builder pattern.


3. Use Assertions Framework

Instead of:

if (response.status() == 201)

Use:

  • JUnit

  • TestNG

  • AssertJ


4. Handle Nested JSON Properly

For nested objects:

{ "user": { "name": "Himanshu" } }

Create nested POJO classes.


5. Validate Schema When Needed

Use schema validation for contract testing.


14. Common Mistakes to Avoid

  • Writing raw JSON everywhere

  • Not deserializing response

  • Ignoring response validation

  • Mixing test logic and data models

  • Hardcoding values repeatedly


15. Final Thoughts

A POJO (Plain Old Java Object) is one of the most important building blocks in Java-based API automation.

When combined with:

  • Playwright Java

  • Gson or Jackson

  • Structured test design

It provides:

  • Clean code

  • Strong validation

  • Reusable models

  • Scalable automation frameworks

Testing APIs using POJOs ensures your automation framework is professional, maintainable, and production-ready.

If you are serious about mastering API automation with Playwright Java, learning how to properly design and use POJO classes is absolutely essential.



Suggested Posts:

1. Automate GET API in Playwright
2. Automate POST API in Playwright
3. Automate PUT API in Playwright
4. Test Basic Authentication in Playwright
5. Token Bsed Authentication in Playwright

How to Test DELETE API By Playwright























What Is a DELETE API? Complete Guide to Testing DELETE API Using Playwright Java

In modern web applications and RESTful services, APIs are the backbone of communication between client and server. While GET retrieves data, POST creates new resources, and PUT updates existing ones, the DELETE API is responsible for removing resources from the server.

If you are an automation tester, backend developer, or preparing for API automation interviews, understanding how DELETE API works and how to test it using Playwright Java is extremely important.

In this comprehensive guide, you will learn:

  • What is a DELETE API?

  • How DELETE API works in REST architecture

  • Common response status codes

  • Why DELETE API testing is important

  • Step-by-step guide to testing DELETE API using Playwright Java

  • Java code example with explanation

  • How to validate deletion properly

  • Negative test scenarios

  • Best practices for DELETE API testing

This article is written in a natural, human-friendly tone, fully SEO optimized, and AdSense compliant for blog publishing.


What Is a DELETE API?

A DELETE API is an HTTP method used in RESTful web services to remove an existing resource from the server.

It typically requires a unique identifier (such as an ID) to specify which resource should be deleted.

Simple Definition

DELETE = Remove an existing resource from the server


Example of DELETE API

If you have a user stored in a database with ID 123, you can delete that user using:

DELETE /users/123

This request tells the server to remove the user with ID 123 permanently.


Common Response Status Codes for DELETE API

When testing a DELETE API, understanding response codes is essential.

Status CodeMeaning
200 OKDeletion successful (with response body)
204 No ContentDeletion successful (no response body)
404 Not FoundResource does not exist
401 UnauthorizedAuthentication required
403 ForbiddenPermission denied
500 Internal Server ErrorServer-side issue

Most DELETE APIs return 204 No Content when deletion is successful.


Why Test DELETE API?

Testing a DELETE API is critical to ensure system integrity and data safety.

Here’s why:

1. Confirm Resource Is Actually Removed

Just because API returns success doesn’t mean data is deleted. Testing verifies actual deletion.

2. Validate Correct Status Codes

Ensures server follows API contract.

3. Check Unauthorized Access Handling

Ensures only authorized users can delete data.

4. Prevent Accidental Deletions

Ensures no unintended resources are removed.

5. Validate Error Scenarios

Ensures proper handling of invalid or non-existing resource IDs.

In production systems, improper DELETE API handling can lead to major data loss issues.


How DELETE API Works in REST Architecture

The flow is simple:

  1. Client sends DELETE request with resource ID.

  2. Server verifies authentication and authorization.

  3. Server removes resource from database.

  4. Server returns appropriate HTTP status code.

Example:

DELETE https://example.com/api/users/2


Testing DELETE API Using Playwright Java

Many people know Playwright as a UI automation tool. However, it also provides powerful API testing capabilities using APIRequestContext.

With Playwright Java, you can:

  • Send DELETE requests

  • Send GET, POST, PUT requests

  • Validate status codes

  • Validate headers

  • Verify resource deletion

  • Combine API and UI automation

And all of this without launching a browser.


Example Scenario

We will test this DELETE API:

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

This example API is taken from reqres.in for demonstration purposes.


Step-by-Step Guide to Test DELETE API in Playwright Java

Let’s go through the steps in detail.


Step 1: Add Maven Dependency

Add the Playwright dependency in your pom.xml file:

<dependency> <groupId>com.microsoft.playwright</groupId> <artifactId>playwright</artifactId> <version>1.44.0</version> </dependency>

Always use the latest stable version available.


Step 2: Java Code to Test DELETE API

Here is the complete working example:

import com.microsoft.playwright.*; import java.util.Map; public class DeleteAPITest { public static void main(String[] args) { try (Playwright playwright = Playwright.create()) { // Set up base URL and headers APIRequest.NewContextOptions options = new APIRequest.NewContextOptions() .setBaseURL("https://reqres.in") .setExtraHTTPHeaders(Map.of( "Content-Type", "application/json" )); APIRequestContext request = playwright.request().newContext(options); // Send DELETE request APIResponse response = request.delete("/api/users/2"); // Print response details System.out.println("Status Code: " + response.status()); System.out.println("Status Text: " + response.statusText()); if (response.status() == 204) { System.out.println("DELETE API test passed"); } else { System.out.println("DELETE API test failed"); } request.close(); } } }


Code Explanation (Step-by-Step)

Let’s break down the code for better understanding.


(a) Set Base URL

.setBaseURL("https://reqres.in")

This defines the base API endpoint.

Instead of writing full URL every time, we only use relative path.


(b) Add Headers

.setExtraHTTPHeaders(Map.of("Content-Type", "application/json"))

Headers are necessary when API expects specific content type or authentication tokens.


(c) Send DELETE Request

request.delete("/api/users/2");

This sends DELETE request to remove user with ID 2.


(d) Validate Status Code

response.status();

Expected successful status = 204 No Content


(e) Close Request Context

request.close();

Always close context to release resources.


Expected Output

Status Code: 204 Status Text: No Content DELETE API test passed

This confirms that the resource was successfully deleted.


How to Verify Resource Deletion (Important Step)

A professional way to confirm deletion is:

  1. Send DELETE request.

  2. Send GET request for same ID.

  3. Validate GET returns 404 Not Found.

Example:

APIResponse getResponse = request.get("/api/users/2"); System.out.println("GET after DELETE Status: " + getResponse.status());

Expected:

404 Not Found

This confirms the resource is permanently removed.


Negative Testing for DELETE API

Always test negative scenarios.

1. Delete Non-Existing Resource

DELETE /users/9999

Expected response:

404 Not Found


2. Unauthorized Delete Request

If authentication token is missing:

Expected:

401 Unauthorized


3. Forbidden Request

If user doesn’t have permission:

Expected:

403 Forbidden

Negative testing ensures system security and stability.


Measuring Response Time

Performance matters in API testing.

Example:

long start = System.currentTimeMillis(); APIResponse response = request.delete("/api/users/2"); long end = System.currentTimeMillis(); System.out.println("Response Time: " + (end - start) + " ms");

You can define acceptable threshold such as:

  • Response time < 2000 ms


Best Practices for DELETE API Testing

Here are professional best practices:

1. Always Validate Status Code

Never assume success.

2. Confirm Actual Deletion

Send GET request after DELETE.

3. Test Security

Validate authentication and authorization.

4. Test Edge Cases

Invalid IDs
Large data sets
Concurrent deletion requests

5. Use Assertions Framework

Integrate with TestNG or JUnit for structured validation.


Combining API and UI Testing

Playwright allows you to combine API and UI tests efficiently.

Example scenario:

  1. Use POST API to create user.

  2. Use DELETE API to remove user.

  3. Launch browser.

  4. Verify deleted user does not appear in UI.

This approach increases automation reliability and speed.


Common Interview Questions on DELETE API

  1. What is DELETE API?

  2. What status code is returned for successful DELETE?

  3. What does 204 No Content mean?

  4. How do you confirm resource deletion?

  5. How to automate DELETE API using Playwright?

  6. What are common negative scenarios?

If you are preparing for automation interviews, mastering DELETE API testing is essential.


Advantages of API Testing

  • Faster than UI testing

  • More stable and reliable

  • Detect backend issues early

  • Suitable for CI/CD pipelines

  • Supports microservices testing

Modern automation frameworks always include API testing as a core component.


Conclusion

A DELETE API is used to remove an existing resource from the server in RESTful applications. Proper testing ensures that:

  • Resource is actually deleted

  • Correct status codes are returned

  • Unauthorized access is blocked

  • No unintended data is affected

Using Playwright Java, you can:

  • Send DELETE requests

  • Validate status codes

  • Confirm deletion with GET request

  • Measure response time

  • Handle negative scenarios

  • Integrate API and UI testing seamlessly

If you are learning automation testing or preparing for interviews, mastering DELETE API testing with Playwright will significantly enhance your skills.


Suggested Posts:

1. Automate GET API in Playwright
2. Automate POST API in Playwright
3. Automate PUT API in Playwright
4. Automate Lombok API in Playwright
5. Test API by POJO Class in Playwright