Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.
Playwright Python API testing uses APIRequestContext to send HTTP(S) requests directly from Python, without loading a page or running JavaScript. You can use it to test REST endpoints, create server state before a UI test, and verify server-side results after browser actions. The key design choice is whether requests share cookies with a browser context or run in an isolated context.
This guide shows both approaches with pytest examples, authentication-state transfer, cleanup patterns, version-sensitive storage behavior, troubleshooting, and a browser-free alternative for generating website screenshots.
What Playwright Python API testing actually does
Playwright’s API testing guide describes sending requests directly from Python. An APIRequestContext handles HTTP methods such as GET, POST, PUT, PATCH and DELETE, lets you inspect response bodies and status codes, and can be used independently of a page.
That makes it useful in three situations:
- Direct API tests: verify status codes, headers, JSON payloads and error handling without browser rendering.
- UI-test setup: create users, projects or other records through the API before opening the application.
- Postcondition checks: perform a browser action, then confirm the server state through an API call.
Because response bodies are retained in memory for inspection, dispose of a request context when its work is finished, especially in large suites.
#1 Best Overall
- CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
- INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
- THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
- WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
- A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents
Install Playwright and pytest fixtures
Install the Python package and the pytest plugin in your virtual environment:
python -m pip install playwright pytest pytest-playwright
python -m playwright install
The second command installs browser binaries for tests that also use Chromium, Firefox or WebKit. Pure API tests do not load a browser, but installing the plugin gives you the standard fixtures and keeps a mixed API/UI project consistent.
The examples below use the fixtures supplied by pytest-playwright. Save a test in a file such as tests/test_api.py and run:
Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Clear out junk files and repair common Windows errorsFree Scan →pytest -q
Choose the right request context
Browser-associated context: shared cookies
browser_context.request and page.request refer to an API request context associated with that browser context. Requests use the browser context’s cookie jar, and cookies received in API responses update the same jar. Choose this mode when an API setup or verification call must use the same logged-in session as browser actions.
def test_profile_via_api_and_ui(page):
response = page.request.get("/api/profile")
assert response.ok
profile = response.json()
assert profile["email"]
page.goto("https://example.test/account")
assert page.get_by_role("heading", name="Account").is_visible()
The exact base URL comes from the browser context configuration. If you create the context yourself, pass base_url there or use absolute URLs.
Isolated context: separate cookies
Use playwright.request.new_context() to create an independent context. Its cookie storage is isolated from every browser context. This is safer when API setup should not alter browser authentication, or when tests need separate users.
Rank #2
- CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
- 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
- SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
- INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
- THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
from playwright.sync_api import Playwright, expect
def test_isolated_api(playwright: Playwright):
api = playwright.request.new_context(
base_url="https://example.test",
extra_http_headers={"Accept": "application/json"},
timeout=30_000,
)
try:
response = api.get("/api/health")
expect(response).to_be_ok()
assert response.json()["status"] == "ok"
finally:
api.dispose()
The API reference documents options including base_url, HTTP credentials, storage_state and timeout configuration: APIRequest. Keep one context per logical session; do not accidentally reuse a context between tests that should be isolated.
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Scan for outdated or missing drivers - takes under a minute3Clear out junk files and repair common Windows errorsA complete pytest API test
This example configures a base URL and authorization header, creates a resource, checks it, and deletes it. It follows the same lifecycle as the repository-and-issue example in the official guide: mutation requires unique test data and reliable cleanup.
import os
import uuid
from playwright.sync_api import APIRequestContext, Playwright, expect
def test_create_and_remove_project(playwright: Playwright):
api: APIRequestContext = playwright.request.new_context(
base_url=os.environ["API_BASE_URL"],
extra_http_headers={
"Accept": "application/json",
"Authorization": f"Bearer {os.environ['API_TOKEN']}",
},
timeout=30_000,
)
project_id = None
try:
name = f"pw-{uuid.uuid4()}"
created = api.post("/projects", data={"name": name})
expect(created).to_be_ok()
project_id = created.json()["id"]
fetched = api.get(f"/projects/{project_id}")
expect(fetched).to_be_ok()
assert fetched.json()["name"] == name
finally:
if project_id is not None:
deleted = api.delete(f"/projects/{project_id}")
assert deleted.ok
api.dispose()
Use environment variables or a CI secret store for tokens. Do not place credentials directly in source control. If deletion is not available, create data in a dedicated test tenant and add a separate cleanup job.
API plus browser: a practical workflow
Prepare state through the API
Creating records by API is usually more deterministic than clicking through setup screens. You can then launch a browser context and visit the page that consumes those records. With pytest-playwright, a fixture can return setup data while the test uses the standard page fixture.
import pytest
@pytest.fixture
def seeded_order(playwright):
api = playwright.request.new_context(
base_url="https://shop.example",
extra_http_headers={"Authorization": "Bearer test-token"},
)
response = api.post("/api/orders", data={"sku": "widget", "quantity": 1})
response.raise_for_status()
order = response.json()
yield order
api.delete(f"/api/orders/{order['id']}")
api.dispose()
def test_order_page(page, seeded_order):
page.goto(f"https://shop.example/orders/{seeded_order['id']}")
expect(page.get_by_text("widget")).to_be_visible()
Verify server state after a UI action
After clicking in the browser, call an associated request context so the API request carries the same cookies:
def test_checkout_updates_order(page):
page.goto("https://shop.example/cart")
page.get_by_role("button", name="Place order").click()
response = page.request.get("/api/orders/latest")
response.raise_for_status()
assert response.json()["status"] == "paid"
This avoids depending solely on a success banner. API assertions should check the state your system actually promises, such as an order status, audit record or inventory count.
Authentication and storage state
Playwright can transfer authentication state between API and browser contexts. The API testing guide shows obtaining state from an authenticated request context and using it when creating a browser context. The authentication guide also recommends saving state once and reusing it so every test does not repeat login.
Rank #3
- Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
- Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
- Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
- In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
- Ultra-thin bezels: Maximize your viewing experience with thin bezels.
Save API authentication for a browser context
from playwright.sync_api import Playwright
def create_authenticated_state(playwright: Playwright):
api = playwright.request.new_context(base_url="https://example.test")
try:
login = api.post("/api/login", data={
"username": "test-user",
"password": "use-a-secret-from-ci",
})
login.raise_for_status()
api.storage_state(path="playwright/.auth/user.json")
finally:
api.dispose()
def browser_with_state(playwright: Playwright):
browser = playwright.chromium.launch()
context = browser.new_context(storage_state="playwright/.auth/user.json")
return browser, context
Protect that file. Cookies and headers in a storage-state file can impersonate the account. Add playwright/.auth to .gitignore, use a disposable test account, and never commit real production state.
Version-sensitive storage features
Check the Playwright version installed in your project before relying on advanced storage behavior. The Python release notes identify IndexedDB support in storage_state() as added in v1.51, which matters for applications that keep authentication tokens in IndexedDB. The current API references also tag newer options, including OPFS support in v1.63. A project running an older version may not support those options.
Free tools Windows power users keep installed
One-click scans. No signup required.
Request options you will use most
base_url: lets relative paths such as/api/usersresolve against one host.extra_http_headers: supplies common headers such asAuthorizationandAccept.data: sends JSON-compatible dictionaries or other request payloads.params: adds query-string parameters.timeout: sets the request timeout in milliseconds.storage_state: seeds cookies and other saved state when creating a context.fetch: provides a lower-level request method when you need to choose method, URL and options dynamically.
Use the APIRequestContext reference for the complete method and option list, including get, delete and fetch.
Troubleshooting common failures
401 or 403 responses
Confirm the token, header spelling and audience expected by the API. If the browser is logged in but an isolated context receives 401, that is expected: isolated contexts do not share browser cookies. Use page.request or pass an appropriate storage_state.
404 from a relative URL
Check base_url and URL joining. A missing API prefix, such as /v1, is a common cause. Log the final endpoint and try an absolute URL temporarily.
Tests pass alone but fail in the suite
Look for shared contexts, fixed usernames, duplicate names and missing cleanup. Generate unique identifiers, isolate contexts, and remove resources in a finally block. Parallel workers should use separate accounts or namespaces.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Rank #4
- CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
- SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
- MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
- KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
- INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient
Timeouts and empty responses
Increase the context timeout only after checking server health and dependency latency. Inspect the status, headers and body before decoding JSON; an HTML proxy error page will make response.json() fail. Dispose of contexts so retained response bodies do not accumulate.
Storage state does not authenticate the browser
Verify that the login response actually set cookies or supported storage, that the state file is readable, and that the browser context uses the same origin. For IndexedDB-backed tokens, confirm a Playwright version that supports the required storage-state feature.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Performance, reliability and cost decisions
API calls avoid browser rendering, so they are a good fit for setup and server assertions. They do not replace UI coverage: an API test cannot prove that a button is reachable, JavaScript wiring works or a browser renders correctly. Keep API checks focused and use browser tests for user-visible behavior.
For reliable suites, use deterministic fixtures, unique data, explicit assertions on response status and payload, and cleanup that runs after failures. Treat remote services as integration dependencies; retries should be narrow and should not hide persistent authorization or validation errors.
Recommended Free Tools
Or skip the browser setup
If your goal is a website screenshot rather than testing an API, ScreenshotNeo provides a single HTTP request. It accepts cookie and consent banners before capture and removes more than 60 known consent platforms, newsletter popups and chat widgets. Bot checks, blank pages, timeouts, failed loads and cache hits are not billed, and each response identifies the page verdict and billing status. Its MCP server exposes take_screenshot, get_page_info and capture_pdf to Claude, Cursor and other MCP clients.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
See the ScreenshotNeo documentation for the 63 capture options, including full-page lazy-image loading, CSS selectors, device presets, retina scale, PDFs, custom headers and cookies, JavaScript, waits, request blocking, geolocation, caching, signed links, async webhooks and bulk capture.
The Free plan includes 1,000 shots per month with no card. Paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.
Best Value
- 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
- 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
- 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.
FAQ
Does Playwright API testing require a browser?
No. An isolated APIRequestContext sends HTTP(S) requests without loading a page. Browser binaries are needed only for tests that launch a browser.
Should every test create a new request context?
Create a context per logical session and dispose of it after use. Isolate contexts when cookies or authentication must not leak between tests.
Can API and UI tests use the same login?
Yes. Use an associated context for shared cookies, or save API storage state and provide that state when creating the browser context.
Frequently Asked Questions
Does Playwright API testing require a browser?
No. An APIRequestContext sends HTTP(S) requests without loading a page. A browser is required only for tests that launch one.
How do I prevent authentication leakage between tests?
Use isolated request contexts, disposable accounts, protected storage-state files and cleanup in finally blocks.
The Tool Desk
Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

