1. Introduction to Playwright Python API Testing
API testing is an important part of modern software quality assurance. QA Engineers and SDETs use API testing to verify communication between applications, validate server responses, check business logic, and identify defects before they affect end users.
Traditionally, testers use tools such as Postman, Requests, and REST Assured for API automation. However, Playwright also provides built-in API testing capabilities through its APIRequestContext class.
Playwright Python API testing allows testers to send HTTP requests, validate responses, manage authentication, and combine API tests with browser automation using Python.
For example, consider an e-commerce application. Before testing the checkout page, you may need to create a customer or add a product through an API. Instead of performing every setup operation through the browser, you can use Playwright API requests to prepare the test data.
In this Playwright Python API testing tutorial, you will learn:
- API testing fundamentals.
- Playwright APIRequestContext.
- GET, POST, PUT, PATCH, and DELETE requests.
- Status code and JSON response validation.
- API authentication and authorization.
- Pytest fixtures and reusable API tests.
- Combining API testing with browser automation.
- Real-world API testing project implementation.
- Reporting, debugging, and CI/CD integration.
By the end, you will understand how to create a reusable API automation framework using Playwright Python.
2. What Is API Testing and Why Use Playwright?
API testing is the process of validating application programming interfaces to ensure that they work correctly.
An API allows two software applications or services to communicate with each other.
For example, when a user logs into an application, the frontend sends login credentials to an authentication API. The server validates the credentials and returns a response.
API testing verifies whether this communication works as expected.
Why use Playwright for API testing?
Playwright provides API testing capabilities through APIRequestContext.
Important benefits include:
- Supports HTTP methods such as GET, POST, PUT, PATCH, and DELETE.
- Validates HTTP status codes and response bodies.
- Supports authentication headers and cookies.
- Allows API and browser testing in one framework.
- Helps prepare test data before UI execution.
- Integrates with Pytest.
- Supports reusable request contexts.
Playwright is especially useful when QA teams want to combine API testing and end-to-end browser automation in the same Python project.
3. Prerequisites and Python Installation
Before starting Playwright Python API testing, install the following:
- Python 3.
- Basic Python programming knowledge.
- Playwright.
- Pytest.
- A REST API or test API endpoint.
- VS Code or another Python editor.
Step 1: Create a project
mkdir playwright-api-testing
cd playwright-api-testing
Step 2: Create a virtual environment
python -m venv venv
Activate it on Windows:
venv\Scripts\activate
On macOS or Linux:
source venv/bin/activate
Step 3: Install dependencies
pip install playwright pytest pytest-playwright
For browser-based tests, install browser binaries:
API-only tests do not require launching a browser or installing browser binaries.
Step 4: Create the project structure
playwright-api-testing/
│
├── tests/
│ ├── test_get.py
│ ├── test_post.py
│ └── test_users.py
│
├── conftest.py
├── pytest.ini
└── requirements.txt
4. Understanding APIRequestContext and APIRequest
Two important Playwright concepts are APIRequest and APIRequestContext.
What is APIRequest?
APIRequest provides methods to create API request contexts.
You can access it through:
playwright.request
Use new_context() to create a request context.
What is APIRequestContext?
APIRequestContext is responsible for sending HTTP requests and receiving API responses.
It provides methods such as:
- get()
- post()
- put()
- patch()
- delete()
- fetch()
Example:
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
request = p.request.new_context(
base_url=”https://jsonplaceholder.typicode.com”
)
response = request.get(“/users/1”)
print(response.status)
print(response.json())
request.dispose()
Understanding playwright.request.new_context()
The following code creates an independent API request context:
request = playwright.request.new_context(
base_url=”https://api.example.com”
)
You can configure common headers, authentication, and other request settings when creating the context.
There is another useful option: page.request or browser_context.request. These use the browser context’s associated API request context and share its cookie storage.
This is particularly useful when API testing and browser automation need to share authentication state.
Remember:
- playwright.request.new_context() creates an isolated request context.
- page.request uses the current browser context’s request context.
- request.dispose() releases the API request context and its stored response resources.
5. Sending GET, POST, PUT, PATCH, and DELETE Requests
REST APIs commonly use HTTP methods to perform different operations.
Let’s understand each method using the JSONPlaceholder public testing API.
Base URL:
A. GET request
GET retrieves information from an API.
response = request.get(“/users/1”)
print(response.status)
data = response.json()
print(data[“name”])
print(data[“email”])
B. POST request
POST creates a new resource.
response = request.post(
“/posts”,
data={
“title”: “Playwright API Testing”,
“body”: “Learning API automation”,
“userId”: 1
}
)
print(response.status)
print(response.json())
C. PUT request
PUT generally replaces or updates a resource.
response = request.put(
“/posts/1”,
data={
“id”: 1,
“title”: “Updated Title”,
“body”: “Updated Content”,
“userId”: 1
}
)
print(response.status)
print(response.json())
D. PATCH request
PATCH updates selected fields of a resource.
response = request.patch(
“/posts/1”,
data={
“title”: “New Post Title”
}
)
print(response.status)
print(response.json())
E. DELETE request
DELETE requests removal of a resource.
response = request.delete(“/posts/1”)
print(response.status)
JSONPlaceholder simulates write operations for practice; it does not persistently modify its underlying data.
These examples demonstrate the request syntax. In real projects, use your application’s API contract and verify the expected response codes and behavior.
6. Validating Status Codes, Headers, and JSON Responses
Sending an API request is only the first step. A good automation test must validate the response.
Status code validation
response = request.get(“/users/1”)
assert response.status == 200
Common HTTP status codes:
| Status | Meaning |
| 200 | OK |
| 201 | Created |
| 204 | No Content |
| 400 | Bad Request |
| 401 | Unauthorized |
| 403 | Forbidden |
| 404 | Not Found |
| 500 | Internal Server Error |
Header validation
response = request.get(“/users/1”)
headers = response.headers
assert “application/json” in headers.get(
“content-type”, “”
)
JSON response validation
response = request.get(“/users/1”)
data = response.json()
assert data[“id”] == 1
assert data[“name”] == “Leanne Graham”
assert “email” in data
Complete response validation
response = request.get(“/users/1”)
assert response.status == 200
data = response.json()
assert isinstance(data, dict)
assert data[“id”] == 1
assert data[“email”] != “”
For real applications, validate required fields, data types, business rules, and error responses rather than checking only the status code.
7. API Authentication, Tokens, and Request Headers
Many APIs require authentication before allowing access to protected resources.
Common authentication approaches include:
- Bearer token authentication.
- Basic authentication.
- API keys.
- Cookie-based authentication.
Bearer token authentication
A bearer token is generally passed through the Authorization header.
token = “YOUR_ACCESS_TOKEN”
request = p.request.new_context(
base_url=”https://api.example.com”,
extra_http_headers={
“Authorization”: f”Bearer {token}”,
“Accept”: “application/json”
}
)
Send an authenticated request:
response = request.get(“/api/users”)
assert response.status == 200
Never hardcode real authentication tokens in source code.
Use environment variables instead:
import os
token = os.getenv(“API_TOKEN”)
if not token:
raise RuntimeError(“API_TOKEN is not configured”)
Basic authentication
request = p.request.new_context(
base_url=”https://api.example.com”,
http_credentials={
“username”: “testuser”,
“password”: “testpassword”
}
)
Use test credentials only in authorized environments.
8. Using API Testing with Pytest and Fixtures
Pytest is a popular Python test runner used for API automation and regression testing.
Fixtures help create reusable resources that can be shared across multiple tests.
Step 1: Create conftest.py
import pytest
from playwright.sync_api import Playwright
@pytest.fixture(scope=”session”)
def api_request_context(playwright: Playwright):
request = playwright.request.new_context(
base_url=”https://jsonplaceholder.typicode.com”
)
yield request
request.dispose()
This fixture creates one API request context for the test session and disposes of it after the tests finish.
Step 2: Create test_users.py
def test_get_user(api_request_context):
response = api_request_context.get(“/users/1”)
assert response.status == 200
data = response.json()
assert data[“id”] == 1
assert data[“username”] == “Bret”
def test_get_posts(api_request_context):
response = api_request_context.get(“/posts”)
assert response.status == 200
data = response.json()
assert len(data) > 0
Step 3: Run tests
pytest -v
pip install pytest-html
pytest –html=report.html –self-contained-html
For API projects using pytest-playwright, the playwright fixture is provided by the plugin. It can be used to create and manage API request contexts.
9. Combining API Testing with Browser Automation
One major advantage of Playwright is that it supports API testing and browser automation within the same framework.
Consider an e-commerce application.
Before testing the checkout page, you need to create test data through an API.
You can create a user or prepare application state through API requests and then verify the result through the browser.
Example:
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
request = p.request.new_context(
base_url=”https://api.example.com”
)
response = request.post(
“/api/users”,
data={
“name”: “Test User”,
“email”: “test@example.com”
}
)
assert response.status == 201
user = response.json()
browser = p.chromium.launch()
page = browser.new_page()
page.goto(“https://example.com/users”)
expect(
page.get_by_text(user[“name”])
).to_be_visible()
browser.close()
request.dispose()
This is an illustrative integration example. The API endpoint, response contract, and UI must belong to the same application.
Benefits of combining API and UI testing
- Faster test data preparation.
- Reduced repetitive UI interactions.
- Better end-to-end validation.
- Easier regression testing.
- Reusable authentication state.
- Better coverage of application workflows.
10. Complete Real-World API Testing Project
Let’s organize a small API automation project using Playwright and Pytest.
api-automation/
│
├── tests/
│ └── test_api.py
│
├── conftest.py
├── pytest.ini
└── requirements.txt
conftest.py
import pytest
@pytest.fixture(scope=”session”)
def api_request_context(playwright):
request = playwright.request.new_context(
base_url=”https://jsonplaceholder.typicode.com”,
extra_http_headers={
“Accept”: “application/json”
}
)
yield request
request.dispose()
test_api.py
from playwright.sync_api import expect
def test_get_user(api_request_context):
response = api_request_context.get(“/users/1”)
assert response.status == 200
data = response.json()
assert data[“id”] == 1
assert data[“name”] == “Leanne Graham”
def test_create_post(api_request_context):
response = api_request_context.post(
“/posts”,
data={
“title”: “API Testing”,
“body”: “Playwright Python”,
“userId”: 1
}
)
assert response.status == 201
data = response.json()
assert data[“title”] == “API Testing”
assert data[“userId”] == 1
def test_invalid_user(api_request_context):
response = api_request_context.get(“/users/9999”)
assert response.status == 404
pytest.ini
[pytest]
testpaths = tests
addopts = -v
Run the complete test suite:
pytest
This project demonstrates positive API testing, resource creation, and negative API testing.
For production applications, expand it with authentication fixtures, schema validation, parameterization, environment configuration, and cleanup operations.
11. Reporting, Debugging, and CI/CD Integration
Reporting helps QA teams understand test execution results.
Install the HTML reporting plugin:
pip install pytest-html
pytest –html=report.html –self-contained-html
Debugging API tests
Print the response status:
print(response.status)
Print response headers:
print(response.headers)
Print JSON response:
print(response.json())
Use clear assertions and log request details carefully. Avoid printing passwords, tokens, or other sensitive information.
GitHub Actions integration
Create:
.github/workflows/api-tests.yml
name: Playwright API Tests
on:
push:
pull_request:
jobs:
test:
runs-on: ubuntu-latest
steps:
– name: Checkout
uses: actions/checkout@v6
– name: Setup Python
uses: actions/setup-python@v7
with:
python-version: “3.12”
– name: Install dependencies
run: |
pip install playwright pytest pytest-playwright pytest-html
– name: Run API tests
run: |
pytest –html=report.html –self-contained-html
– name: Upload report
if: always()
uses: actions/upload-artifact@v6
with:
name: api-test-report
path: report.html
API-only tests do not need browser installation, so this workflow does not download browser binaries.
Jenkins can execute the same test suite using:
pipeline {
agent any
stages {
stage(‘Install’) {
steps {
sh ‘pip install playwright pytest pytest-playwright pytest-html’
}
}
stage(‘API Tests’) {
steps {
sh ‘pytest –html=report.html –self-contained-html’
}
}
}
post {
always {
archiveArtifacts artifacts: ‘report.html’,
allowEmptyArchive: true
}
}
}
12. Common Errors, Troubleshooting, and Best Practices
Common API testing errors
1. Incorrect endpoint
A wrong API URL may return 404.
Solution: Verify the base URL and endpoint path.
2. Unauthorized response
A 401 response usually indicates missing or invalid authentication.
Solution: Check the token and Authorization header.
3. Incorrect request body
A 400 response may indicate missing fields or invalid JSON.
Solution: Verify the API contract and request payload.
4. JSON parsing errors
The response may not contain valid JSON.
Solution: Check the status and content type before parsing.
5. Request context not disposed
Undisposed request contexts can retain response resources.
Solution:
request.dispose()
Best practices
- Use reusable API request fixtures.
- Keep API endpoints in configuration files.
- Store tokens in environment variables.
- Validate response status, headers, and body.
- Cover positive and negative scenarios.
- Avoid hardcoded test data where possible.
- Use unique test data for parallel execution.
- Clean up resources created during testing.
- Generate HTML or Allure reports.
- Integrate API tests into CI/CD pipelines.
Interview Tips for Indian QA Engineers and SDETs
For QA automation interviews and placements, prepare these topics:
- What is API testing?
- What is APIRequestContext?
- What is the difference between APIRequest and APIRequestContext?
- How do you send GET and POST requests?
- How do you validate JSON responses?
- How do you implement Bearer token authentication?
- How do you create reusable Pytest fixtures?
- How do you combine API and UI automation?
- How do you execute API tests in Jenkins or GitHub Actions?
Build a practical API testing project and explain how you handle authentication, response validation, negative scenarios, and test data cleanup.
These skills are useful for candidates preparing for QA Engineer, Automation Tester, and SDET opportunities in Indian IT services and product companies.
Frequently Asked Questions
1. What is Playwright Python API testing?
Playwright Python API testing is the process of automating HTTP requests and validating API responses using Playwright’s APIRequestContext class. It supports CRUD operations, authentication, response validation, and integration with browser automation.
2. What are the benefits of Playwright Python API testing?
It provides built-in HTTP request handling, reusable request contexts, authentication support, Pytest integration, and the ability to combine API tests with browser automation.
3. How do I get started with Playwright Python API testing?
Install Python, then run pip install playwright pytest pytest-playwright. Create an API request context using playwright.request.new_context() and start sending GET or POST requests.
4. What is APIRequestContext in Playwright?
APIRequestContext is the Playwright class responsible for sending HTTP requests and handling API responses. It supports request methods such as GET, POST, PUT, PATCH, and DELETE.
5. Can Playwright Python be used for REST API testing?
Yes. Playwright Python supports REST API testing through APIRequestContext. You can validate endpoints, status codes, response headers, JSON data, and authentication.
6. Can we use Pytest with Playwright API testing?
Yes. Playwright integrates with Pytest through the pytest-playwright plugin. You can create reusable API fixtures and execute automated tests using the Pytest test runner.
7. Can Playwright API testing be combined with UI automation?
Yes. You can create test data through API requests, open the application in a browser, and verify the same data through the UI. Browser contexts can also share authentication cookies with their associated API request contexts.
