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