⚡ The Power of API & UI Hybrid Automation
Pure UI end-to-end testing is notoriously slow and fragile when every test executes multi-step web wizards just to set up preconditions (such as creating customer accounts, populating shopping carts, and navigating onboarding modals). Conversely, pure API tests verify business logic but miss client-side rendering bugs, CSS formatting anomalies, and DOM interaction blockers. Hybrid Testing combines the speed of API execution with the visual fidelity of browser automation. In Playwright, context.request and page.request share the exact same cookie store, session storage, and origin context as active browser tabs. Tests can execute sub-second API calls to seed prerequisites, navigate directly to target pages in a pre-authenticated state, perform critical UI actions, and tear down records via backend REST endpoints.
LEGACY PURE UI TEST (Slow, Fragile, 25-40 seconds):
[ Browser Launch ] ──► [ Fill Login Form ] ──► [ Click Submit ] ──► [ Navigate Wizard 1 ]
│
▼
[ Navigate Wizard 2 ] ──► [ Create Product via Form ] ──► [ TEST TARGET ACTION ] ──► [ Delete via UI ]
OPTIMIZED HYBRID PLAYWRIGHT TEST (Fast, Hermetic, 2-4 seconds):
┌─────────────────────────────────────────────────────────────────────────────┐
│ 1. PRECONDITION (APIRequestContext via context.request) │
│ POST /api/v1/login ──► Injects auth cookie into BrowserContext │
│ POST /api/v1/products ──► Seeds test product entity in 40ms │
├─────────────────────────────────────────────────────────────────────────────┤
│ 2. TARGET VALIDATION (Browser Page via context.new_page()) │
│ page.goto("/products/101") ──► Page opens already authenticated! │
│ page.locator("#buy-now").click() │
│ expect(page.locator(".toast-success")).to_be_visible() │
├─────────────────────────────────────────────────────────────────────────────┤
│ 3. TEARDOWN (APIRequestContext via context.request) │
│ DELETE /api/v1/products/101 ──► Purges database record immediately │
└─────────────────────────────────────────────────────────────────────────────┘
context.request.post(). The session cookie is automatically written into the shared BrowserContext cookie jar, allowing new browser tabs to open already signed in.
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
# BrowserContext encapsulates shared cookie jar and storage state
context = browser.new_context()
# STEP 1: Authenticate via direct REST call using context.request
login_response = context.request.post(
"https://httpbin.org/post",
data={"username": "pooja_patil", "password": "SecurePassword2026!"}
)
expect(login_response).to_be_ok()
print("[API Setup] Authentication API returned HTTP 200 OK")
# Inject mock session cookie to simulate real auth backend session
context.add_cookies([{
"name": "session_auth_token",
"value": "AUTH_TOKEN_POOJA_9921",
"domain": "httpbin.org",
"path": "/"
}])
# STEP 2: Navigate directly to secure dashboard without touching login UI forms
page = context.new_page()
page.goto("https://httpbin.org/cookies")
# Verify browser carries session cookie established by API step
cookies_rendered = page.inner_text("pre")
print(f"[UI Assertion] Verified Browser Session Cookies:\n {cookies_rendered.strip()}")
assert "AUTH_TOKEN_POOJA_9921" in cookies_rendered
print("UI accessed in authenticated state with zero form interaction!")
context.close()
browser.close()
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
context = browser.new_context()
# 1. API SEEDING: Create a high-priority support ticket in backend
ticket_payload = {
"ticket_id": "TCK-8841",
"subject": "Production Database Latency Escalation",
"severity": "P1-Critical",
"assigned_to": "Aarav Sharma"
}
create_res = context.request.post("https://httpbin.org/post", data=ticket_payload)
expect(create_res).to_be_ok()
seeded_ticket = create_res.json()["json"]
print(f"[API Precondition] Ticket seeded successfully: {seeded_ticket['ticket_id']}")
# 2. UI VALIDATION: Navigate to UI and verify seeded record renders properly
page = context.new_page()
page.set_content(f"""
Support Escalations
{seeded_ticket['subject']}
{seeded_ticket['severity']}
{seeded_ticket['assigned_to']}
""")
card = page.locator(f"#{seeded_ticket['ticket_id']}")
expect(card).to_be_visible()
expect(card.locator(".ticket-title")).to_have_text("Production Database Latency Escalation")
expect(card.locator(".severity")).to_have_text("P1-Critical")
print(f"[UI Assertion] Seeded ticket verified in DOM: '{card.locator('.ticket-title').inner_text()}'")
context.close()
browser.close()
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
context = browser.new_context()
page = context.new_page()
# 1. UI ACTION: User updates their notification preferences on screen
page.set_content("""
""")
# User clicks checkbox and submits form in browser
page.locator("#sms-toggle").check()
page.locator("#save-settings").click()
expect(page.locator("#status")).to_have_text("SETTINGS_SAVED")
print("[UI Action] User updated preferences in browser interface.")
# 2. API ASSERTION: Validate backend data matches UI action
# Query backend REST endpoint to inspect persisted state
api_verify_res = context.request.get(
"https://httpbin.org/get",
params={"user": "usr_99", "sms_alerts": "true"}
)
expect(api_verify_res).to_be_ok()
db_state = api_verify_res.json()["args"]
print("[API Verification] Inspected backend state via REST:")
print(f" Target User : {db_state['user']}")
print(f" SMS Alerts : {db_state['sms_alerts']}")
assert db_state["sms_alerts"] == "true"
print("Database record matches UI action perfectly!")
context.close()
browser.close()
api.delete() calls inside teardown blocks, preventing clutter and database pollution without slow browser teardowns.
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
context = browser.new_context()
created_entity_id = "INV-AUTO-9902"
try:
# Step A: UI Test execution creates an entity
page = context.new_page()
page.set_content(f"""
Invoice Reference: {created_entity_id}
GENERATED
""")
expect(page.locator("#invoice-view")).to_be_visible()
print(f"[UI Test] Executed business transaction for {created_entity_id}")
finally:
# Step B: Fast API Teardown guarantees cleanup even if UI tests fail
print(f"[API Teardown] Purging {created_entity_id} from database...")
delete_response = context.request.delete(
"https://httpbin.org/delete",
params={"invoice_id": created_entity_id}
)
expect(delete_response).to_be_ok()
print(f"[API Teardown] Entity {created_entity_id} purged cleanly via HTTP DELETE!")
context.close()
browser.close()
expect(locator).to_be_visible() to auto-wait for rendering.
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
context = browser.new_context()
page = context.new_page()
page.set_content("""
User Account Overview
Credit Limit: ₹ 50,000
""")
# 1. API action updates backend credit limit
api_res = context.request.post("https://httpbin.org/post", data={"credit_limit": 150000})
expect(api_res).to_be_ok()
print("[API Step] Backend credit limit updated to ₹ 1,50,000")
# 2. UI user triggers sync refresh
page.locator("#refresh-btn").click()
# 3. Web-first auto-waiting assertion absorbs asynchronous DOM update
credit_display = page.locator("#credit-status")
expect(credit_display).to_have_text("Credit Limit: ₹ 1,50,000 (Approved)")
print(f"[UI Assertion] Auto-waiting confirmed DOM update: '{credit_display.inner_text()}'")
context.close()
browser.close()
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
# CONTEXT 1: Admin Manager User (Operates purely via API for speed)
admin_context = browser.new_context(
extra_http_headers={"X-User-Role": "Manager", "X-User-ID": "MGR-01"}
)
task_payload = {"task_id": "TSK-990", "assignee": "Pooja Patil", "title": "Playwright Pipeline Audit"}
create_task_res = admin_context.request.post("https://httpbin.org/post", data=task_payload)
expect(create_task_res).to_be_ok()
print("[Role 1: Admin API] Created new assignment: 'Playwright Pipeline Audit'")
# CONTEXT 2: Staff User (Operates via Browser UI)
staff_context = browser.new_context()
staff_page = staff_context.new_page()
staff_page.set_content(f"""
Assigned Tasks for Pooja Patil
- {task_payload['title']} [Pending Review]
""")
task_item = staff_page.locator("#task-list li").first
expect(task_item).to_be_visible()
expect(task_item).to_contain_text("Playwright Pipeline Audit")
print(f"[Role 2: Staff UI] Verified task in staff view: '{task_item.inner_text()}'")
admin_context.close()
staff_context.close()
browser.close()
page object to the test function.
# content of conftest.py
import pytest
from playwright.sync_api import BrowserContext, Page
@pytest.fixture
def seeded_order(context: BrowserContext, page: Page):
"""Hybrid fixture: seeds an order via API, yields details to UI test, then deletes via API."""
# 1. API Setup
order_data = {"order_id": "ORD-HYBRID-771", "item": "Optic Sensor Relay", "price": 4500}
res = context.request.post("https://httpbin.org/post", data=order_data)
assert res.ok
print(f"\n[Fixture Setup] Seeded {order_data['order_id']} via API")
# Yield order info and page instance to test function
yield order_data
# 2. API Teardown
del_res = context.request.delete("https://httpbin.org/delete", params={"id": order_data["order_id"]})
assert del_res.ok
print(f"\n[Fixture Teardown] Cleaned up {order_data['order_id']} via API")
# content of test_orders_ui.py
def test_order_fulfillment_flow(page: Page, seeded_order: dict):
# Test receives pre-seeded order ID instantly without performing UI order creation
page.set_content(f"Order Details: {seeded_order['order_id']}
Status: Ready
")
heading = page.locator("h1")
assert seeded_order["order_id"] in heading.inner_text()
print(f"UI Test validated order {seeded_order['order_id']} successfully!")
expect(response).to_be_ok() works directly on APIResponse objects returned by context.request, providing clean diagnostic output on non-2xx status codes.
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
api = p.request.new_context(base_url="https://httpbin.org")
# Positive validation: expect(response).to_be_ok()
success_res = api.get("/status/200")
expect(success_res).to_be_ok()
print("Positive assertion passed: status code is in 200-299 range.")
# Status inspection
assert success_res.status == 200
assert success_res.status_text == "OK"
# Negative validation
not_found_res = api.get("/status/404")
assert not not_found_res.ok
assert not_found_res.status == 404
print("Negative assertion passed: status code is 404 (not ok).")
api.dispose()
HYBRID TESTING DIVISION OF RESPONSIBILITY MATRIX:
┌──────────────────────────────┬──────────────────┬──────────────────┬──────────────────────────────────────────┐
│ Testing Lifecycle Phase │ Preferred Method │ Secondary Method │ Core Architectural Justification │
├──────────────────────────────┼──────────────────┼──────────────────┼──────────────────────────────────────────┤
│ User Authentication │ ★ API (Tokens) │ UI Form │ UI login across 100+ tests wastes hours. │
│ Data Seeding (Preconditions) │ ★ API (POST) │ UI Entry │ Instant DB entity creation in 50ms. │
│ Target Business Logic │ ★ UI (Clicks) │ API Verification │ Validates real user experience and DOM. │
│ Visual Styling & Layout │ ★ UI (expect) │ N/A │ CSS colors, responsive bounds, overlays. │
│ Backend State Verification │ ★ API (GET) │ UI Inspection │ Verifies database persistence directly. │
│ Test Teardown (Cleanup) │ ★ API (DELETE) │ UI Purge │ Guarantees cleanup even if UI test fails.│
└──────────────────────────────┴──────────────────┴──────────────────┴──────────────────────────────────────────┘
SHARED CONTEXT API SHORTCUTS:
* context.request.get(url, params=...) ──► Dispatches GET sharing browser cookies and headers.
* context.request.post(url, data=...) ──► Dispatches POST sharing browser cookies and headers.
* context.request.delete(url, params=...)──► Dispatches DELETE for fast test teardown.
* context.add_cookies([{"name":...}]) ──► Hydrates browser storage state from API auth response.