1. Introduction
API testing is an important part of software quality assurance. Modern applications use APIs to exchange information between frontend applications, backend services, databases, and external systems.
Testing APIs helps QA engineers verify that requests are processed correctly and responses contain the expected information.
For example, when a user logs into an application, the frontend sends an authentication request to the backend. The backend validates the credentials and returns a response containing user information or an authentication token.
Instead of testing every operation through the browser, automation engineers can directly send HTTP requests and validate API responses.
Playwright Java API testing allows Java automation engineers to test REST APIs using Playwright’s official Java API request capabilities.
It supports HTTP methods such as:
- GET – Retrieve information.
- POST – Create new information.
- PUT – Replace an existing resource.
- PATCH – Partially update a resource.
- DELETE – Remove a resource.
Playwright Java also provides response validation, authentication headers, request configuration, and integration with Java test frameworks.
In this tutorial, you will learn how to create a complete API automation framework using Playwright Java, Maven, and JUnit. We will implement practical API examples, authentication, CRUD operations, reusable API clients, reporting, and CI/CD integration.
2. What Is Playwright Java API Testing?
Playwright Java API testing is the process of testing application programming interfaces using Playwright’s Java API request library.
A REST API allows applications to communicate using HTTP requests and responses.
For example, an application might expose the following endpoints:
| API endpoint | HTTP method | Purpose |
| /users | GET | Retrieve users |
| /users | POST | Create a user |
| /users/1 | GET | Retrieve one user |
| /users/1 | PUT | Replace user details |
| /users/1 | PATCH | Update selected user details |
| /users/1 | DELETE | Delete a user |
How Playwright Java API testing works
Java Test Script
JUnit / TestNG
Playwright APIRequestContext
Creates and manages HTTP requests
REST API Server
Processes HTTP requests
API Response
Status code, headers and response body
Assertions and Test Report
Validates expected API behavior
Playwright Java provides API testing independently of browser UI automation. This means you can test backend functionality without opening a browser.
Important distinction: Playwright Java uses Java classes such as APIRequest, APIRequestContext, and APIResponse. Its API testing syntax is different from the JavaScript and TypeScript Playwright Test API testing syntax.
3. Benefits of Playwright Java API Testing
API automation offers several advantages for QA teams.
| Benefit | Explanation |
| Faster feedback | Tests APIs without loading browser interfaces. |
| Backend validation | Verifies server-side business logic. |
| Integration testing | Checks communication between services. |
| Reliability | Avoids many UI-related synchronization issues. |
| Regression testing | Quickly validates existing API functionality. |
| Test data preparation | Creates test data for UI automation. |
| CI/CD integration | Supports automated API validation in pipelines. |
Why use Playwright instead of only UI testing?
Consider an e-commerce application.
To validate product creation, a tester could navigate through multiple UI pages, fill forms, and submit data.
Alternatively, an API test can send a POST request directly to the product endpoint and validate the response.
This reduces unnecessary browser interactions and allows teams to identify backend defects earlier.
4. Prerequisites and Maven Setup
Before starting the playwright java api testing tutorial, install the required development tools.
Prerequisites
| Tool | Purpose |
| JDK 17 | Java development |
| Maven | Dependency management |
| IntelliJ IDEA | Java IDE |
| Playwright Java | API request library |
| JUnit 5 | Test execution |
| REST API | Application under test |
Step 1: Create a Maven project
Create a project named:
PlaywrightJavaAPITesting
Step 2: Configure pom.xml
Add the following dependencies:
Add the following dependencies and plugins to complete the Maven configuration:
<properties>
<maven.compiler.release>17</maven.compiler.release>
<playwright.version>1.64.0</playwright.version>
<junit.version>5.13.4</junit.version>
<jackson.version>2.19.2</jackson.version>
</properties>
<dependencies>
<dependency>
<groupId>com.microsoft.playwright</groupId>
<artifactId>playwright</artifactId>
<version>${playwright.version}</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.14.1</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.5.4</version>
</plugin>
</plugins>
</build>
The versions above are pinned examples. Check compatibility with your build environment before upgrading.
Step 3: Install Maven dependencies
Run:
mvn clean install
Unlike browser UI testing, standalone API testing does not require installing Chromium or other browser binaries.
5. Understanding APIRequest, APIRequestContext, and APIResponse
Playwright Java provides three important classes for API automation.
APIRequest
APIRequest is responsible for creating API request contexts.
Example:
APIRequest request = playwright.request();
APIRequestContext
APIRequestContext sends HTTP requests and manages request configuration, headers, cookies, and authentication.
Example:
APIRequestContext api =
playwright.request().newContext();
APIResponse
APIResponse stores the response received from the API server.
It provides methods to retrieve:
- HTTP status code.
- Response headers.
- Response body.
- Success status.
Example:
APIResponse response = api.get(“/posts/1”);
System.out.println(response.status());
System.out.println(response.text());
Comparison
| Class | Responsibility |
| APIRequest | Creates request contexts |
| APIRequestContext | Sends HTTP requests |
| APIResponse | Provides response information |
You can create a standalone request context or use the request context associated with a browser context. Standalone contexts are particularly useful for independent API testing.
Playwright Java+1
6. First API Test: GET Request Using Playwright Java
Let’s create our first API test using the JSONPlaceholder public testing API.
Base URL:
This service provides sample REST API endpoints for practicing automation.
Create GetApiTest.java inside src/test/java/tests.
package tests;
import com.microsoft.playwright.*;
import org.junit.jupiter.api.*;
import static org.junit.jupiter.api.Assertions.*;
public class GetApiTest {
private Playwright playwright;
private APIRequestContext request;
@BeforeEach
void setUp() {
playwright = Playwright.create();
request = playwright.request().newContext(
new APIRequest.NewContextOptions()
.setBaseURL(
“https://jsonplaceholder.typicode.com”
)
);
}
@Test
void getPostTest() {
APIResponse response = request.get(“/posts/1”);
assertEquals(200, response.status());
System.out.println(response.text());
assertTrue(
response.text().contains(“userId”)
);
}
@AfterEach
void tearDown() {
if (request != null) {
request.dispose();
}
if (playwright != null) {
playwright.close();
}
}
}
Explanation
- Playwright.create() initializes Playwright.
- newContext() creates an API request context.
- setBaseURL() defines the API base URL.
- get() sends an HTTP GET request.
- status() retrieves the response status.
- text() retrieves the response body.
- dispose() releases API request resources.
Execute the test
mvn clean test
Expected result:
GetApiTest
getPostTest PASSED
Tests run: 1
Failures: 0
Errors: 0
The API should return HTTP status 200 and a JSON response containing post information.
7. HTTP Method Examples in Playwright Java
REST API automation requires testing different HTTP methods.
Let’s understand how to implement GET, POST, PUT, PATCH, and DELETE using Playwright Java.
A. GET request
GET retrieves existing information.
APIResponse response = request.get(“/posts/1”);
System.out.println(response.status());
System.out.println(response.text());
Expected status: 200 OK.
B. POST request
POST creates a new resource.
import java.util.HashMap;
import java.util.Map;
Map<String, Object> data = new HashMap<>();
data.put(“title”, “Playwright API Testing”);
data.put(“body”, “Learning Java API Automation”);
data.put(“userId”, 1);
APIResponse response = request.post(
“/posts”,
RequestOptions.create().setData(data)
);
System.out.println(response.status());
System.out.println(response.text());
Expected status: 201 Created.
C. PUT request
PUT replaces an existing resource.
Map<String, Object> data = new HashMap<>();
data.put(“id”, 1);
data.put(“title”, “Updated Title”);
data.put(“body”, “Updated Content”);
data.put(“userId”, 1);
APIResponse response = request.put(
“/posts/1”,
RequestOptions.create().setData(data)
);
System.out.println(response.status());
Expected status: 200 OK.
D. PATCH request
PATCH updates selected resource fields.
Map<String, Object> data = new HashMap<>();
data.put(“title”, “Partially Updated Title”);
APIResponse response = request.patch(
“/posts/1”,
RequestOptions.create().setData(data)
);
System.out.println(response.status());
System.out.println(response.text());
Expected status: 200 OK.
E. DELETE request
DELETE requests resource removal.
APIResponse response = request.delete(“/posts/1”);
System.out.println(response.status());
Expected status: 200 OK for this sample API.
HTTP method comparison
| Method | Operation | Typical success status |
| GET | Retrieve | 200 |
| POST | Create | 201 |
| PUT | Replace | 200 or 204 |
| PATCH | Partial update | 200 or 204 |
| DELETE | Delete | 200 or 204 |
The actual status codes depend on the API contract. JSONPlaceholder simulates write operations and does not permanently save changes. Its returned responses should not be treated as proof of persistent CRUD behavior.
8. API Response Validation and JSON Parsing
Validating only the status code is not enough for professional API automation.
You should also validate response content, headers, JSON fields, and business rules.
Validate response status
assertEquals(200, response.status());
Validate response body
Jackson can parse JSON responses into Java objects.
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper mapper = new ObjectMapper();
JsonNode json = mapper.readTree(response.text());
assertEquals(1, json.get(“id”).asInt());
assertEquals(
“sunt aut facere repellat provident occaecati”,
json.get(“title”).asText().substring(0, 49)
);
For a simpler validation:
assertTrue(json.has(“userId”));
assertTrue(json.has(“title”));
assertTrue(json.has(“body”));
Validate response headers
String contentType =
response.headers().get(“content-type”);
assertNotNull(contentType);
assertTrue(
contentType.contains(“application/json”)
);
Important response validation areas
- HTTP status code.
- Response body structure.
- Required JSON fields.
- Data types.
- Response headers.
- Business validation rules.
- Error messages.
9. Authentication Testing with Playwright Java
Many real-world REST APIs require authentication.
Common authentication mechanisms include:
- Bearer token authentication.
- Basic authentication.
- API keys.
- Cookie-based authentication.
Bearer token example
A bearer token is generally passed through the HTTP Authorization header.
import java.util.HashMap;
import java.util.Map;
Map<String, String> headers = new HashMap<>();
headers.put(
“Authorization”,
“Bearer ” + System.getenv(“API_TOKEN”)
);
headers.put(
“Accept”,
“application/json”
);
APIRequestContext authenticatedRequest =
playwright.request().newContext(
new APIRequest.NewContextOptions()
.setBaseURL(“https://api.example.com”)
.setExtraHTTPHeaders(headers)
);
APIResponse response =
authenticatedRequest.get(“/users”);
assertEquals(200, response.status());
authenticatedRequest.dispose();
Replace the example URL with your application’s actual API endpoint.
Important: Never hardcode production authentication tokens in Java source code or upload them to GitHub. Store credentials in environment variables or your CI/CD secret manager.
For negative authentication testing, send an invalid or missing token and validate the API’s documented 401 Unauthorized or 403 Forbidden response.
10. Real-World CRUD API Testing Using Playwright Java
CRUD stands for Create, Read, Update, and Delete. These operations are essential in enterprise API testing.
Let’s create a reusable API client to avoid repeating request logic in every test.
Step 1: Create ApiClient.java
package api;
import com.microsoft.playwright.*;
import java.util.HashMap;
import java.util.Map;
public class ApiClient {
private final Playwright playwright;
private final APIRequestContext request;
public ApiClient() {
playwright = Playwright.create();
request = playwright.request().newContext(
new APIRequest.NewContextOptions()
.setBaseURL(
“https://jsonplaceholder.typicode.com”
)
);
}
public APIResponse get(String endpoint) {
return request.get(endpoint);
}
public APIResponse post(
String endpoint,
Map<String, Object> data) {
return request.post(
endpoint,
RequestOptions.create().setData(data)
);
}
public APIResponse put(
String endpoint,
Map<String, Object> data) {
return request.put(
endpoint,
RequestOptions.create().setData(data)
);
}
public APIResponse patch(
String endpoint,
Map<String, Object> data) {
return request.patch(
endpoint,
RequestOptions.create().setData(data)
);
}
public APIResponse delete(String endpoint) {
return request.delete(endpoint);
}
public void close() {
request.dispose();
playwright.close();
}
}
Step 2: Create CRUD test
Create CrudApiTest.java.
package tests;
import api.ApiClient;
import com.microsoft.playwright.APIResponse;
import org.junit.jupiter.api.*;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
public class CrudApiTest {
private ApiClient api;
@BeforeEach
void setUp() {
api = new ApiClient();
}
@Test
void crudOperationsTest() {
Map<String, Object> data = new HashMap<>();
data.put(“title”, “Java API Testing”);
data.put(“body”, “Playwright Automation”);
data.put(“userId”, 1);
// CREATE
APIResponse create =
api.post(“/posts”, data);
assertEquals(201, create.status());
System.out.println(“CREATE: ” + create.text());
// READ
APIResponse read =
api.get(“/posts/1”);
assertEquals(200, read.status());
// UPDATE
data.put(“title”, “Updated API Testing”);
APIResponse update =
api.put(“/posts/1”, data);
assertEquals(200, update.status());
// PARTIAL UPDATE
Map<String, Object> patchData = new HashMap<>();
patchData.put(“title”, “Patched Title”);
APIResponse patch =
api.patch(“/posts/1”, patchData);
assertEquals(200, patch.status());
// DELETE
APIResponse delete =
api.delete(“/posts/1”);
assertEquals(200, delete.status());
}
@AfterEach
void tearDown() {
if (api != null) {
api.close();
}
}
}
Expected result
CREATE: 201
READ: 200
UPDATE: 200
PATCH: 200
DELETE: 200
Tests run: 1
Failures: 0
This example demonstrates the HTTP CRUD operations. Because JSONPlaceholder simulates write operations, the GET operation reads an existing sample post rather than verifying persistence of the newly created post. In a real application, use the ID returned by POST and verify the created resource through the backend.
11. API Testing with JUnit 5 and Test Framework Integration
JUnit 5 helps organize API tests using lifecycle annotations.
| Annotation | Purpose |
| @BeforeAll | Runs once before all tests |
| @BeforeEach | Runs before every test |
| @Test | Defines an API test |
| @AfterEach | Runs after every test |
| @AfterAll | Runs once after all tests |
For small test suites, the previous @BeforeEach and @AfterEach approach is suitable.
For larger suites, use reusable API clients and configuration classes.
You can also integrate Playwright Java API testing with TestNG using @BeforeMethod, @Test, and @AfterMethod.
Parallel execution consideration: Create independent Playwright instances and API request contexts for each parallel test thread. Do not share Playwright objects between threads.
12. Integrating API Testing with UI Automation
One important advantage of Playwright is that API testing and browser automation can be combined in the same Java framework.
Consider an e-commerce application.
You need to test whether a newly created customer can log in and access the dashboard.
Instead of creating the customer through the UI, you can:
- Create the customer through an API request.
- Launch the browser.
- Open the application.
- Log in with the created customer’s credentials.
- Validate the dashboard.
Playwright also supports sharing authentication cookies between an API request context and browser context when you use the associated request context.
For example:
APIRequestContext api =
playwright.request().newContext();
BrowserContext browserContext =
browser.newContext();
APIRequestContext browserRequest =
browserContext.request();
The browser-associated request context shares its cookie storage with the browser context. A standalone API context does not automatically share browser cookies.
Playwright Java+1
This approach reduces repetitive UI setup and makes end-to-end regression tests faster.
13. Reporting and Debugging
Reporting helps QA engineers understand which API tests passed or failed.
JUnit 5 can generate test execution information through Maven Surefire.
Important debugging information includes:
- Request URL and HTTP method.
- Response status.
- Response headers.
- Response body.
- Exception messages.
- Execution time.
For debugging, add:
System.out.println(“Status: ” + response.status());
System.out.println(“Body: ” + response.text());
System.out.println(“Headers: ” + response.headers());
Avoid logging passwords, bearer tokens, or sensitive customer information.
You can also use Maven Surefire reports:
target/surefire-reports/
These reports contain test execution results and failure information.
14. CI/CD Integration Using GitHub Actions
API tests should run automatically whenever developers push code or create pull requests.
Create:
.github/workflows/api-tests.yml
name: Playwright Java API Tests
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
api-tests:
runs-on: ubuntu-latest
steps:
– name: Checkout code
uses: actions/checkout@v6
– name: Setup Java
uses: actions/setup-java@v5
with:
distribution: temurin
java-version: ’17’
cache: maven
– name: Run API tests
run: mvn clean test
– name: Upload test reports
if: always()
uses: actions/upload-artifact@v4
with:
name: api-test-reports
path: target/surefire-reports/
For authenticated APIs, configure API_TOKEN as a GitHub Actions repository secret and expose it to the test step through an environment variable.
Jenkins can execute the same Maven command:
mvn clean test
Unlike browser automation, standalone API tests do not require browser installation, making CI execution simpler.
15. Best Practices and Common Mistakes
| Best practice | Recommendation |
| Use reusable API clients | Avoid duplicate request code |
| Validate response bodies | Do not depend only on status codes |
| Use environment variables | Protect authentication credentials |
| Dispose request contexts | Prevent resource leaks |
| Use independent test data | Avoid test interference |
| Validate negative scenarios | Test invalid inputs and authorization |
| Configure timeouts | Prevent indefinitely waiting tests |
| Maintain API documentation | Keep endpoint contracts clear |
Common mistakes
1. Checking only status codes: A successful status does not guarantee correct business data.
2. Hardcoding tokens: Use environment variables and CI/CD secrets.
3. Ignoring cleanup: Always dispose of API request contexts and close Playwright.
4. Sharing request contexts across threads: Use independent contexts for parallel execution.
5. Confusing simulated APIs with real CRUD: Verify persistence against an application that actually stores changes.
16. Playwright Java API Testing Interview Questions and FAQs
Q1. What is Playwright Java API testing?
It is API automation using Playwright’s Java APIRequestContext to send HTTP requests and validate REST API responses.
Q2. What is APIRequestContext?
It is the Playwright Java class responsible for sending HTTP requests and managing request configuration, headers, and cookies.
Q3. What is the difference between APIRequest and APIRequestContext?
APIRequest creates request contexts, while APIRequestContext sends HTTP requests.
Q4. What is APIResponse?
APIResponse contains the response status, headers, and body returned by the server.
Q5. Which HTTP methods does Playwright Java support?
GET, POST, PUT, PATCH, DELETE, and HEAD, among other request capabilities.
Q6. How do you validate an API response?
Use status(), text(), headers(), and a JSON parser such as Jackson with JUnit assertions.
Q7. How do you implement bearer token authentication?
Add an Authorization header containing Bearer followed by the token.
Q8. Can Playwright Java perform API and UI testing together?
Yes. API requests can prepare test data and validate backend conditions while Playwright browser contexts perform UI testing.
Q9. Does Playwright Java require browser installation for API testing?
No. Standalone API request contexts can execute without launching a browser.
Q10. How do you execute API tests using Maven?
Run:
mvn clean test
Q11. Is Playwright Java API testing suitable for beginners?
Yes. Beginners can start with GET requests, then learn POST, PUT, PATCH, DELETE, JSON validation, and authentication.
