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

How to Test GET API in Playwright


What is a GET API?

  • A GET API is an HTTP request method used to retrieve data from a server.
  • It doesn’t change or update data; it only fetches information (for example: getting user details, product listings, weather data, etc.).
  • Example: If you open https://jsonplaceholder.typicode.com/users, the server responds with user data in JSON format.

In automation, testing a GET API means checking whether the API:

  • Returns the correct status code (e.g., 200 OK).
  • Provides the expected response body (data correctness).
  • Responds within an acceptable time (performance).
  • Returns correct headers (e.g., content type, cache control).    

How to Test GET API with Playwright Java

Playwright is not only for UI automation; it also provides an API testing capability.

1. Create APIRequestContext
  • Playwright provides a special context to send API requests.
  • This context allows you to perform GET, POST, PUT, DELETE requests without opening a browser.
2. Send GET Request
  • Use the APIRequestContext to call the GET endpoint (e.g., /users, /posts).
  • Playwright sends the request and stores the response.
3. Validate Response Status
  • Check if the status code is what you expect (200 for success, 404 for not found, etc.).
4. Validate Response Body
  • Extract the response in JSON or text format.
  • Verify key fields and values (e.g., userId, name, email).
  • Ensure response data structure matches the API contract.
5. Validate Headers
  • Check headers like Content-Type to ensure the response is in the correct format (e.g., application/json).
6. Validate Response Time
  • Ensure the API responds within performance thresholds.

Why Use Playwright for GET API Testing?
  • Unified framework: You can test both UI and API in the same test suite.
  • Useful for scenarios like: 
         Pre-test setup → Create or fetch test data using API before UI test.
         Validation → Compare UI results with API results for consistency.
  • Lightweight and fast compared to browser-based UI automation.


To test a GET API using Playwright in Java, you can use Playwright’s built-in APIRequestContext to send HTTP requests. This is useful for API testing in addition to browser automation.























Steps to Test a GET API using Playwright Java:

  • Initialize Playwright and APIRequestContext
  • Send GET request to the API endpoint
  • Validate the response: Status code, body content, headers, etc.
  • Close Playwright

Example: Test GET API in Playwright Java

Let’s test a public API like:
https://jsonplaceholder.typicode.com/posts/1




Maven Dependency

<dependency>
    <groupId>com.microsoft.playwright</groupId>
    <artifactId>playwright</artifactId>
    <version>1.43.0</version> <!-- use latest -->
</dependency>


Java Code to Test GET API

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

