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




1. What is a POJO Class?

  • POJO stands for Plain Old Java Object.
  • It is a simple Java class that does not extend or implement any special framework classes.
  • It is mainly used to define structured data in Java with fields, constructors, getters, and setters.
  • In the context of APIs, POJOs are used to map request and response payloads (usually JSON or XML) into Java objects, making it easier to handle data.
  • Playwright Java supports HTTP requests using the APIRequest module. You can serialize a POJO (Plain Old Java Object) to JSON and send it in the POST request body.

2. Why Use POJO in API Testing?
  • Readable & Maintainable → Instead of writing raw JSON strings, you can work with objects.
  • Reusability → The same POJO class can be used across multiple tests for request/response validation.
  • Serialization/Deserialization → Libraries like Jackson or Gson can automatically convert POJOs to JSON (for requests) and JSON back to POJOs (for responses).
  • Strong Typing → You get compile-time type safety when accessing response fields.


3. How to Test an API with POJO in Playwright Java

Although Playwright is primarily for browser automation, it provides API testing support through its APIRequestContext. Here’s how POJOs fit in:

(1) Define POJO Class

  • Create a POJO representing the request body structure (for POST/PUT).
  • Create another POJO representing the response body structure (for parsing).

(2) Serialize Request POJO to JSON

  • Use Jackson or Gson to convert the Java object (POJO) into JSON format.
  • Pass this JSON as the request body when making API calls with Playwright’s API request methods.

(3) Send API Request with Playwright

  • Use Playwright’s APIRequestContext to send GET, POST, PUT, or DELETE requests.
  • Attach headers, authentication, and the serialized JSON request if needed.

(4) De serialize Response into POJO

  • Playwright will return the response body as JSON.
  • Convert (de serialize) that JSON into a POJO class using Jackson or Gson.

(5) Assertions Using POJO

  • Instead of manually parsing JSON, directly access response fields from the POJO.
  • Example: check if responsePojo.getStatus() equals "success".

4. Advantages of Testing API with POJOs in Playwright Java
  • Cleaner test code → Work with objects, not raw JSON strings.
  • Reusable Models → Same POJO can be used across multiple test cases.
  • Consistency → Ensures request and response structures are strongly validated.
  • Scalability → Easier to expand test coverage as API complexity grows.








Steps

  • Create POJO class to represent your request payload.
  • Initialize Playwright and APIRequestContext.
  • Send POST request using .post() with the serialized POJO.
  • Validate the response.


Example:

Suppose you're testing an API endpoint:


POST https://reqres.in/api/users
Payload: { "name": "Himanshu", "job": "QA Engineer" }


















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>



1. Create POJO Class

Below is the POJO class consists of two attributes name and job and their getter and setter methods.

public class User {
    private String name;
    private String job;

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

    // Getters and setters (optional)
    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; }
}



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!");
            }
        }
    }
}



Code explanation:

(a) Create Playwright Object and APIRequestContext object
(b) Create Pojo class object
(c) Convert POJO to JSON
(d)  Send POST request
(e) Validate the resposne



Expected Output

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

Above is the output of API with status code 201, as this is POST API and response body in the JSON format.


Important Points:

  • Gson is used to serialize the POJO into JSON.
  • RequestOptions.create().setData(jsonBody) sets the request body.
  • This approach is ideal when working with complex request bodies in APIs.


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?

  • A DELETE API is an HTTP method used in RESTful web services to remove a resource from the server.
  • It typically requires an identifier (like id) of the resource to be deleted.
  • Example: DELETE /users/123 would delete the user with ID 123.
  • The response usually confirms deletion with a status code:
          200 OK or 204 No Content → deletion successful.

          404 Not Found → resource doesn’t exist.

          401/403 → authentication or authorization issues.


Why test DELETE API?

Testing ensures that:

  • The resource is actually removed from the server.
  • The correct HTTP status codes are returned.
  • Unauthorized or invalid requests are handled properly.
  • No unintended resources are affected.

How to test a DELETE API with Playwright Java

Playwright’s APIRequestContext allows making direct API calls. Testing a DELETE API would involve:

(1) Setup API Context
  • Initialize an API request context with the base URL and authentication headers if needed.

(2) Send DELETE Request
  • Use the DELETE method with the resource endpoint (like /users/{id}).
  • Attach headers (Authorization, Content-Type) if required.

(3) Validate Response Status
  • Check if the response status code matches expectations (e.g., 204 for success).

