Combine API and UI Tests in Playwright Python
The slowest and most fragile part of most UI tests is not the step being tested but the setup before it: logging in, creating data, filling a cart. An API call does the same work in milliseconds. In this lesson you will mix API and UI steps in one Playwright test: see how page.request shares cookies with the browser, log in through an API and continue in the browser, check that the UI shows exactly what the API returns, set up application state directly instead of clicking through it, and use the API to verify what a UI action did.
📖 What You’ll Learn: the arrange-act-assert split between API and UI, page.request and context.request vs a standalone client, sharing cookies in both directions, logging in with an API call and continuing in the browser, comparing UI content with the API response, seeding client-side state with add_init_script, verifying UI actions through storage or the API, cleaning up with the API, and when hybrid tests are worth it.
🔀 Why Combine API and UI?
Every test has three parts: arrange (get into the right state), act (do the thing being tested) and assert (check the result). Only the act needs to go through the UI in a UI test. The other parts can use faster, more reliable channels:
| Part | UI only | Hybrid |
|---|---|---|
| Arrange | Click through login, create data in forms | API login, API-created data, seeded state |
| Act | UI | UI |
| Assert | Read the screen | Read the screen and check the API or stored state |
Typical gains: 3 to 10 times faster tests, fewer failures in steps unrelated to the test, and stronger assertions (the UI says “Saved”, and the API confirms it really was).
🍪 page.request Shares Cookies with the Browser
Playwright gives every browser context an API client: context.request (also available as page.request). Unlike playwright.request.new_context(), it uses the browser context’s cookie jar: cookies set by an API response appear in the browser, and browser cookies are sent with API calls.
The SQA Tools practice API has a cookie-session login: POST /auth-lab/session/login sets an HttpOnly session cookie (sqa_lab_session), and GET /auth-lab/session/profile works only when that cookie is sent back.
📄 pytest.ini
[pytest]
addopts = --base-url https://sqatools.in
📄 tests/test_shared_cookies.py
from playwright.sync_api import BrowserContext, Page, Playwright, expect
LAB = "/wp-json/sqa-api/v1/auth-lab/session"
VIEWER = {"username": "viewer", "password": "viewer@123"}
def test_api_login_is_visible_to_the_browser(page: Page, context: BrowserContext, base_url):
# 1. log in with an API call that shares the browser's cookie jar
response = page.request.post(base_url + LAB + "/login", data=VIEWER)
assert response.status == 200
# 2. the cookie set by the API response is now in the browser context
names = [c["name"] for c in context.cookies()]
print("\nbrowser cookies after API login:", [n for n in names if n.startswith("sqa")])
assert "sqa_lab_session" in names
# 3. the browser itself is logged in: opening the profile URL shows the user
page.goto(LAB + "/profile")
expect(page.locator("body")).to_contain_text('"username":"viewer"')
def test_standalone_client_has_its_own_cookies(page: Page, playwright: Playwright, base_url):
page.request.post(base_url + LAB + "/login", data=VIEWER) # browser context is logged in
other = playwright.request.new_context(base_url=base_url) # separate cookie jar
assert page.request.get(base_url + LAB + "/profile").status == 200
assert other.get(LAB + "/profile").status == 401
other.dispose()
⌨️ Terminal
pytest tests/test_shared_cookies.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
baseurl: https://sqatools.in
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_shared_cookies.py::test_api_login_is_visible_to_the_browser[chromium]
browser cookies after API login: ['sqa_lab_session']
PASSED
tests/test_shared_cookies.py::test_standalone_client_has_its_own_cookies[chromium] PASSED
============================== 2 passed in 3.11s ==============================
This is the key building block of hybrid tests: log in with one fast API call, then continue in the browser already logged in. It works for any application whose login sets a session cookie.
📌 Note: page.request does not use the page’s base_url automatically in every version, so these tests pass full URLs built from the base_url fixture. Relative URLs with page.goto() work as usual.
🪞 The UI Shows What the API Returns
A classic hybrid check: fetch the data through the API and compare it with what the page renders. This catches mapping bugs (wrong field, wrong order, missing items, formatting). The page here is the mini catalog from Lesson 52, which lists products from the practice API:
📄 tests/test_ui_matches_api.py
from pathlib import Path
from playwright.sync_api import Page, expect
CATALOG_URL = "https://sqatools.in/pw-demo/catalog"
def test_catalog_lists_what_the_api_returns(page: Page):
page.route(CATALOG_URL, lambda route: route.fulfill(path=Path(__file__).parent / "catalog.html"))
api_products = page.request.get("https://sqatools.in/wp-json/sqa-api/v1/products?per_page=5").json()["data"]
expected = [f"{p['name']} — ₹{p['price']}" + ("" if p["in_stock"] else " (out of stock)") for p in api_products]
page.goto(CATALOG_URL)
expect(page.get_by_test_id("product")).to_have_text(expected)
print("\n" + "\n".join(expected))
⌨️ Terminal
pytest tests/test_ui_matches_api.py -q -s
🖥️ Output
Wireless Mouse — ₹799
Mechanical Keyboard — ₹3499
USB-C Hub 7-in-1 — ₹2199 (out of stock)
27-inch Monitor — ₹15999
Cotton T-Shirt — ₹499
.
1 passed in 2.01s
to_have_text() with a list checks every item and the order in one assertion, and retries until the page has rendered.
⚡ Fast Setup: Seed State Instead of Clicking
The SQA Shop practice store keeps its cart in the browser (localStorage, key spCart), not on a server. For apps like this, the equivalent of “create data with the API” is to write the state directly before the page loads. context.add_init_script() runs before the store’s own JavaScript, so the app starts with the cart you want:
📄 tests/test_checkout_seeded.py
import json
import pytest
from playwright.sync_api import BrowserContext, Page, expect
SHOP = "/dummy-ecommerce-website/"
@pytest.fixture
def seeded_cart(context: BrowserContext):
"""Start the store with two items in the cart, without clicking through search and product pages."""
cart = [{"id": "EL-013", "size": "", "color": "", "qty": 1}, # Wireless Earbuds
{"id": "DG-010", "size": "", "color": "", "qty": 2}] # Agile Testing Handbook
context.add_init_script(f"""
if (!sessionStorage.getItem('seeded')) {{
localStorage.setItem('spCart', {json.dumps(json.dumps(cart))});
sessionStorage.setItem('seeded', '1');
}}""")
return cart
def test_cart_page_shows_seeded_items(page: Page, seeded_cart):
page.goto(SHOP + "#/cart")
expect(page.get_by_test_id("cart-count")).to_have_text("3")
expect(page.get_by_test_id("cart-item-name")).to_have_text(["Wireless Earbuds", "Agile Testing Handbook"])
def test_coupon_on_seeded_cart(page: Page, seeded_cart):
page.goto(SHOP + "#/cart")
page.get_by_test_id("coupon-input").fill("FLAT200")
page.get_by_test_id("apply-coupon").click()
expect(page.get_by_test_id("coupon-discount")).to_have_text("−₹200")
⌨️ Terminal
pytest tests/test_checkout_seeded.py -v --durations=3
🖥️ 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
baseurl: https://sqatools.in
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_checkout_seeded.py::test_cart_page_shows_seeded_items[chromium] PASSED [ 50%]
tests/test_checkout_seeded.py::test_coupon_on_seeded_cart[chromium] PASSED [100%]
============================= slowest 3 durations =============================
1.91s call tests/test_checkout_seeded.py::test_cart_page_shows_seeded_items[chromium]
1.56s call tests/test_checkout_seeded.py::test_coupon_on_seeded_cart[chromium]
0.42s setup tests/test_checkout_seeded.py::test_cart_page_shows_seeded_items[chromium]
============================== 2 passed in 4.09s ==============================
Two details:
- The
seededflag in sessionStorage makes the script seed the cart only on the first page load. Without it, every navigation would reset the cart and you could never test removing an item. json.dumps(json.dumps(cart))produces a JavaScript string literal containing JSON, which is whatlocalStorage.setItemexpects.
For server-side applications you would do the same with page.request.post("/api/cart", data=...) after an API login.
🔍 Verify UI Actions Behind the Scenes
The other direction: act in the UI, then check the source of truth rather than only the screen. In SQA Shop that is the stored cart; in a server-side app it is an API call.
📄 tests/test_verify_state.py
import json
from playwright.sync_api import Page, expect
SHOP = "/dummy-ecommerce-website/"
def stored_cart(page: Page) -> list[dict]:
return json.loads(page.evaluate("localStorage.getItem('spCart') || '[]'"))
def test_quantity_change_is_saved(page: Page):
page.goto(SHOP + "#/search/earbuds")
page.get_by_role("button", name="Add to cart").first.click()
page.goto(SHOP + "#/cart")
page.get_by_test_id("cart-plus-EL-013").click() # UI action
expect(page.get_by_test_id("cart-count")).to_have_text("2") # the screen says 2
assert [(line["id"], line["qty"]) for line in stored_cart(page)] == [("EL-013", 2)] # the data says 2
⌨️ Terminal
pytest tests/test_verify_state.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
baseurl: https://sqatools.in
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_verify_state.py::test_quantity_change_is_saved[chromium] PASSED [100%]
============================== 1 passed in 2.21s ==============================
A screen can show a number that was never saved (an optimistic update that later fails). Checking the stored data, or the API, catches that.
🧹 Clean Up with the API
When a UI test creates server data (an order, a user, a ticket), delete it through the API in the fixture’s teardown, so the next run starts clean:
@pytest.fixture
def created_ticket_ids(page):
ids = []
yield ids # the test appends the IDs it created
for ticket_id in ids:
page.request.delete(f"https://app.example.com/api/tickets/{ticket_id}")
Clean-up through the API is fast and keeps working even when the UI for deleting is broken.
⚖️ When Hybrid Tests Are Worth It
Use API steps for setup and clean-up that are not what the test is about (login, test data, feature flags), and for assertions that need the source of truth.
Keep pure UI steps for the behaviour under test, and keep a few full end-to-end journeys (for example “new user signs up, logs in, orders”) completely in the UI, because those are the flows real users take.
A common shape for a mature suite: many hybrid tests (API arrange, UI act, UI + API assert), a handful of pure end-to-end journeys, and a fast API test layer (Lesson 54).
🏋️ 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 logs in to the auth-lab cookie session with page.request, then calls page.request.post on /auth-lab/session/logout, and finally checks that opening /auth-lab/session/profile in the browser no longer shows the user.
Show answer
def test_logout_clears_browser_session(page, base_url):
lab = base_url + "/wp-json/sqa-api/v1/auth-lab/session"
page.request.post(lab + "/login", data={"username": "viewer", "password": "viewer@123"})
page.request.post(lab + "/logout")
page.goto(lab + "/profile")
expect(page.locator("body")).not_to_contain_text('"username":"viewer"')The logout response clears the cookie in the shared jar, so the browser is logged out too.
Exercise 2: Seed the SQA Shop cart with three units of EL-013 and check that the cart page shows the quantity 3. Reuse the add_init_script approach.
Show answer
def test_three_earbuds(context, page):
cart = [{"id": "EL-013", "size": "", "color": "", "qty": 3}]
context.add_init_script(f"if (!sessionStorage.getItem('s')) {{ localStorage.setItem('spCart', {json.dumps(json.dumps(cart))}); sessionStorage.setItem('s','1'); }}")
page.goto("/dummy-ecommerce-website/#/cart")
expect(page.get_by_test_id("cart-qty-EL-013")).to_have_value("3")The quantity is a read-only <input>, so check its value, not its text.
Exercise 3: Your hybrid test logs in with playwright.request.new_context().post(...) and then opens the app in page, but the page is not logged in. Why?
Show answer
A standalone request context has its own cookie jar, so the session cookie never reaches the browser context. Use page.request or context.request (shared cookies), or save the standalone client’s state with request_context.storage_state() and pass it to browser.new_context(storage_state=...).
Exercise 4: Write the assertion that checks each catalog item contains the matching product name from page.request.get(...), in the same order, in one line.
Show answer
expect(page.get_by_test_id("product")).to_contain_text([p["name"] for p in api_products])With a list, to_contain_text checks that there are as many elements as names and that each element contains its name, in order, with auto-retry. The items also contain prices, so to_contain_text fits better than to_have_text here.
🧠 MCQ Quiz: Combine API and UI Tests
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 part of a hybrid test should normally go through the UI?Answer: Act: the behaviour being tested. Setup and teardown can use the API; the action under test must use the UI.
- What is special about
page.requestcompared withplaywright.request.new_context()?Answer: It shares cookies with the browser context.context.request/page.requestuse the browser context’s cookie jar. - After
page.request.post(login_url, ...)sets a session cookie, what happens in the browser?Answer: The browser context has the cookie, so pages are logged in. The API client and the browser context share one cookie jar. - In the lesson, why did the standalone client get 401 for the profile?Answer: It has its own cookie jar without the session cookie.
playwright.request.new_context()is isolated from the browser context. - What does
expect(locator).to_have_text([...])with a list check?Answer: The number of elements and the text of each, in order. A list of expected texts is compared element by element, with retries. - Why seed the SQA Shop cart with
add_init_script?Answer: It sets the state before the app’s scripts run, skipping slow UI setup steps. Init scripts run first on every page load, so the app starts in the seeded state. - Why did the seeding script use a sessionStorage flag?Answer: So the cart is seeded only on the first load and not reset on every navigation. Init scripts run on every navigation; the flag prevents overwriting later changes.
- Why check stored data or the API after a UI action?Answer: The screen may show a change that was never saved; the source of truth confirms it. Optimistic UI updates can hide failed saves.
- Where is API clean-up best placed?Answer: In the teardown of a
yieldfixture. Teardown runs after every test, pass or fail. - Which tests should stay fully UI from start to finish?Answer: A few critical end-to-end user journeys. Real users take full journeys; a small set of pure UI journeys protects them, while hybrid tests cover the rest efficiently.
Want a longer, timed test? Take the Module 9 mock interview (20 MCQs in 20 minutes).
❓ Frequently Asked Questions
🤔 Can I log in through the API if my app uses tokens in localStorage, not cookies?
Yes. Call the login API, take the token from the response, and put it into localStorage with add_init_script (as the cart example does), or create a storage-state file with the token and load it (Lesson 51).
🤔 Does page.request appear in the trace?
Yes. API calls made with page.request or context.request are recorded in Playwright traces, so you can see them next to the UI steps when debugging.
🤔 What if the API and the UI are on different domains?
Cookies are per domain, so an API login on api.example.com sets cookies for that domain only. Hybrid login works when the session cookie is valid for the domain the browser opens (often a shared parent domain such as .example.com).
🤔 Is seeding client-side state cheating?
No, as long as the seeded state is one the app can really be in and the test is not about the steps you skipped. Keep a separate UI test for the skipped flow (here: adding to the cart from a product page).
🤔 How do I share an API-created object ID with the UI test?
Return it from the fixture (yield obj["id"]) and use it in the URL or locator, for example page.goto(f"/orders/{order_id}").
🏁 Summary
- Use the API for arrange and clean-up, the UI for the action under test, and both for assertions.
page.request/context.requestshare cookies with the browser: an API login logs in the browser too.- Compare what the UI shows with what the API returns using
to_have_text([...]). - For client-side apps, seed state with
add_init_script; for server apps, create it with API calls. - Verify UI actions against stored data or the API, and keep a few pure end-to-end journeys.
🎬 Watch the Playwright tutorial series on YouTube!
Subscribe to SqaToolsByDY • Practice on the SQA Tools Automation Practice Page