API Testing with Playwright Python (APIRequestContext)
Playwright is not only a browser tool. Its APIRequestContext sends HTTP requests directly, without a browser, so the same pytest project can test your REST API and your UI with one set of fixtures, one report and one CI job. In this lesson you will build an API test suite against the SQA Tools practice API: a session fixture for the client, GET with query parameters, POST, PUT, PATCH and DELETE on real temporary objects, response assertions, API keys, Basic auth and Bearer tokens, validation errors, and clean-up after every test.
📖 What You’ll Learn: what APIRequestContext is, playwright.request.new_context with base_url and extra_http_headers, the base_url trailing-slash rule, a session-scoped api fixture, GET with params, response.status, ok, json() and headers, expect(response).to_be_ok(), POST with data, PUT, PATCH and DELETE, CRUD with clean-up fixtures, API key and Basic auth, logging in for a Bearer token, testing 401 and 422 errors, fail_on_status_code, timeouts, and page.request sharing cookies with the browser.
🔌 What Is APIRequestContext?
APIRequestContext is Playwright’s HTTP client. It has methods for every HTTP verb (get, post, put, patch, delete, head, fetch) and returns an APIResponse with the status, headers and body.
Why use it instead of the requests library?
- One toolkit: the same fixtures, reports, traces and CI setup as your UI tests.
- Shared cookies:
page.requestandcontext.requestuse the browser context’s cookies, so you can log in through the API and continue in the UI (next lesson). - Playwright assertions:
expect(response).to_be_ok()prints the response body when it fails.
There are three ways to get one:
| Object | Cookies | Typical use |
|---|---|---|
playwright.request.new_context(...) |
Its own, isolated | Pure API tests |
context.request / page.request |
Shared with the browser context | Mixing API and UI steps |
🧪 The Practice API
All examples use the free SQA Tools practice API at https://sqatools.in/wp-json/sqa-api/v1. It has read-only data (/people, /products, /orders), temporary objects you can create, change and delete (/objects, kept for 10 minutes), and endpoints behind an API key, Basic auth and Bearer tokens. The credentials below are the public practice ones shown on that page.
🧰 The api Fixture
Create the client once per test session:
📄 pytest.ini
[pytest]
markers =
smoke: quick API checks
📄 tests/conftest.py
from typing import Generator
import pytest
from playwright.sync_api import APIRequestContext, Playwright
API_URL = "https://sqatools.in/wp-json/sqa-api/v1/" # note the trailing slash
@pytest.fixture(scope="session")
def api(playwright: Playwright) -> Generator[APIRequestContext, None, None]:
context = playwright.request.new_context(
base_url=API_URL,
extra_http_headers={"Accept": "application/json"},
timeout=15_000,
)
yield context
context.dispose() # release resources when the run ends
playwright is a pytest-playwright fixture, so no browser is launched for these tests.
⚠️ Watch out: The trailing-slash rule. With base_url="https://sqatools.in/wp-json/sqa-api/v1/", a request to "products" goes to .../v1/products. A request to "/products" (leading slash) replaces the whole path and goes to https://sqatools.in/products. Always end the base URL with / and write endpoint paths without a leading slash. The test below proves it.
📄 tests/test_base_url_rule.py
def test_relative_paths(api):
ok = api.get("products")
wrong = api.get("/products")
print(f"\n'products' -> {ok.url} {ok.status}\n'/products' -> {wrong.url} {wrong.status}")
assert ok.status == 200 and wrong.status == 404
⌨️ Terminal
pytest tests/test_base_url_rule.py -q -s
🖥️ Output
'products' -> https://sqatools.in/wp-json/sqa-api/v1/products 200
'/products' -> https://sqatools.in/products 404
.
1 passed in 1.00s
📥 GET Requests and Response Checks
📄 tests/test_get.py
import pytest
from playwright.sync_api import APIRequestContext, expect
@pytest.mark.smoke
def test_health(api: APIRequestContext):
response = api.get("health")
expect(response).to_be_ok() # status 200-299, shows the body on failure
assert response.json()["status"] == "ok"
def test_people_first_page(api: APIRequestContext):
response = api.get("people", params={"per_page": 3, "page": 1})
assert response.status == 200
assert response.headers["content-type"].startswith("application/json")
body = response.json()
assert [p["name"] for p in body["data"]] == ["Asha Verma", "Rahul Mehta", "Priya Nair"]
assert body["meta"] == {"page": 1, "per_page": 3, "total": 12, "total_pages": 4, "sort": "id", "order": "asc"}
def test_filter_products(api: APIRequestContext):
body = api.get("products", params={"category": "books", "in_stock": "true"}).json()
assert body["data"], "expected at least one book in stock"
for product in body["data"]:
assert product["category"] == "books"
assert product["in_stock"] is True
def test_unknown_product_is_404(api: APIRequestContext):
response = api.get("products/99999")
assert response.status == 404
assert response.json()["error"]["code"] == "not_found"
⌨️ Terminal
pytest tests/test_get.py -v
🖥️ Output
============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0 -- C:\Users\you\playwright-python\.venv\Scripts\python.exe
cachedir: .pytest_cache
rootdir: C:\Users\you\playwright-python
configfile: pytest.ini
plugins: allure-pytest-2.16.2, base-url-2.1.0, bdd-9.0.1, html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0
collecting ... collected 4 items
tests/test_get.py::test_health PASSED [ 25%]
tests/test_get.py::test_people_first_page PASSED [ 50%]
tests/test_get.py::test_filter_products PASSED [ 75%]
tests/test_get.py::test_unknown_product_is_404 PASSED [100%]
============================== 4 passed in 2.06s ==============================
The main APIResponse members:
| Member | Returns |
|---|---|
status, status_text, ok |
200, "OK", True for 2xx |
headers |
Dictionary of response headers (lower-case names) |
json(), text(), body() |
Parsed JSON, a string, raw bytes |
url |
The final URL after redirects |
params= builds the query string (?category=books&in_stock=true) and encodes values safely; never concatenate query strings by hand.
✍️ POST, PUT, PATCH and DELETE
The /objects endpoint stores temporary objects for 10 minutes, so you can practise the full lifecycle:
📄 tests/test_crud.py
from playwright.sync_api import APIRequestContext, expect
def test_object_lifecycle(api: APIRequestContext):
# CREATE
created = api.post("objects", data={"name": "Playwright laptop", "data": {"price": 55000, "color": "grey"}})
assert created.status == 201
obj = created.json()
object_id = obj["id"]
assert obj["name"] == "Playwright laptop" and obj["version"] == 1
# READ
expect(api.get(f"objects/{object_id}")).to_be_ok()
# PATCH: change one field, keep the rest
patched = api.patch(f"objects/{object_id}", data={"data": {"price": 52000}})
assert patched.status == 200
print("\nafter PATCH:", patched.json()["data"], "version", patched.json()["version"])
# PUT: replace the whole object
replaced = api.put(f"objects/{object_id}", data={"name": "Playwright laptop v2", "data": {"price": 50000}})
assert replaced.status == 200
print("after PUT: ", replaced.json()["name"], replaced.json()["data"], "version", replaced.json()["version"])
# DELETE, then it is gone
assert api.delete(f"objects/{object_id}").status in (200, 204)
assert api.get(f"objects/{object_id}").status == 404
⌨️ Terminal
pytest tests/test_crud.py -v -s
🖥️ Output
============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0 -- C:\Users\you\playwright-python\.venv\Scripts\python.exe
cachedir: .pytest_cache
rootdir: C:\Users\you\playwright-python
configfile: pytest.ini
plugins: allure-pytest-2.16.2, base-url-2.1.0, bdd-9.0.1, html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0
collecting ... collected 1 item
tests/test_crud.py::test_object_lifecycle
after PATCH: {'price': 52000, 'color': 'grey'} version 2
after PUT: Playwright laptop v2 {'price': 50000} version 3
PASSED
============================== 1 passed in 2.78s ==============================
data=with a dictionary sends JSON and setsContent-Type: application/json. Useform=for HTML form encoding andmultipart=for file uploads.- The output shows the difference between PATCH (merge:
colorsurvived) and PUT (replace:coloris gone), and the server incrementingversionon every change.
🧹 Create Test Data with a Fixture and Clean Up
Tests that create data must remove it, even when they fail. A yield fixture does both:
📄 tests/test_fixture_data.py
from typing import Generator
import pytest
from playwright.sync_api import APIRequestContext
@pytest.fixture
def temp_object(api: APIRequestContext) -> Generator[dict, None, None]:
obj = api.post("objects", data={"name": "fixture object", "data": {"qty": 1}}).json()
yield obj
api.delete(f"objects/{obj['id']}") # runs after the test, pass or fail
def test_rename(api: APIRequestContext, temp_object):
response = api.patch(f"objects/{temp_object['id']}", data={"name": "renamed"})
assert response.json()["name"] == "renamed"
def test_listing_contains_it(api: APIRequestContext, temp_object):
ids = [o["id"] for o in api.get("objects", params={"per_page": 100}).json()["data"]]
assert temp_object["id"] in ids
⌨️ Terminal
pytest tests/test_fixture_data.py -v
🖥️ Output
============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0 -- C:\Users\you\playwright-python\.venv\Scripts\python.exe
cachedir: .pytest_cache
rootdir: C:\Users\you\playwright-python
configfile: pytest.ini
plugins: allure-pytest-2.16.2, base-url-2.1.0, bdd-9.0.1, html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0
collecting ... collected 2 items
tests/test_fixture_data.py::test_rename PASSED [ 50%]
tests/test_fixture_data.py::test_listing_contains_it PASSED [100%]
============================== 2 passed in 2.42s ==============================
🔐 Authentication
API key in a header
Put headers every request needs into the context with extra_http_headers:
📄 tests/test_auth.py
import pytest
from playwright.sync_api import APIRequestContext, Playwright
def test_api_key_missing(api: APIRequestContext):
response = api.get("apikey/profile")
assert response.status == 401
assert response.json()["error"]["code"] == "missing_api_key"
def test_api_key(playwright: Playwright):
client = playwright.request.new_context(base_url="https://sqatools.in/wp-json/sqa-api/v1/",
extra_http_headers={"X-API-Key": "sqa-key-12345"})
response = client.get("apikey/profile")
assert response.status == 200
print("\napikey profile:", response.json())
client.dispose()
def test_basic_auth(playwright: Playwright):
client = playwright.request.new_context(base_url="https://sqatools.in/wp-json/sqa-api/v1/",
http_credentials={"username": "sqa_user", "password": "sqa@123"})
assert client.get("auth-lab/basic").status == 200
client.dispose()
@pytest.fixture(scope="session")
def admin_token(api: APIRequestContext) -> str:
response = api.post("auth/login", data={"username": "admin", "password": "admin@123"})
assert response.ok, response.text()
return response.json()["access_token"]
def test_bearer_token(api: APIRequestContext, admin_token):
me = api.get("auth/me", headers={"Authorization": f"Bearer {admin_token}"})
assert me.status == 200
assert me.json()["data"]["username"] == "admin"
assert me.json()["data"]["can_write"] is True
def test_wrong_password(api: APIRequestContext):
response = api.post("auth/login", data={"username": "admin", "password": "nope"})
assert response.status == 401
assert response.json()["error"]["code"] == "invalid_credentials"
⌨️ Terminal
pytest tests/test_auth.py -v -s
🖥️ Output
============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0 -- C:\Users\you\playwright-python\.venv\Scripts\python.exe
cachedir: .pytest_cache
rootdir: C:\Users\you\playwright-python
configfile: pytest.ini
plugins: allure-pytest-2.16.2, base-url-2.1.0, bdd-9.0.1, html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0
collecting ... collected 5 items
tests/test_auth.py::test_api_key_missing PASSED
tests/test_auth.py::test_api_key
apikey profile: {'data': {'client': 'api-client', 'auth': 'apikey', 'plan': 'free', 'message': 'API key accepted.'}}
PASSED
tests/test_auth.py::test_basic_auth PASSED
tests/test_auth.py::test_bearer_token PASSED
tests/test_auth.py::test_wrong_password PASSED
============================== 5 passed in 3.51s ==============================
extra_http_headerson the context applies to every request;headers=on one call adds or overrides headers for that call only.http_credentialsanswers HTTP Basic challenges automatically.- The
admin_tokenfixture logs in once per session, like the storage-state login in Lesson 51.
💡 Tip: Read real credentials from environment variables (Lesson 47). The practice API’s public demo credentials are written inline here only because they are published on its documentation page.
🚫 Testing Errors: 422 Validation
Negative tests matter as much as happy paths. The /validate/user endpoint returns 422 with one entry per invalid field:
📄 tests/test_validation.py
import pytest
from playwright.sync_api import APIRequestContext
@pytest.mark.parametrize(
"payload, bad_fields",
[
pytest.param({}, {"name", "email", "age"}, id="empty-body"),
pytest.param({"name": "Asha", "email": "not-an-email", "age": 30}, {"email"}, id="bad-email"),
pytest.param({"name": "Asha", "email": "asha@example.com", "age": "30"}, {"age"}, id="age-as-string"),
pytest.param({"name": "Asha", "email": "asha@example.com", "age": 17}, {"age"}, id="under-18"),
],
)
def test_invalid_user(api: APIRequestContext, payload, bad_fields):
response = api.post("validate/user", data=payload)
assert response.status == 422
details = response.json()["error"]["details"]
assert {d["field"] for d in details} == bad_fields
def test_valid_user(api: APIRequestContext):
response = api.post("validate/user", data={"name": "Asha", "email": "asha@example.com", "age": 30})
assert response.status == 200
⌨️ Terminal
pytest tests/test_validation.py -v
🖥️ Output
============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0 -- C:\Users\you\playwright-python\.venv\Scripts\python.exe
cachedir: .pytest_cache
rootdir: C:\Users\you\playwright-python
configfile: pytest.ini
plugins: allure-pytest-2.16.2, base-url-2.1.0, bdd-9.0.1, html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0
collecting ... collected 5 items
tests/test_validation.py::test_invalid_user[empty-body] PASSED [ 20%]
tests/test_validation.py::test_invalid_user[bad-email] PASSED [ 40%]
tests/test_validation.py::test_invalid_user[age-as-string] PASSED [ 60%]
tests/test_validation.py::test_invalid_user[under-18] PASSED [ 80%]
tests/test_validation.py::test_valid_user PASSED [100%]
============================== 5 passed in 2.34s ==============================
The age-as-string case shows why API tests matter: a UI form usually sends strings, so only an API test checks that the server really enforces the number type.
⚙️ Useful Request Options
| Option | Example | Use |
|---|---|---|
params |
params={"page": 2} |
Query string |
data / form / multipart |
multipart={"file": {"name": "a.txt", "mimeType": "text/plain", "buffer": b"hi"}} |
Body formats |
headers |
headers={"If-None-Match": etag} |
Per-request headers |
timeout |
timeout=5_000 |
Fail slow endpoints fast (milliseconds) |
fail_on_status_code |
fail_on_status_code=True |
Raise an error for non-2xx instead of returning the response |
max_redirects |
max_redirects=0 |
Inspect a redirect instead of following it |
📄 tests/test_options.py
import pytest
from playwright.sync_api import APIRequestContext, Error
def test_fail_on_status_code(api: APIRequestContext):
with pytest.raises(Error) as info:
api.get("status/503", fail_on_status_code=True)
print("\n", str(info.value).splitlines()[0])
def test_etag_not_modified(api: APIRequestContext):
first = api.get("products/101")
etag = first.headers["etag"]
second = api.get("products/101", headers={"If-None-Match": etag})
assert second.status == 304
def test_redirect_not_followed(api: APIRequestContext):
response = api.get("redirect", params={"status": 302}, max_redirects=0)
assert response.status == 302
assert "/echo" in response.headers["location"]
⌨️ Terminal
pytest tests/test_options.py -v -s
🖥️ Output
============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0 -- C:\Users\you\playwright-python\.venv\Scripts\python.exe
cachedir: .pytest_cache
rootdir: C:\Users\you\playwright-python
configfile: pytest.ini
plugins: allure-pytest-2.16.2, base-url-2.1.0, bdd-9.0.1, html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0
collecting ... collected 3 items
tests/test_options.py::test_fail_on_status_code
APIRequestContext.get: 503 Service Unavailable
PASSED
tests/test_options.py::test_etag_not_modified PASSED
tests/test_options.py::test_redirect_not_followed PASSED
============================== 3 passed in 1.85s ==============================
✅ Good Practices for API Tests
- Assert the status first, then the body. A wrong status explains most failures.
- Check structure and types, not only values, for example
isinstance(item["price"], int). For larger APIs, validate against the JSON Schema with thejsonschemalibrary (the practice API publishes its schemas under/schema/{name}). - Create your own data in fixtures and delete it afterwards; never depend on data another test created.
- Cover negative cases: missing auth (401), wrong role (403), not found (404), validation (422), rate limits (429).
- Keep secrets out of code and logs; print response bodies only for non-sensitive endpoints.
🏋️ Practice Exercises
Try each exercise on your own first, then open the answer to compare. The answers use the same practice sites and project layout as the lesson.
Exercise 1: Write a test that gets people filtered by city=Pune and asserts that every returned person lives in Pune and that the result is not empty.
Show answer
def test_people_in_pune(api):
response = api.get("people", params={"city": "Pune"})
assert response.status == 200
people = response.json()["data"]
assert people
assert all(p["city"] == "Pune" for p in people)Exercise 2: Write a test that logs in as viewer / viewer@123 and checks that the viewer can read token/objects but gets 403 when creating one.
Show answer
def test_viewer_is_read_only(api):
token = api.post("auth/login", data={"username": "viewer", "password": "viewer@123"}).json()["access_token"]
headers = {"Authorization": f"Bearer {token}"}
assert api.get("token/objects", headers=headers).status == 200
assert api.post("token/objects", headers=headers, data={"name": "x"}).status == 403Role checks are among the most valuable API tests, because the UI usually just hides buttons.
Exercise 3: Create a fixture api_with_key (session scope) that returns a client already sending X-API-Key: sqa-key-12345, and disposes of it at the end of the session.
Show answer
@pytest.fixture(scope="session")
def api_with_key(playwright):
client = playwright.request.new_context(base_url="https://sqatools.in/wp-json/sqa-api/v1/",
extra_http_headers={"X-API-Key": "sqa-key-12345"})
yield client
client.dispose()Exercise 4: A test calls api.get("/people") with base_url="https://sqatools.in/wp-json/sqa-api/v1/" and gets 404. Explain and fix it.
Show answer
A path starting with / is resolved from the host root, so the request goes to https://sqatools.in/people. Remove the leading slash: api.get("people"). Keep the trailing slash on the base URL.
🧠 MCQ Quiz: API Testing with APIRequestContext
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
- Which call creates a standalone API client in Playwright Python?Answer:
playwright.request.new_context(base_url=...).playwright.request.new_context()returns an APIRequestContext with its own cookies. - With
base_url="https://x.com/api/v1/", where doesget("/users")go?Answer:https://x.com/users. A leading slash replaces the whole path of the base URL. - What does
data={"a": 1}do inapi.post()?Answer: Sends JSON and sets the JSON content type. A dictionary passed asdatais serialised as JSON; useform=ormultipart=for other encodings. - Which assertion prints the response body when it fails?Answer:
expect(response).to_be_ok(). Playwright’s API response assertion includes the body in its failure message. - What is the difference between PATCH and PUT in the lesson’s output?Answer: PATCH merged the change and kept other fields; PUT replaced the whole object. PATCH is a partial update; PUT replaces the resource representation.
- How do you send a header with every request of a client?Answer:
extra_http_headerswhen creating the context. Context-level headers apply to all requests; per-callheaders=adds or overrides. - Why is the test-data fixture written with
yield?Answer: So the clean-up afteryieldruns even when the test fails. Code afteryieldis teardown and always runs. - Which status code means the request was understood but the data failed validation?Answer: 422. 422 Unprocessable Content is used for semantic validation errors, as the practice API does.
- What does
fail_on_status_code=Truechange?Answer: Raises an error for non-2xx and non-3xx responses instead of returning them. By default the response is returned whatever the status; this option makes failures raise. - How do
page.requestandplaywright.request.new_context()differ?Answer:page.requestshares the browser context’s cookies; a new request context has its own. The page’s request client uses the same cookie jar as the browser context, which enables API + UI flows.
Want a longer, timed test? Take the Module 9 mock interview (20 MCQs in 20 minutes).
❓ Frequently Asked Questions
🤔 Should I use Playwright or the requests library for API tests?
For API tests that live next to Playwright UI tests, APIRequestContext is the better fit: one dependency, shared cookies with the browser, Playwright assertions and traces. For a pure API project with no UI, requests or httpx are equally good choices.
🤔 Can I validate responses against a JSON Schema?
Yes. Install jsonschema and call jsonschema.validate(instance=response.json(), schema=schema). The practice API serves its schemas at schema/user, schema/product and so on, so you can fetch the schema in a fixture.
🤔 How do I upload a file through the API?
Use multipart={"file": {"name": "report.csv", "mimeType": "text/csv", "buffer": path.read_bytes()}, "note": "nightly"}. Playwright builds the multipart body for you.
🤔 Do API tests appear in pytest-html and Allure reports?
Yes, they are ordinary pytest tests. Lessons 63 and 64 show how to attach request and response details to reports.
🤔 Does APIRequestContext follow redirects?
Yes, up to 20 by default. Set max_redirects=0 to inspect the redirect response itself, as the lesson does.
🏁 Summary
playwright.request.new_context(base_url=..., extra_http_headers=...)creates an API client; dispose of it at the end.- End the base URL with
/and write paths without a leading slash. - Use
get/post/put/patch/deletewithparams,data,headers; checkstatus,json()andheaders, orexpect(response).to_be_ok(). - Create test data in
yieldfixtures and clean up; log in once for Bearer tokens; usehttp_credentialsfor Basic auth. - Test negative cases (401, 403, 404, 422) as carefully as the happy path.
🎬 Watch the Playwright tutorial series on YouTube!
Subscribe to SqaToolsByDY • Practice on the SQA Tools Automation Practice Page