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

No comments:

Post a Comment