(4) Validate Response Body (if any)
  • Some APIs return a confirmation message or the deleted resource details.
  • Validate the message or structure if it exists.

(5) Verify Resource Deletion
  • Optionally send a GET request for the same resource ID.
  • Ensure the response is 404 Not Found (confirming the resource is gone).

To test a DELETE API using Playwright in Java, you can use Playwright’s ability to perform raw HTTP requests using the APIRequestContext interface.














Steps to Test DELETE API in Playwright Java

  • Create Playwright and APIRequestContext instance
  • Send DELETE request using delete() method
  • Validate response (status code, body, etc.)
  • Close the context and playwright


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

The API is taken from reqres.in 














Maven Dependencies

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



Java Code Example to Test DELETE API

import com.microsoft.playwright.*;

import java.util.HashMap;
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") // Example DELETE test API
                .setExtraHTTPHeaders(Map.of(
                    "Content-Type", "application/json"
                ));

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

            // Send DELETE request
            APIResponse response = request.delete("/api/users/2");

            // Print and assert the response
            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

  • setBaseURL("https://reqres.in") sets the base URL.
  • .delete("/api/users/2") sends the DELETE request to delete user with ID 2.
  • The expected status code is 204 No Content — common for successful DELETEs.
  • You can also validate the response body, headers, etc., if needed.


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

How to Test PUT API by Playwright




What is PUT API?

  • A PUT API is an HTTP request method used in RESTful web services to update an existing resource on the server.
  • Unlike POST, which is used to create new data, PUT is typically used when the client wants to replace or update the entire resource with new data.
  • Example use case: Updating a user’s profile information (like email, phone number, or address).



Important Characteristics:
  • Idempotent → Multiple identical PUT requests should result in the same state of the resource.
  • Requires a complete representation of the resource to be sent in the request body (not just partial changes, unless API supports PATCH).


Testing a PUT API with Playwright Java

Although Playwright is mainly used for UI automation, it also provides powerful API testing capabilities. Using Playwright with Java, you can send PUT requests and validate the responses.


(1) Create a request context
  • In Playwright, you use a APIRequestContext (or similar request handling object in Java binding) to interact with APIs.
  • This context acts like a lightweight HTTP client.

(2) Send a PUT request
  • Use the request context to call the PUT method on a given API endpoint.
  • Provide necessary details like:
        URL → The endpoint where the resource exists (e.g., /users/123).
        Headers → Usually includes Content-Type: application/json, and sometimes            Authorization tokens.
        Request body → JSON data with updated information for the resource.


(3) Validate the Response
  • Check the status code (e.g., 200 OK or 204 No Content indicates success).
  • Verify the response body (if API returns the updated resource).
  • Assert that changes are correctly applied by checking response fields or sending a subsequent GET request to fetch updated data.

(4) Error Handling
  • If you send invalid data, the server should return 400 Bad Request.
  • If you update a non-existing resource, you might get 404 Not Found.
  • These scenarios should also be tested.

To test a PUT API using Playwright Java, you can use the APIRequestContext interface provided by Playwright. A PUT request is generally used to update an existing resource on the server. Here's how you can test it step-by-step:










Steps to Test a PUT API in Playwright Java

  • Initialize Playwright and APIRequestContext
  • Prepare the request headers and body
  • Send the PUT request using put() method
  • Verify the response (status code, body, etc.)


Example Scenario

Let’s say we are updating a user at endpoint:

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
















Below is the input JSON request for PUT API

{
  "name": "Himanshu",
  "job": "Software Developer"
}



Java Code to Test PUT API with Playwright

import com.microsoft.playwright.*;
import com.microsoft.playwright.options.*;

import java.util.*;

public class PutApiTest {
  public static void main(String[] args) {
    try (Playwright playwright = Playwright.create()) {
      APIRequest request = playwright.request();

      APIRequestContext requestContext = request.newContext(new APIRequest.NewContextOptions()
        .setBaseURL("https://reqres.in/api"));

      // Prepare JSON request body
      Map<String, Object> data = new HashMap<>();
      data.put("name", "Himanshu");
      data.put("job", "Software Developer");

      // Send PUT request
      APIResponse response = requestContext.put("/users/2",
        RequestOptions.create()
          .setHeader("Content-Type", "application/json")
          .setData(data)
      );

      // Print status code
      System.out.println("Status Code: " + response.status());

      // Print response body
      System.out.println("Response Body: " + response.text());

      // Optional: Validate status code
      if (response.ok()) {
        System.out.println("PUT request successful.");
      } else {
        System.out.println("PUT request failed.");
      }
    }
  }
}



