How to Test POST API by Playwright


















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

In modern web development and automation testing, APIs play a crucial role in enabling communication between different applications. Whether you are working on a web application, mobile app, or enterprise system, APIs help send and receive data between client and server.

Among all HTTP methods, POST API is one of the most important and widely used methods because it allows users to send data to the server.

In this detailed guide, you will learn:

  • What is a POST API?

  • How POST API works

  • Difference between GET and POST API

  • Real-world examples of POST API

  • How to test POST API using Playwright Java

  • Step-by-step explanation with code

  • How to validate status code, response body, and headers

  • Best practices for POST API automation testing

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


What Is a POST API?

A POST API is an HTTP request method used to send data from a client to a server so that the server can process the data and usually create a new resource.

Unlike a GET API, which only retrieves data, a POST API is used to:

  • Create new records

  • Submit form data

  • Upload files

  • Send login credentials

  • Perform transactions

In simple terms:

GET = Fetch data
POST = Send data to server


Key Characteristics of POST API

Here are the main features of a POST API:

  • Used to submit data to the server

  • Often creates a new resource

  • Data is sent in the request body

  • Not idempotent (multiple calls may create multiple records)

  • More secure than GET for sensitive data (data not visible in URL)


Real-World Examples of POST API

POST APIs are everywhere in real-world applications. Some common examples include:

1. User Registration

When you create a new account on a website, your details (name, email, password) are sent using a POST API.

2. Login Form

Username and password are sent to the server via POST request for authentication.

3. Placing an Order

In e-commerce applications, placing an order sends cart details using POST.

4. File Upload

Uploading documents or images uses POST API.

5. Creating Blog Post

When you publish a new article in CMS, a POST request creates that record in database.


How POST API Works

Here is the basic flow:

  1. Client sends POST request to server.

  2. Request includes:

    • Endpoint URL

    • Headers (e.g., Content-Type)

    • Request body (JSON, form-data, etc.)

  3. Server processes the request.

  4. Server returns a response with:

    • Status code

    • Response body

    • Headers


Common Status Codes for POST API

When testing POST API, you should know common response codes:

Status CodeMeaning
200Success
201Resource Created
400Bad Request
401Unauthorized
403Forbidden
500Internal Server Error

For successful creation, the most common status code is 201 Created.


Difference Between GET and POST API

Understanding the difference is very important for interviews and real projects.

FeatureGET APIPOST API
PurposeRetrieve dataSend/Create data
Data LocationURLRequest Body
SecurityLess secureMore secure
IdempotentYesNo
CacheableYesUsually No


How to Test POST API Using Playwright Java

Many testers think Playwright is only for UI automation. However, Playwright also provides powerful API testing capabilities.

Using Playwright Java, you can:

  • Send POST requests

  • Send GET requests

  • Send PUT requests

  • Send DELETE requests

  • Validate response

  • Integrate API and UI testing

And the best part? No browser is required for API testing.


Steps to Test a POST API Using Playwright Java

Let’s understand step-by-step how to automate a POST API using Playwright in Java.

We will test this fake public API:

Endpoint:

https://jsonplaceholder.typicode.com/posts

Method:

POST


Sample JSON Payload

Below is the request body we will send:

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

This payload simulates creating a new post.


Step 1: Add Maven Dependency

Add Playwright dependency in your pom.xml file:

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

Always use the latest stable version.


Step 2: Java Code to Test POST API

Below is the complete working example:

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 (Step-by-Step)

Let’s break the code into simple parts.


(a) Create APIRequestContext

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

This creates a context to send HTTP requests without launching a browser.


(b) Define the Payload

Map<String, Object> payload = new HashMap<>();

We create a map and add key-value pairs to simulate JSON data.


(c) Send POST Request

requestContext.post()

This method sends POST request with:

  • Endpoint URL

  • Headers

  • Request body


(d) Validate Response

We validate:

  • Status code

  • Response body

  • Success condition

Expected status code for successful creation = 201


(e) Close Context

requestContext.dispose();

Always close context to free resources.


Expected Output

When executed successfully, output will be:

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

Status code 201 confirms that the resource was created successfully.


How to Validate Response Using JSONObject

You can validate JSON fields using JSONObject:

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

This ensures:

  • Correct data is returned

  • API contract is maintained

  • Response values are accurate


How to Validate Response Headers

Headers validation is important.

Example:

String contentType = response.headers().get("content-type"); System.out.println("Content-Type: " + contentType);

Expected:

application/json


