REQUEST MOCKING & API VIRTUALIZATION

Master deterministic API simulation in Playwright with Python: mocking microservices, JSON fixture hydration, synthetic latency injection, selective response tampering, error state replication, and offline test virtualization.

🎭 Deterministic UI Testing via API Virtualization

Modern frontend Single Page Applications (SPAs) depend heavily on asynchronous REST and GraphQL endpoints for data rendering, authorization gates, and operational telemetry. End-to-end testing against live staging environments often introduces test flakiness due to schema drift, rate-limiting, third-party vendor outages, or slow database migrations. Playwright Request Mocking allows engineering teams to construct virtual service layers directly within the browser runtime. Using page.route() and route.fulfill(), tests can decouple the user interface from backend infrastructure, inject static JSON fixtures, simulate high-latency edge networks, and validate critical UI recovery states under catastrophic 5xx failures.

1. Service Virtualization Architecture: Live vs. Mocked Traffic
Playwright intercepts API calls before they reach the network socket layer. Mocked requests never hit your web server, providing zero latency, predictable test data, and total hermeticity across parallel test workers.
Mocking Routing Topology
LIVE ENDPOINT FLOW (High Latency, Environment-Dependent, Prone to Flakiness):
[ UI Component: fetch() ] ──Network Socket──► [ Gateway / CDN ] ──► [ Staging DB ] ──► [ Response ]

VIRTUALIZED ROUTE MOCKING (Sub-millisecond, Deterministic, Offline-Capable):
[ UI Component: fetch() ]
           β”‚
           β–Ό (DevTools Protocol Hook)
[ Playwright Route Interceptor: page.route("**/api/v2/orders/*") ]
           β”‚
           β”œβ”€β”€ Matches URL Pattern?
           β”œβ”€β”€ YES ──► route.fulfill(status=200, json={...mockData...})  ──► Instantly renders UI!
           └── NO  ──► route.continue_()                                ──► Hits external server
Engineering Value: Tests execute 10x faster and run with 100% deterministic repeatability regardless of network state or backend availability.
Real-Time Example 1: Mocking REST API with Native JSON Parameter (json=...)
Playwright's route.fulfill() accepts a native Python dictionary or list directly into the json keyword argument, automatically serializing the data and setting Content-Type: application/json.
Python (Native json= Parameter)
from playwright.sync_api import sync_playwright, expect

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()

    # Define mock dataset using native Python structures
    mock_inventory = [
        {"sku": "SKU-901", "name": "Optic Sensor Relay", "price": "β‚Ή 1,299", "in_stock": True},
        {"sku": "SKU-902", "name": "Industrial IoT Gateway", "price": "β‚Ή 4,850", "in_stock": True}
    ]

    # Intercept API endpoint and supply JSON directly
    page.route("**/api/v1/catalog/items", lambda route: route.fulfill(
        status=200,
        json=mock_inventory
    ))

    page.set_content("""
        

Warehouse Inventory Hub

    Loading items...
""") first_item = page.locator("#items-list li").first expect(first_item).to_have_text("Optic Sensor Relay - β‚Ή 1,299") items_count = page.locator("#items-list li").count() print(f"Mocked items rendered in DOM: {items_count}") print(f"Verified First Item Text : '{first_item.inner_text()}'") browser.close()
Output: Mocked items rendered in DOM: 2 Verified First Item Text : 'Optic Sensor Relay - β‚Ή 1,299'
Real-Time Example 2: Loading External JSON Fixture Files
Decouple large test payloads from Python test scripts by maintaining standardized JSON fixture files on disk and hydrating routes directly via path.
Python (Fixture File Hydration)
import os
import json
import tempfile
from playwright.sync_api import sync_playwright, expect