Code explanation:

(a) Create object of APIRequestContext class
(b) Prepare JSON request body
(c) Called PUT request using APIRequestContext object
(d) Print the status code
(e) Print the response
(d) Validate status code



Output:

Status Code: 200
Response Body: {
    "name": "Himanshu",
    "job": "Software Developer",
    "updatedAt": "2025-07-28T12:13:45.012Z"
}
PUT request successful.

Above is the output of PUT API. We can see status code is 200 as API is successfully executed and have response in the response body.



Important Points:
  • APIRequestContext.put() is used to send the PUT request.
  • You can validate more fields using:
response.json().get("name").toString();
  • Always set the Content-Type header for JSON payloads.


Suggested Posts:

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

How to Test POST API by Playwright




What is POST API?

A POST API is an API endpoint that allows clients to send data to a server so that the server can process it and often create a new resource. Unlike a GET API, which is only used to retrieve data, a POST API typically involves submitting information such as form data, JSON payloads, or file uploads. For example, creating a new user account, submitting a login form, or uploading a file are common use cases of POST APIs.


How to Test a POST API with Playwright Java

Playwright is primarily a UI automation tool, but it also provides ways to send API requests directly without interacting with the browser. In Java, you can use Playwright’s APIRequestContext to test POST APIs. The high-level steps are:


Create an APIRequestContext

  • Initialize a Playwright request context that acts as a client for making API calls.
  • This context allows you to set a base URL, headers, or authentication details.


Prepare the POST Request

  • Define the API endpoint you want to test.
  • Construct the body of the request, which might include JSON, form-data, or raw text.
  • Attach required headers such as Content-Type: application/json or authorization tokens if needed.


Send the POST Request

  • Use the context to send the POST request along with the payload.
  • The server processes the request and returns a response.


Validate the Response

  • Check the status code (e.g., 200 for success, 201 for resource created, 400 for bad request).
  • Validate the response body to ensure that the server returned the correct data or confirmation.
  • Verify response headers if necessary.


Assertions in TestNG/JUnit

  • In actual testing, you would assert expected vs. actual values.
  • For example, if you created a new user, you’d assert that the response contains the user ID or success message.


Integration with UI Tests (Optional)

  • Sometimes you may chain API and UI testing. 
  • For example: Use the POST API to create a user. Then, log in with that user in the UI using Playwright’s browser automation.


To test a POST API using Playwright in Java, you can utilize the APIRequestContext provided by Playwright. This feature allows you to perform HTTP operations like POST, GET, PUT, and DELETE without launching a browser.













Steps to Test a POST API using Playwright Java:

  • Initialize Playwright and create an APIRequestContext.
  • Use post() method to send a POST request.
  • Pass headers, payload (body), and endpoint URL.
  • Read and validate the response (status code, body, etc.).
  • Close the context.


Example: POST API Test in Playwright Java

Let’s take an example of a fake JSON placeholder API:

Endpoint: https://jsonplaceholder.typicode.com/posts
Method: POST






Payload:

{
  "title": "foo",
  "body": "bar",
  "userId": 1
}

Above is the input JSON payload which is used to feed as request to POST API



Java Code (Maven + Playwright):

import com.microsoft.playwright.*;
import java.util.*;

public class PostApiTest {
    public static void main(String[] args) {
        try (Playwright playwright = Playwright.create()) {

            // Create APIRequestContext
            APIRequest apiRequest = playwright.request();
            APIRequestContext requestContext = apiRequest.newContext();

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

            // Send POST request
            APIResponse response = requestContext.post("https://jsonplaceholder.typicode.com/posts", 
                RequestOptions.create()
                    .setHeader("Content-Type", "application/json")
                    .setData(payload)
            );

            // Validate response
            System.out.println("Status Code: " + response.status());
            System.out.println("Response Body: " + response.text());

            if (response.status() == 201) {
                System.out.println("POST API test passed!");
            } else {
                System.out.println("POST API test failed!");
            }

            // Close context
            requestContext.dispose();
        }
    }
}


Code explanation:

(a) Create APIRequestContext
(b) Define the payload
(c) Send POST request
(d) Validate response
(e) Close context



Output:

Status Code: 201
Response Body: {
  "title": "foo",
  "body": "bar",
  "userId": 1,
  "id": 101
}
POST API test passed!

Above is the output, having status code 201 as this is POST request and response body is JSON object which can be validate by JSONObject class


Suggested Posts:

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