How to Measure Response Time

Performance testing is essential.

Example:

long start = System.currentTimeMillis(); APIResponse response = requestContext.post("URL", options); long end = System.currentTimeMillis(); System.out.println("Response Time: " + (end - start) + " ms");

You can define threshold like:

  • Response should be under 2000 ms


Integration of API and UI Testing

One powerful use case of Playwright:

Step 1:

Use POST API to create a new user.

Step 2:

Launch browser using Playwright.

Step 3:

Login using that newly created user.

Step 4:

Validate UI displays correct data.

This approach makes test automation faster and more reliable.


Best Practices for POST API Testing

Here are some professional tips:

1. Always Validate Status Code

Never assume success.

2. Validate Response Body

Ensure correct fields and values.

3. Test Negative Scenarios

Test invalid payloads.
Test missing required fields.
Test unauthorized access.

4. Use Assertions Framework

Integrate with TestNG or JUnit.

5. Store Base URL in Config

Avoid hardcoding URLs.


Common Interview Questions on POST API

  1. What is POST API?

  2. What is difference between GET and POST?

  3. What status code is returned when resource is created?

  4. How do you test POST API?

  5. How do you validate response body?

  6. How to automate API testing using Playwright?

If you are preparing for automation interviews, mastering POST API testing is extremely important.


Advantages of API Testing

  • Faster than UI testing

  • More stable

  • Detects backend issues early

  • Useful in microservices architecture

  • Supports continuous integration pipelines

Modern automation frameworks always include API testing.


Conclusion

A POST API is used to send data from client to server, typically to create new resources. Testing POST APIs ensures that backend services process data correctly, securely, and efficiently.

Using Playwright Java, you can:

  • Send POST requests

  • Pass JSON payloads

  • Validate status codes

  • Validate response body

  • Check headers

  • Measure performance

  • Combine API and UI testing

Playwright provides a powerful and modern solution for automation engineers who want both UI and API testing in a single framework.


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? Complete Guide to GET API Testing Using Playwright Java

In modern software development, APIs (Application Programming Interfaces) play a crucial role in enabling communication between different systems. Whether you are building a web application, mobile app, or enterprise software, APIs help exchange data seamlessly.

One of the most commonly used HTTP methods in API communication is the GET API.

In this detailed guide, you will learn:

  • What is a GET API?

  • How GET API works

  • Real-world examples of GET APIs

  • How to test a GET API using Playwright Java

  • Maven dependency setup

  • Java code example with explanation

  • How to validate status code, response body, headers, and performance

  • Why Playwright is powerful for API testing

This article is fully SEO optimized, beginner-friendly, and written in a human-like format for better readability and AdSense compliance.


What Is a GET API?

A GET API is an HTTP request method used to retrieve data from a server. It is designed to fetch information without modifying or updating any data on the server.

In simple terms:

GET = Fetch data only
It does not insert, update, or delete anything.

Key Characteristics of GET API

  • Used to retrieve data

  • Does not change server data

  • Safe and idempotent

  • Can be cached

  • Parameters are usually sent in the URL

Example of GET API

If you open this URL in your browser:

https://jsonplaceholder.typicode.com/users

The server responds with user data in JSON format.

This is a simple example of a GET API call where data is retrieved but not modified.


Real-World Examples of GET API

Here are some common real-world examples:

  • Getting user details by ID

  • Fetching product listings in an e-commerce app

  • Retrieving weather data

  • Getting bank transaction history

  • Fetching blog posts from a content platform

Almost every modern application uses GET APIs extensively.


What Does GET API Testing Mean?

When we test a GET API, we verify that:

  1. The API returns the correct status code (e.g., 200 OK)

  2. The response body contains expected data

  3. The response time is within acceptable limits

  4. The headers are correct (e.g., Content-Type: application/json)

  5. The data structure matches the API contract

API testing ensures that backend services are working correctly before they are integrated with frontend UI.


How to Test GET API Using Playwright Java

Many people think Playwright is only for UI automation. However, Playwright also provides powerful API testing capabilities.

With Playwright, you can:

  • Send GET requests

  • Send POST requests

  • Send PUT requests

  • Send DELETE requests

  • Validate response data

  • Test performance

And all this without opening a browser.


Why Use Playwright for API Testing?

Here are some strong reasons:

1. Unified Automation Framework

You can test both UI and API in the same project. No need for separate tools.

2. Faster Execution

API tests are much faster than UI tests because no browser is launched.

3. Pre-Test Data Setup