# Setup external temporary fixture file simulating tests/fixtures/user_account.json
temp_dir = tempfile.gettempdir()
fixture_file = os.path.join(temp_dir, "account_fixture.json")
with open(fixture_file, "w") as f:
    json.dump({
        "account_id": "ACC-IN-2026",
        "company": "Nikita Infotech Systems",
        "tier": "Enterprise Premier",
        "active_seats": 48
    }, f)

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()

    # Route fulfill points directly to the external JSON fixture path
    page.route("**/api/account/details", lambda route: route.fulfill(
        status=200,
        content_type="application/json",
        path=fixture_file
    ))

    page.set_content("""
        

Account Summary

Pending...
Pending...
""") company_label = page.locator("#company-name") plan_label = page.locator("#plan-tier") expect(company_label).to_have_text("Nikita Infotech Systems") expect(plan_label).to_have_text("Enterprise Premier") print(f"Loaded external fixture successfully: '{company_label.inner_text()}' ({plan_label.inner_text()})") browser.close() if os.path.exists(fixture_file): os.remove(fixture_file)
Output: Loaded external fixture successfully: 'Nikita Infotech Systems' (Enterprise Premier)
Real-Time Example 3: Simulating Network Latency & Loading Spinners
Test loading states, skeleton screens, and progress indicators by artificially delaying the fulfillment of a mocked route to observe intermediate UI states before completion.
Python (Artificial Latency Injection)
import time
from playwright.sync_api import sync_playwright, expect

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()

    def delayed_fulfillment(route):
        # Simulate network latency (e.g. 500ms delay)
        time.sleep(0.5)
        route.fulfill(
            status=200,
            json={"status": "READY", "summary": "Financial Records Reconciled"}
        )

    page.route("**/api/reconcile", delayed_fulfillment)

    page.set_content("""
        
        
        
Idle
""") btn = page.locator("#reconcile-btn") spinner = page.locator("#spinner") result = page.locator("#result") # Click to start delayed request btn.click() # Verify intermediate loading state is visible expect(spinner).to_be_visible() print("Intermediate loading spinner observed during network delay.") # Auto-waiting assertion verifies final state once route completes expect(spinner).to_be_hidden() expect(result).to_have_text("Financial Records Reconciled") print(f"Final state settled: '{result.inner_text()}'") browser.close()
Output: Intermediate loading spinner observed during network delay. Final state settled: 'Financial Records Reconciled'
Real-Time Example 4: Testing Frontend Recovery on Server Errors (400, 401, 503)
Simulate edge cases that are difficult to reproduce against live backend systems, such as expired JWT authentication (401 Unauthorized) or service downtime (503 Service Unavailable).
Python (HTTP Error Code Mocking)
from playwright.sync_api import sync_playwright, expect

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()

    # Intercept session validation endpoint and return HTTP 401 Unauthorized
    page.route("**/api/v1/session/verify", lambda route: route.fulfill(
        status=401,
        json={"error": "SESSION_EXPIRED", "message": "Access token has expired."}
    ))

    page.set_content("""
        
""") page.locator("#check-auth").click() modal = page.locator("#auth-modal") expect(modal).to_be_visible() expect(modal.locator("h3")).to_have_text("Session Expired") print(f"Frontend correctly handled HTTP 401: Modal displayed '{modal.locator('h3').inner_text()}'") browser.close()
Output: Frontend correctly handled HTTP 401: Modal displayed 'Session Expired'
Real-Time Example 5: GraphQL Endpoint Query Mocking
GraphQL sends all queries to a single /graphql URL via HTTP POST. Inspect the request's post data to conditionally fulfill specific GraphQL operations while letting others pass through.
Python (GraphQL Operation Routing)
import json
from playwright.sync_api import sync_playwright, expect

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()

    def handle_graphql(route):
        post_data = route.request.post_data_json or {}
        operation_name = post_data.get("operationName")

        if operation_name == "GetUserProfile":
            route.fulfill(
                status=200,
                json={
                    "data": {
                        "user": {"id": "U-100", "username": "pooja_patil", "role": "Lead Architect"}
                    }
                }
            )
        elif operation_name == "GetOrderHistory":
            route.fulfill(
                status=200,
                json={
                    "data": {
                        "orders": [{"id": "ORD-1", "total": "β‚Ή 4,500"}]
                    }
                }
            )
        else:
            route.continue_()

    page.route("**/graphql", handle_graphql)

    page.set_content("""
        

GraphQL Dashboard

Querying user...
""") user_label = page.locator("#user-display") expect(user_label).to_have_text("pooja_patil (Lead Architect)") print(f"GraphQL operation 'GetUserProfile' mocked successfully: '{user_label.inner_text()}'") browser.close()
Output: GraphQL operation 'GetUserProfile' mocked successfully: 'pooja_patil (Lead Architect)'
Real-Time Example 6: Query Parameter Pattern Matching with Regex
Use compiled Python regular expressions in page.route() to match complex dynamic query strings, search parameters, and paginated URLs.
Python (Regex URL Mocking)
import re
from playwright.sync_api import sync_playwright, expect

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()

    # Matches: /api/v2/search?query=...&page=...
    search_pattern = re.compile(r".*/api/v2/search\?query=.*&page=\d+")

    def handle_search(route):
        url = route.request.url
        print(f"Intercepted Regex Matched URL: {url}")
        route.fulfill(
            status=200,
            json={
                "query": "playwright",
                "total_results": 1,
                "items": [{"title": "Mastering Playwright Python", "link": "/course/pw-py"}]
            }
        )

    page.route(search_pattern, handle_search)

    page.set_content("""
        

Search Engine

Searching...
""") results_div = page.locator("#results") expect(results_div).to_have_text("Found 1: Mastering Playwright Python") print(f"Search results successfully verified: '{results_div.inner_text()}'") browser.close()
Output: Intercepted Regex Matched URL: http://localhost/api/v2/search?query=playwright&page=1 Search results successfully verified: 'Found 1: Mastering Playwright Python'
Real-Time Example 7: Context-Level vs. Page-Level Routing Scopes
Apply route mocking across the entire BrowserContext to ensure multi-tab workflows, popups, and iframes share the same virtual service layer without registering routes on each tab individually.
Python (Context-Level Route Virtualization)
from playwright.sync_api import sync_playwright, expect

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    # Define route rule on the BrowserContext level
    context = browser.new_context()

    context.route("**/api/config/flags", lambda route: route.fulfill(
        status=200,
        json={"feature_beta_export": True, "maintenance_mode": False}
    ))

    # Tab 1: Opens and fetches configuration
    tab1 = context.new_page()
    tab1.set_content("""
        
Loading...
""") # Tab 2: Opens in parallel and accesses the same endpoint tab2 = context.new_page() tab2.set_content("""
Loading...
""") expect(tab1.locator("#t1-flag")).to_have_text("ENABLED") expect(tab2.locator("#t2-flag")).to_have_text("ENABLED") print(f"Context-level route applied to Tab 1: '{tab1.locator('#t1-flag').inner_text()}'") print(f"Context-level route applied to Tab 2: '{tab2.locator('#t2-flag').inner_text()}'") context.close() browser.close()
Output: Context-level route applied to Tab 1: 'ENABLED' Context-level route applied to Tab 2: 'ENABLED'
Real-Time Example 8: Deregistering Routes with unroute()
Remove an active route handler during test execution using page.unroute() to transition from mock data back to live backend integration dynamically.
Python (unroute Dynamic Teardown)
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()

    handler_calls = 0

    def mock_handler(route):
        nonlocal handler_calls
        handler_calls += 1
        route.fulfill(status=200, body="MOCKED_RESPONSE")

    target_pattern = "**/api/ping"

    # Step 1: Register mock route
    page.route(target_pattern, mock_handler)

    # Trigger request 1
    page.goto("https://example.com")
    res1 = page.evaluate("() => fetch('/api/ping').then(r => r.text())")
    print(f"Request 1 Result (Route Active)    : '{res1}'")

    # Step 2: Unroute pattern
    page.unroute(target_pattern, mock_handler)
    print("Deregistered route handler with page.unroute()")

    print(f"Total times mock handler was executed: {handler_calls}")
    browser.close()
Output: Request 1 Result (Route Active) : 'MOCKED_RESPONSE' Deregistered route handler with page.unroute() Total times mock handler was executed: 1
Real-Time Example 9: Request Mocking API Reference Matrix
A comprehensive reference summary of methods, options, and parameters supported by Playwright's route virtualization API in Python.
Route API Reference Matrix
PLAYWRIGHT ROUTE MOCKING & VIRTUALIZATION MATRIX:
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Method / Argument            β”‚ Types                        β”‚ Description / Primary Use Case                          β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ page.route() / context.route β”‚ url: str / Pattern, handler  β”‚ Intercepts matching requests at page or context scope.  β”‚
β”‚ route.fulfill(status=...)    β”‚ status: int (default: 200)   β”‚ Returns custom HTTP status code (200, 401, 500, etc.).  β”‚
β”‚ route.fulfill(json=...)      β”‚ json: Dict / List            β”‚ Directly passes Python dictionary/list as JSON payload. β”‚
β”‚ route.fulfill(body=...)      β”‚ body: str / bytes            β”‚ Supplies raw string or binary response body.            β”‚
β”‚ route.fulfill(path=...)      β”‚ path: str                    β”‚ Hydrates response body directly from external file.     β”‚
β”‚ route.fulfill(headers=...)   β”‚ headers: Dict[str, str]      β”‚ Sets custom HTTP response headers.                      β”‚
β”‚ route.fulfill(content_type=) β”‚ content_type: str            β”‚ Shortcut for setting Content-Type header.               β”‚
β”‚ route.abort(error_code=...)  β”‚ error_code: Optional[str]    β”‚ Fails request with connection error ("failed", etc.).   β”‚
β”‚ route.continue_()            β”‚ headers, post_data, method   β”‚ Forwards request to real server with optional overrides.β”‚
β”‚ route.fetch()                β”‚ kwargs                       β”‚ Fetches real upstream response for inspect-and-modify.  β”‚
β”‚ page.unroute()               β”‚ url, handler                 β”‚ Deregisters active route pattern.                       β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Engineering Best Practice: Keep UI tests fast and deterministic by mocking backend API dependencies via route.fulfill(json=...). Reserve full end-to-end un-mocked requests for smoke test runs on live staging environments.