β‘ Headless API Testing & Hybrid Test Acceleration
Full end-to-end UI testing is powerful, but setting up complex test state through the browser (such as logging in, navigating multi-page wizards, creating sample inventories, and generating test users) makes regression runs slow and prone to UI flakes. Playwright APIRequestContext provides a high-performance HTTP client that executes direct web requests without opening a browser window. Even more importantly, when created via context.request or page.request, the API Request Context shares the exact same cookie jar, storage state, and authentication tokens as the active browser tab. This enables fast hybrid test automation: seed test data instantly via REST calls in milliseconds, then assert user outcomes through the UI.
playwright.request.new_context() (zero browser overhead) and linked contexts via browser_context.request (shared session state).
STANDALONE API CLIENT (No Browser Launched - 100% Headless HTTP):
[ p.request.new_context(base_url="https://api.example.com") ]
β
βββ Ultra-lightweight (Zero Chromium / WebKit memory overhead)
βββ Full REST/GraphQL API test harness (Replaces requests / httpx)
βββ Disposed independently with api_context.dispose()
BROWSER-LINKED CONTEXT (Hybrid UI + API Testing):
[ browser.new_context() ]
β
βββ Shares same Cookie Jar & Authentication Headers
βββ browser_context.request.post("/api/login") βββΊ Stores auth cookie
βΌ
[ context.new_page().goto("/dashboard") ] βββββββββββββββΊ Already logged in!
request.get(), inspect status codes, read response headers, and parse structured JSON bodies without launching a browser.
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
# Create an isolated HTTP client context (no browser binary launched)
api_request_context = p.request.new_context(
base_url="https://httpbin.org",
extra_http_headers={"Accept": "application/json"}
)
# Dispatch GET request with query parameters
response = api_request_context.get(
"/get",
params={"client": "Nikita-Infotech", "env": "Staging"}
)
# 1. Web-first API assertions
expect(response).to_be_ok() # Verifies status is in the 200-299 range
assert response.status == 200
# 2. Extract payload and metadata
data = response.json()
print(f"HTTP Status Code : {response.status} {response.status_text}")
print(f"Resolved Request URL : {response.url}")
print(f"Captured Query Params : {data['args']}")
print(f"Content-Type Header : {response.headers.get('content-type')}")
# Dispose context to clean up connections
api_request_context.dispose()
data parameter, validating status codes and created entity identifiers.
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
api = p.request.new_context(base_url="https://httpbin.org")
new_invoice_payload = {
"invoice_id": "INV-2026-904",
"customer_name": "Pooja Patil",
"service_tier": "Full Stack Quality Engineering",
"amount_inr": 24999.00,
"status": "APPROVED"
}
# Dispatch POST with Python dictionary serialized into JSON payload
response = api.post(
"/post",
data=new_invoice_payload,
headers={"X-Initiated-By": "Automation-Worker-1"}
)
expect(response).to_be_ok()
response_body = response.json()
print(f"Entity Created Successfully via API (Status: {response.status}):")
print(f" Invoice ID : {response_body['json']['invoice_id']}")
print(f" Customer : {response_body['json']['customer_name']}")
print(f" Amount (INR) : βΉ {response_body['json']['amount_inr']}")
api.dispose()
put() or patch(), and clean up test records with delete().
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
api = p.request.new_context(base_url="https://httpbin.org")
# 1. UPDATE via PUT (Full Resource Replacement)
put_res = api.put("/put", data={"role": "Lead Architect", "active": True})
expect(put_res).to_be_ok()
print(f"PUT Operation Succeeded : {put_res.status} | Updated role: {put_res.json()['json']['role']}")
# 2. PARTIAL UPDATE via PATCH (Delta Patching)
patch_res = api.patch("/patch", data={"active": False})
expect(patch_res).to_be_ok()
print(f"PATCH Operation Succeeded : {patch_res.status} | Set active: {patch_res.json()['json']['active']}")
# 3. DELETE (Resource Teardown)
del_res = api.delete("/delete", params={"id": "REC-8841"})
expect(del_res).to_be_ok()
print(f"DELETE Operation Succeeded: {del_res.status} | Purged id: {del_res.json()['args']['id']}")
api.dispose()
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
context = browser.new_context()
# Step 1: Execute fast API precondition call using browser-linked request context
api_response = context.request.post(
"https://httpbin.org/post",
data={"sku": "COURSE-PY-01", "name": "Playwright Automation Mastery"}
)
expect(api_response).to_be_ok()
seeded_item = api_response.json()["json"]["name"]
print(f"[API Precondition] Seeded record in database: '{seeded_item}'")
# Step 2: Open UI page and verify frontend renders the seeded record
page = context.new_page()
page.set_content(f"""
Course Catalog
{seeded_item}
""")
course_card = page.get_by_test_id("course-title")
expect(course_card).to_be_visible()
expect(course_card).to_have_text("Playwright Automation Mastery")
print(f"[UI Assertion] Verified seeded item rendered in DOM: '{course_card.inner_text()}'")
context.close()
browser.close()
multipart parameter without interacting with browser file dialogs.
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
api = p.request.new_context(base_url="https://httpbin.org")
# Construct synthetic in-memory file payload
file_bytes = b"sample_id,result\n1,PASS\n2,PASS\n"
response = api.post(
"/post",
multipart={
"description": "Weekly Regression Run Report",
"log_level": "DEBUG",
"file": {
"name": "audit_metrics_2026.csv",
"mimeType": "text/csv",
"buffer": file_bytes
}
}
)
expect(response).to_be_ok()
result = response.json()
print("Multipart File Dispatched Successfully via APIRequestContext:")
print(f" Field 'description' : {result['form']['description']}")
print(f" Uploaded File Name : audit_metrics_2026.csv")
print(f" File Content Length : {len(result['files']['file'])} characters")
api.dispose()
application/x-www-form-urlencoded) by passing a dictionary to the form parameter instead of data.
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
api = p.request.new_context(base_url="https://httpbin.org")
form_payload = {
"username": "nikita_admin",
"action": "RESET_CACHE",
"target_cluster": "DC-West-01"
}
# 'form' parameter sets Content-Type: application/x-www-form-urlencoded
response = api.post("/post", form=form_payload)
expect(response).to_be_ok()
data = response.json()
print("Form URL-Encoded Dispatch Verified:")
print(f" Received Form Data: {data['form']}")
print(f" Headers Sent : {data['headers']['Content-Type']}")
api.dispose()
headers on a per-request basis, or configure persistent base headers across the entire API-Request-Context instance.
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
jwt_token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.TEST_SESSION_2026"
# Set persistent authorization header for all subsequent API requests
api = p.request.new_context(
base_url="https://httpbin.org",
extra_http_headers={
"Authorization": f"Bearer {jwt_token}",
"X-Client-Version": "4.2.0"
}
)
response = api.get("/headers")
expect(response).to_be_ok()
headers_received = response.json()["headers"]
print("Authorization Headers Successfully Echoed by Gateway:")
print(f" Authorization : {headers_received.get('Authorization')}")
print(f" X-Client-Version : {headers_received.get('X-Client-Version')}")
api.dispose()
# content of conftest.py
import pytest
from playwright.sync_api import Playwright, APIRequestContext
@pytest.fixture(scope="session")
def api_client(playwright: Playwright) -> APIRequestContext:
"""Session-scoped standalone API client for test fixtures and data hydration."""
request_context = playwright.request.new_context(
base_url="https://httpbin.org",
extra_http_headers={"X-Test-Session": "Pytest-Automation-Suite"}
)
yield request_context
request_context.dispose()
# content of test_inventory_flow.py
def test_create_and_query_item(api_client: APIRequestContext):
# 1. Direct API creation
res = api_client.post("/post", data={"item": "Industrial Gateway Relay"})
assert res.ok
assert res.status == 200
# 2. Query record state
verify_res = api_client.get("/get", params={"item": "Industrial Gateway Relay"})
assert verify_res.ok
assert verify_res.json()["args"]["item"] == "Industrial Gateway Relay"
API-Request-Context and APIResponse interfaces in Python.
PLAYWRIGHT APIREQUESTCONTEXT & APIRESPONSE MATRIX:
ββββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Method / Operation β Key Parameters β Primary Description / Use Case β
ββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β playwright.request.new_context base_url, extra_http_headers β Creates standalone HTTP client without launching browserβ
β context.request β Property on BrowserContext β HTTP client sharing same cookies/storage as browser. β
β api.get(url, **kwargs) β params, headers, timeout β Dispatches HTTP GET query with URL params. β
β api.post(url, **kwargs) β data, form, multipart β Dispatches HTTP POST (supports JSON, form, or files). β
β api.put(url, **kwargs) β data, form, headers β Dispatches HTTP PUT (full resource replacement). β
β api.patch(url, **kwargs) β data, form, headers β Dispatches HTTP PATCH (partial delta modification). β
β api.delete(url, **kwargs) β params, headers β Dispatches HTTP DELETE (resource teardown/cleanup). β
β api.fetch(url_or_request) β method, headers, data β Generic HTTP dispatcher method. β
β api.dispose() β None β Cleans up connection pool and disposes the context. β
ββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β APIRESPONSE METHODS: β
β * response.status βββΊ int: Returns HTTP status code (200, 201, 404, 500). β
β * response.status_text βββΊ str: Returns HTTP status message (e.g., "OK", "Not Found"). β
β * response.ok βββΊ bool: Returns True if status is between 200 and 299 inclusive. β
β * response.json() βββΊ Dict / List: Parses JSON payload body into native Python objects. β
β * response.text() βββΊ str: Decodes response body into UTF-8 string. β
β * response.body() βββΊ bytes: Returns raw binary response buffer. β
β * response.headers βββΊ Dict[str, str]: Returns dictionary of all normalized response headers. β
β * expect(response).to_be_ok() βββΊ Web-first assertion verifying status in 200-299 range. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