public class GetApiTest {
    public static void main(String[] args) {
        // Step 1: Initialize Playwright
        try (Playwright playwright = Playwright.create()) {
            // Step 2: Create APIRequest context
            APIRequest request = playwright.request();
            APIRequestContext requestContext = request.newContext();

            // Step 3: Send GET request
            APIResponse response = requestContext.get("https://jsonplaceholder.typicode.com/posts/1");

            // Step 4: Validate the response
            System.out.println("Status: " + response.status()); // 200 expected
            System.out.println("Status Text: " + response.statusText());

            // Step 5: Validate body content
            String responseBody = response.text();
            System.out.println("Response Body: \n" + responseBody);

            // Optional: Assert status code and content
            if (response.ok()) {
                System.out.println("API responded successfully.");
            } else {
                System.out.println("API test failed.");
            }

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


Code explanation:

(a) Step 1: Initialize Playwright
(b) Step 2: Create APIRequest context
(c) Step 3: Send GET request
(d) Step 4: Validate the response
(e) Step 5: Validate body content
(f) Optional: Assert status code and content
(g) Close API request context


Expected Output:

Status: 200
Status Text: OK
Response Body:
{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "..."
}
API responded successfully.


As shown above, status code of API is 200, that means API is successfully returned the response. And response body is given in JON format.


You Can Also Validate Specific Fields:

import org.json.JSONObject;
import org.testng.*;
JSONObject json = new JSONObject(response.text()); int id = jsonObject.getInt("id"); Assert.assertEquals(id, 1); System.out.println("JSON fields validated.");

For validating response, we can use JSONObject class.


Suggested Posts:

1. Automate POST 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

Advantages and Disadvantages of Playwright

  

Playwright is a modern open-source automation tool developed by Microsoft that enables end-to-end testing of web applications. It supports automation across Chromium, Firefox, and WebKit, making it highly versatile. Below is a detailed explanation of the advantages and disadvantages of using Playwright.



Advantages of Playwright Automation Tool

1. Cross-Browser Support
  • Playwright supports Chromium (Chrome, Edge)Firefox, and WebKit (Safari) with a single API, making it easy to run the same test across multiple browsers.

  • Great for ensuring consistent behavior across different platforms.

2. Headless and Headed Modes

  • Tests can be run in headless mode for faster execution (CI/CD).

  • Headed mode is available for debugging and local development.

3. Auto-Wait Mechanism

  • Playwright automatically waits for elements to be ready, like being visible, enabled, or stable before performing actions.

  • Reduces flaky tests significantly without manually writing waits or sleeps.

4. Multiple Language Support

  • Official support for:

    • JavaScript/TypeScript

    • Python

    • C# (.NET)

    • Java

5. Parallel Test Execution

  • Playwright Test runner supports parallel execution at the file, project, and even test level.

  • Drastically reduces test execution time in CI pipelines.

6. Multiple Contexts / Browser Sessions

  • Allows creating isolated browser contexts (like incognito sessions).

  • Useful for testing multi-user scenarios in the same test run.

7. Powerful Tracing and Debugging Tools

  • Provides tracing with screenshots, videos, logs, and DOM snapshots.

  • Helps developers diagnose failures efficiently.

8. Network Interception and Mocking

  • Can intercept HTTP requests/responses, modify them, or mock API data.

  • Useful for testing front-end components independently from backend systems.

9. Mobile Emulation and Geolocation

  • Supports mobile device emulation, including device viewport sizes, user agents, and touch events.

  • Simulate geolocationpermissionsoffline mode, etc.

10. Component Testing

  • With Playwright Test, component testing can be performed (especially with React, Vue, etc.).


Disadvantages of Playwright Automation Tool

1. Relatively New Compared to Selenium

  • Playwright is newer than tools like Selenium, meaning:

    • Smaller community.

    • Fewer third-party plugins or integrations.

    • Less documentation for edge-case scenarios.

2. Steep Learning Curve for Beginners

  • Advanced features like contexts, network mocking, and tracing require deeper understanding.

  • New testers or QA professionals may find the learning curve steep.

3. No Native Support for Non-Web Applications

  • Playwright is strictly for web automation.

  • It does not support desktop, mobile (native), or hybrid apps.

4. Larger Bundle Size

  • Playwright downloads browser binaries by default, which increases installation time and disk usage (~500MB+).

  • Can be problematic in constrained CI environments or Docker containers.

5. Limited Built-in Test Runner Flexibility

  • While the Playwright Test runner is powerful, it lacks some advanced features of mature runners like JUnit, TestNG, or NUnit.

  • Complex reporting or dependency injection may need external integration.

6. No Built-in Record-and-Playback

  • Unlike Selenium IDE or Cypress Recorder, Playwright lacks a native visual recording tool (though community tools may exist).

7. WebKit Testing May Not Be Fully Reliable

  • Since WebKit is primarily maintained by Apple, Playwright uses a custom build for automation, which may behave differently than Safari on macOS/iOS in rare cases.


At a glance:


FeaturePlaywright AdvantagePossible Drawback
Cross-browser supportChromium, Firefox, WebKit via same APIWebKit not always identical to Safari
Language supportJavaScript, Python, C#, JavaSome APIs are JS-centric
Auto-waitReduces flaky testsRequires understanding of lifecycle
Debugging toolsBuilt-in tracing, screenshot, videoAdds overhead in test run size
Network mockingEasy API mocking for frontend testsSlightly complex to configure initially
CommunityGrowing and backed by MicrosoftSmaller than Selenium's community
CI/CD integrationFirst-class supportNeeds browser setup in CI runners

When to Use Playwright

  • Testing modern web apps with dynamic content (e.g., React, Angular, Vue).

  • Cross-browser testing without separate frameworks.

  • Complex scenarios needing multiple browser contexts or user roles.

  • Performance-sensitive test pipelines (fast, parallel execution).


When Not to use Playwright

  • Automating non-web applications.

  • Projects requiring a large ecosystem of plugins/tools.

  • Teams heavily invested in tools like Selenium with lots of legacy scripts.


Suggested Posts:

1. First Script in Playwright
2. Playwright Architecture
3. Maximize Window in Playwright
4. Handle Alerts in Playwright
5. Find Web Elements by XPath in Playwright

Selenium vs Playwright

 

Below is the detailed comparison of Playwright and Selenium which are two popular open-source web automation tools.


Selenium

Selenium is one of the oldest and most widely used web automation frameworks. It supports multiple programming languages such as Java, Python, C#, Ruby, and JavaScript, and works across many browsers. Selenium operates using the WebDriver protocol, which communicates with browsers to perform actions like clicking, typing, or navigating. 

It has a large community, strong ecosystem, and compatibility with many third-party tools like TestNG, JUnit, or Maven. However, Selenium often requires explicit waits to handle dynamic content, and test execution can sometimes be slower compared to modern frameworks. 

Its biggest advantage is its maturity, stability, and wide industry adoption.


Playwright

Playwright is a relatively newer automation framework developed by Microsoft. It supports JavaScript/TypeScript, Python, Java, and .NET. Unlike Selenium, Playwright does not rely on WebDriver; it directly communicates with browsers using native DevTools protocols, which makes it faster and more reliable. Playwright provides built-in auto-waiting mechanisms, making it easier to handle dynamic web applications without adding many explicit waits. 

It also has advanced features like intercepting network requests, handling multiple browser contexts, working with iframes, and supporting modern browsers including Chromium, Firefox, and WebKit. 

Additionally, Playwright supports parallel execution and cross-browser testing out of the box. Its modern design makes it well-suited for today’s single-page applications.



















FeaturePlaywrightSelenium
ArchitectureModern, browser automation through WebSocket protocolTraditional, uses WebDriver protocol
Languages SupportedJavaScript, TypeScript, Python, C#, JavaJava, Python, C#, Ruby, JavaScript, Kotlin, etc.
Browsers SupportedChromium, Firefox, WebKit (Safari engine)Chrome, Firefox, Safari, IE, Edge
Cross-browser TestingYes (via single API)Yes (via WebDriver, requires separate drivers)
Headless ModeBuilt-in for all browsersSupported but configuration-heavy
Mobile EmulationBuilt-in (Android/iOS simulation)Supported via Chrome DevTools or Appium
Multi-tab/Context SupportExcellent (isolated browser contexts)Limited (each tab requires handling in a new driver instance)
Auto-wait for ElementsYes (automatic waiting for DOM/state readiness)Manual waits often needed (e.g., WebDriverWait)
Screenshots/VideosBuilt-in support for screenshots, videos, and tracesScreenshots supported, video needs external integration
Debugging ToolsBuilt-in tracing, time-travel debuggingBasic logs, stack traces, external tools needed for deep debug
Execution SpeedFaster (uses WebSocket and optimized browser contexts)Slower (uses HTTP/WebDriver protocol)
Parallel ExecutionBuilt-in support (workers, test sharding)Needs external config (e.g., Selenium Grid, TestNG parallel)
Ease of SetupEasy, single binary for all supported browsersComplex, needs drivers for each browser
CI/CD IntegrationGood support (GitHub Actions, Jenkins, etc.)Excellent support and maturity



Final Take:

Use Playwright for modern, high-speed automation with features like auto-wait, parallel testing, and browser context isolation.

Use Selenium for broad browser compatibility (example: legacy IE), or if you already have a mature Selenium-based infrastructure.


Suggested Posts:

1. First Script in Playwright
2. Automate GET API in Playwright
3. Comma Selectors in Playwright
4. Handle Alerts in Playwright
5. Find Web Elements by XPath in Playwright

Automate Google.com by Playwright

 

To automate https://www.google.com using Playwright with Java, you can perform the following basic steps:


1. Set up Playwright Environment

  • First, you would need to install Playwright and configure it for your preferred programming language (Java, JavaScript/TypeScript, Python, etc.).
  • Playwright provides browsers like Chromium, Firefox, and WebKit, which can be used to open and interact with Google.

2. Launch the Browser
  • Playwright allows launching a browser instance in either headless mode (without GUI) or headed mode (with GUI).
  • For automation, you typically start a new browser session to ensure a clean state.
3. Create a Browser Context
  • A BrowserContext is like a separate user profile, with its own cookies, cache, and session data.
  • Using contexts helps in isolating tests so that actions on one context don’t affect another.
  • For example, if you open Google in one context, it won’t share login data with another context unless you configure it.
4. Navigate to Google.com
  • You instruct Playwright to open the URL https://www.google.com
  • Playwright waits until the page loads and becomes interactive.
5. Locate the Search Box
  • Playwright uses selectors (like CSS selectors, XPath, text selectors) to find elements on a page.
  • The Google search box is a standard input field, so automation involves locating it.
6. Type a Search Query
  • After finding the search box, Playwright can simulate user actions: Typing text into the box (e.g., “Playwright automation”), Adding key presses like Enter to submit the search.
7. Interact with Search Results
  • Once Google displays results, Playwright can: Locate all result links, Click on the first result or verify that certain text is present, Extract text from search results for validation.
8. Handle Dynamic Behavior
  • Google search results often load dynamically, so Playwright’s auto-waiting ensures it waits for elements to be ready before interacting.
  • For example, it won’t try to click a result before the page is fully interactive.
9. Perform Additional Actions
  • You can automate actions beyond just searching: Navigate to the Images or News tab, open links in new tabs, validate page titles or URLs to confirm successful navigation.
10. Close Browser
  • At the end of the automation, Playwright closes the browser or context to free resources.


























Website to be automated: https://www.google.com












Maven Dependencies


<dependencies>
    <dependency>
        <groupId>com.microsoft.playwright</groupId>
        <artifactId>playwright</artifactId>
        <version>1.44.0</version> <!-- Use latest if available -->
    </dependency>
</dependencies>


Java Code to Automate Google Search


import com.microsoft.playwright.*;

public class GoogleAutomation {
    public static void main(String[] args) {
        // Step 1: Launch Playwright and Browser
        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));

            // Step 2: Create a new browser context and page
            BrowserContext context = browser.newContext();
            Page page = context.newPage();

            // Step 3: Navigate to Google
            page.navigate("https://www.google.com");

            // Step 4: Accept cookies if visible (optional step depending on location)
            Locator acceptButton = page.locator("button:has-text('I agree'), button:has-text('Accept all')");
            if (acceptButton.isVisible()) {
                acceptButton.click();
            }

            // Step 5: Type a query into the search box
            page.locator("[name='q']").fill("Playwright Java");

            // Step 6: Press Enter to search
            page.keyboard().press("Enter");

            // Step 7: Wait for results to load and print titles
            page.waitForSelector("h3");  // wait for results

            System.out.println("Top Search Results:");
            for (Locator result : page.locator("h3").all()) {
                System.out.println(result.textContent());
            }

            // Step 8: Close browser
            browser.close();
        }
    }
}


Code Explanation:


StepDescription
Playwright.create()Initializes Playwright engine.
browser.newContext()Creates a new browser context (like an incognito window).
page.navigate()Navigates to the URL.
page.locator("[name='q']")Finds the search box on Google using the name attribute.
keyboard().press("Enter")Simulates pressing Enter to submit the form.
locator("h3")Search results on Google usually appear under <h3> tags.


Suggested Posts:

1. BrowserContext in Playwright
2. Automate GET API in Playwright
3. Comma Selectors in Playwright
4. Handle Alerts in Playwright
5. Find Web Elements by XPath in Playwright