Modern applications rely heavily on APIs to exchange data between frontend and backend systems. While Playwright is widely known for browser automation, it also provides powerful built-in support for API testing.
This means you can automate both UI tests and REST API tests using the same framework, reducing the need for separate tools in many automation projects.
In this tutorial, you'll learn how to perform API testing in Playwright using Java with practical examples.
Why Use Playwright for API Testing?
Playwright provides a built-in HTTP client that supports:
- GET requests
- POST requests
- PUT requests
- PATCH requests
- DELETE requests
- Authentication
- Custom headers
- Query parameters
- Response validation
Using one framework for both UI and API testing simplifies project maintenance and reduces dependencies.
Creating an API Request Context
Playwright uses an APIRequestContext to send HTTP requests.
Example:
Playwright playwright = Playwright.create();
APIRequestContext request =
playwright.request().newContext();The request context acts as the client for all API operations.
Sending a GET Request
Let's retrieve a list of users.
APIResponse response =
request.get("https://reqres.in/api/users?page=2");You can verify the response status:
System.out.println(response.status());Expected output:
200Reading the Response Body
To print the response content:
String body = response.text();
System.out.println(body);This returns the JSON response as a string.
Sending a POST Request
POST requests are commonly used to create resources.
Example:
String json = """
{
"name":"John",
"job":"QA Engineer"
}
""";
APIResponse response =
request.post(
"https://reqres.in/api/users",
RequestOptions.create()
.setData(json)
);Expected status:
201 CreatedSending a PUT Request
PUT requests update existing resources.
String updateJson = """
{
"name":"John",
"job":"Senior QA Engineer"
}
""";
APIResponse response =
request.put(
"https://reqres.in/api/users/2",
RequestOptions.create()
.setData(updateJson)
);Sending a DELETE Request
Deleting resources is equally simple.
APIResponse response =
request.delete(
"https://reqres.in/api/users/2"
);Expected response:
204 No ContentAdding Custom Headers
Many APIs require custom headers.
Example:
APIResponse response =
request.get(
"https://example.com/api/users",
RequestOptions.create()
.setHeader(
"Authorization",
"Bearer YOUR_TOKEN"
)
.setHeader(
"Content-Type",
"application/json"
)
);Sending Query Parameters
Suppose the API accepts pagination.
APIResponse response =
request.get(
"https://reqres.in/api/users?page=2"
);Alternatively, build URLs dynamically for different test scenarios.
Validating the Response
A good API test should verify more than the status code.
Example:
assert response.status() == 200;
assert response.text().contains("Michael");You can validate:
- Status code
- Response body
- Headers
- Response time
- Business data
Authentication
Many enterprise APIs use Bearer tokens.
Example:
APIRequestContext request =
playwright.request().newContext(
new APIRequest.NewContextOptions()
.setExtraHTTPHeaders(
Map.of(
"Authorization",
"Bearer YOUR_ACCESS_TOKEN"
)
)
);This automatically sends the token with every request.
Complete Example
Playwright playwright = Playwright.create();
APIRequestContext request =
playwright.request().newContext();
APIResponse response =
request.get(
"https://reqres.in/api/users?page=2"
);
System.out.println(
response.status()
);
System.out.println(
response.text()
);
request.dispose();
playwright.close();Best Practices
Reuse the API Request Context
Create one request context and reuse it throughout your test suite instead of creating a new one for every request.
Keep Test Data Separate
Store request payloads in JSON files instead of hardcoding them inside test classes.
Example:
testdata/
createUser.json
updateUser.jsonValidate Business Responses
Don't verify only the status code.
Also validate:
- Response fields
- Error messages
- IDs
- Dates
- Business rules
Use Environment Variables
Store:
- Base URL
- Tokens
- Credentials
inside configuration files rather than directly in code.
Common Interview Questions
Can Playwright perform API testing?
Yes.
Playwright includes a built-in HTTP client through APIRequestContext.
Which HTTP methods does Playwright support?
- GET
- POST
- PUT
- PATCH
- DELETE
Why use Playwright for API testing?
Because it allows teams to automate both UI and API tests using the same framework, improving consistency and reducing maintenance.
How do you authenticate API requests?
Use request headers with an Authorization token or configure default headers when creating the request context.
Conclusion
Playwright is much more than a browser automation framework. Its built-in API testing capabilities make it a powerful choice for modern automation engineers.
In this tutorial, you learned how to:
- Create an API request context
- Send GET, POST, PUT, and DELETE requests
- Validate responses
- Add authentication
- Use headers and query parameters
- Follow best practices for scalable API automation
By combining UI and API testing within the same Playwright project, you can build efficient, maintainable, and enterprise-ready automation frameworks.
No comments:
Post a Comment