You can create or fetch test data using API before running UI automation.

Example scenario:

  • Use API to create a user

  • Use UI test to log in with that user

  • Validate UI displays correct data

4. Backend Validation

You can compare UI data with API data to ensure consistency.


Steps to Test a GET API Using Playwright Java

Let’s understand step-by-step how to test a GET API using Playwright in Java.

We will test this public API:

https://jsonplaceholder.typicode.com/posts/1


Step 1: Add Maven Dependency

First, add Playwright dependency in your pom.xml.

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

Always use the latest stable version available.


Step 2: Java Code to Test GET API

Here is a complete example:

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 response status System.out.println("Status: " + response.status()); System.out.println("Status Text: " + response.statusText()); // Step 5: Get response body String responseBody = response.text(); System.out.println("Response Body:\n" + responseBody); // Optional validation if (response.ok()) { System.out.println("API responded successfully."); } else { System.out.println("API test failed."); } // Close context requestContext.dispose(); } } }


Code Explanation (Step-by-Step)

Let’s break it down for better understanding.

(a) Initialize Playwright

Playwright playwright = Playwright.create();

This starts the Playwright engine.


(b) Create APIRequestContext

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

This context allows you to send HTTP requests without opening a browser.


(c) Send GET Request

APIResponse response = requestContext.get("API_URL");

This sends a GET request to the specified endpoint.


(d) Validate Response Status

response.status();

Expected status for success = 200


(e) Validate Response Body

response.text();

Extracts JSON response as a string.


(f) Optional Assertion

response.ok();

Returns true if status code is between 200–299.


(g) Close API Context

requestContext.dispose();

Closes request context to avoid memory leaks.


Expected Output

When executed successfully, output will look like:

Status: 200 Status Text: OK Response Body: { "userId": 1, "id": 1, "title": "...", "body": "..." } API responded successfully.

Status code 200 means the API returned a successful response.


How to Validate Specific JSON Fields

To validate response fields, you can use JSONObject.

Example:

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

This ensures:

  • Correct ID is returned

  • Data matches expected value

  • API contract is maintained


How to Validate Response Headers

Headers are important in API testing.

Example:

String contentType = response.headers().get("content-type"); System.out.println("Content-Type: " + contentType);

Expected:

application/json


How to Validate Response Time

Performance is critical in real applications.

You can measure response time like this:

long startTime = System.currentTimeMillis(); APIResponse response = requestContext.get("API_URL"); long endTime = System.currentTimeMillis(); System.out.println("Response Time: " + (endTime - startTime) + " ms");

You can set threshold like:

  • API should respond within 2000 ms


Best Practices for GET API Testing

Here are some professional tips:

1. Always Validate Status Code

Do not assume API is successful.

2. Validate Response Schema

Ensure response structure matches API documentation.

3. Validate Edge Cases

Test:

  • Invalid ID

  • Non-existing resource

  • Unauthorized access

4. Use Assertions

Integrate with TestNG or JUnit for structured testing.

5. Avoid Hardcoding

Store base URL and endpoints in configuration files.


Difference Between GET and Other HTTP Methods

MethodPurpose
GETRetrieve data
POSTCreate data
PUTUpdate data
DELETERemove data

GET is read-only and should not modify server state.


Advantages of API Testing Over UI Testing

  • Faster execution

  • More stable

  • No dependency on UI changes

  • Early bug detection

  • Backend validation before UI integration

In professional automation projects, API testing is always recommended alongside UI automation.


When Should You Use GET API Testing?

You should use GET API testing when:

  • Verifying data retrieval

  • Validating backend business logic

  • Checking integration between services

  • Testing microservices architecture

  • Validating database data exposure


Common Interview Questions on GET API Testing

  1. What is GET API?

  2. What is idempotent HTTP method?

  3. How do you validate API response?

  4. How do you test API performance?

  5. Difference between GET and POST?

  6. How to test API using Playwright?

If you are preparing for automation interviews (especially in Java-based frameworks), mastering Playwright API testing is highly beneficial.


Conclusion

A GET API is one of the most fundamental and widely used HTTP methods for retrieving data from a server. Testing GET APIs ensures that backend services return correct, reliable, and performant responses.

Using Playwright Java, you can:

  • Send GET requests easily

  • Validate status codes

  • Validate JSON response

  • Check headers

  • Measure performance

  • Integrate API tests with UI automation

Playwright provides a powerful and lightweight approach to API automation testing, making it a great choice for modern QA engineers and automation testers.


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