Network Interception and API Mocking in Playwright Python (page.route)

Your front end talks to APIs, and many UI bugs only appear when those APIs answer with an empty list, an error, a slow response or nothing at all. Waiting for a real server to misbehave is not a test strategy. Playwright lets a test sit between the page and the network and decide what every request gets back. In this lesson you will intercept requests with page.route(), replace real API data with your own JSON, simulate server errors, network failures and slow responses, change a real response, check what the page sends, wait for specific responses, and block analytics and ads to make tests faster.

Advertisement

📖 What You’ll Learn: how routing works, page.route and context.route, URL patterns (glob, regex, predicate), route.fulfill with json, status, headers, body and path, route.abort for network failures, holding a route to test loading states, route.fetch to modify real responses, route.continue_ with changed headers, route.fallback, expect_request and expect_response, request.post_data_json, blocking third-party traffic, times and unroute, and what mocking should not replace.


🧭 How Routing Works

Every request the page makes (documents, scripts, images, fetch and XHR calls) passes through Playwright before it reaches the network. When you register a route for a URL pattern, Playwright pauses matching requests and calls your handler, which must do exactly one of these:

Handler call Effect
route.fulfill(...) Answer the request yourself: the server is never contacted
route.abort() Fail the request, as if the network were down
route.continue_(...) Send it to the server (optionally with changed URL, method, headers or body)
route.fetch() + route.fulfill(response=...) Get the real response, change it, then answer
route.fallback() Let the next matching route handler decide

page.route() applies to one page; context.route() applies to every page in the context, including pop-ups.


🛠️ The Demo Page

The lessons need a page whose data comes from an API. The SQA Tools practice REST API has a /products endpoint:

⌨️ Terminal

curl "https://sqatools.in/wp-json/sqa-api/v1/products?per_page=2"

This small HTML page lists products from that API and has a newsletter form that posts to the API’s /echo endpoint:

📄 tests/catalog.html

<!doctype html>
<html>
<head><meta charset="utf-8"><title>Mini catalog</title></head>
<body>
  <h1>Mini catalog</h1>
  <p id="status" data-testid="status"></p>
  <ul id="list" data-testid="list"></ul>
  <button id="reload">Reload</button>
  <form id="subscribe">
    <input id="email" type="email" aria-label="Email" value="tester@example.com">
    <button>Subscribe</button>
  </form>
  <p id="msg" data-testid="msg"></p>
  <script>
    const status = document.getElementById('status'), list = document.getElementById('list');
    async function load() {
      status.textContent = 'Loading…';
      list.innerHTML = '';
      try {
        const r = await fetch('/wp-json/sqa-api/v1/products?per_page=5');
        if (!r.ok) throw new Error('HTTP ' + r.status);
        const body = await r.json();
        list.innerHTML = body.data.map(p =>
          `<li data-testid="product">${p.name} — ₹${p.price}${p.in_stock ? '' : ' (out of stock)'}</li>`).join('');
        status.textContent = body.meta.total + ' products';
      } catch (e) {
        status.textContent = 'Could not load products: ' + e.message;
      }
    }
    document.getElementById('reload').onclick = load;
    document.getElementById('subscribe').onsubmit = async (e) => {
      e.preventDefault();
      const email = document.getElementById('email').value;
      const r = await fetch('/wp-json/sqa-api/v1/echo', {method: 'POST', headers: {'Content-Type': 'application/json'},
                                                         body: JSON.stringify({email, source: 'catalog'})});
      document.getElementById('msg').textContent = r.ok ? 'Subscribed ' + email : 'Subscription failed';
    };
    load();
  </script>
</body>
</html>

The page is served by Playwright itself: a route answers https://sqatools.in/pw-demo/catalog with this file, so the page runs on the sqatools.in origin and its fetch() calls go to the real practice API. Serving a test page through route.fulfill(path=...) is itself a useful technique for testing widgets in isolation.

📄 tests/conftest.py

from pathlib import Path

import pytest
from playwright.sync_api import Page

CATALOG_URL = "https://sqatools.in/pw-demo/catalog"
API = "**/wp-json/sqa-api/v1/products*"


@pytest.fixture
def open_catalog(page: Page):
    """Serve the demo page from a file; API calls still go to the real practice API unless a test mocks them."""
    page.route(CATALOG_URL, lambda route: route.fulfill(path=Path(__file__).parent / "catalog.html"))

    def _open():
        page.goto(CATALOG_URL)
        return page

    return _open

The baseline test runs against real data:

📄 tests/test_real_api.py

from playwright.sync_api import expect


def test_catalog_with_real_api(open_catalog):
    page = open_catalog()
    expect(page.get_by_test_id("product")).to_have_count(5)
    expect(page.get_by_test_id("status")).to_have_text("12 products")

⌨️ Terminal

pytest tests/test_real_api.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
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_real_api.py::test_catalog_with_real_api[chromium] PASSED      [100%]

============================== 1 passed in 3.24s ==============================

Advertisement

🎭 Mock a Response with route.fulfill

Real data changes, and it rarely contains the cases you need, such as an out-of-stock item. Replace the response with your own JSON. Register the route before the page makes the request, so before goto():

📄 tests/test_mock_data.py

from playwright.sync_api import Page, expect

from tests.conftest import API

TWO_PRODUCTS = {
    "data": [
        {"id": 1, "name": "Test Laptop", "price": 50000, "in_stock": True},
        {"id": 2, "name": "Test Phone", "price": 20000, "in_stock": False},
    ],
    "meta": {"total": 2},
}


def test_mocked_products(page: Page, open_catalog):
    page.route(API, lambda route: route.fulfill(json=TWO_PRODUCTS))
    open_catalog()
    expect(page.get_by_test_id("product")).to_have_text(["Test Laptop — ₹50000", "Test Phone — ₹20000 (out of stock)"])
    expect(page.get_by_test_id("status")).to_have_text("2 products")


def test_empty_catalog(page: Page, open_catalog):
    page.route(API, lambda route: route.fulfill(json={"data": [], "meta": {"total": 0}}))
    open_catalog()
    expect(page.get_by_test_id("product")).to_have_count(0)
    expect(page.get_by_test_id("status")).to_have_text("0 products")

⌨️ Terminal

pytest tests/test_mock_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
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_mock_data.py::test_mocked_products[chromium] PASSED           [ 50%]
tests/test_mock_data.py::test_empty_catalog[chromium] PASSED             [100%]

============================== 2 passed in 2.06s ==============================

route.fulfill(json=...) serialises the dictionary, sets Content-Type: application/json and status 200. Other useful arguments: status, headers, body (a string or bytes) and path (a file, as the conftest does).

The empty-list test found a small UX issue: the page shows “0 products” with no friendly message. Mocking makes such edge cases cheap to see.


💥 Errors, Network Failures and Slow APIs

📄 tests/test_failures.py

from playwright.sync_api import Page, expect

from tests.conftest import API


def test_server_error(page: Page, open_catalog):
    page.route(API, lambda route: route.fulfill(status=500, json={"error": "database down"}))
    open_catalog()
    expect(page.get_by_test_id("status")).to_have_text("Could not load products: HTTP 500")


def test_network_failure(page: Page, open_catalog):
    page.route(API, lambda route: route.abort())          # like a dropped connection
    open_catalog()
    expect(page.get_by_test_id("status")).to_contain_text("Could not load products")


def test_loading_state_then_data(page: Page, open_catalog):
    held = []
    page.route(API, lambda route: held.append(route))      # hold the request: no answer yet
    open_catalog()
    expect(page.get_by_test_id("status")).to_have_text("Loading…")

    held[0].continue_()                                     # now let it reach the real API
    expect(page.get_by_test_id("product")).to_have_count(5)

⌨️ Terminal

pytest tests/test_failures.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
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_failures.py::test_server_error[chromium] PASSED               [ 33%]
tests/test_failures.py::test_network_failure[chromium] PASSED            [ 66%]
tests/test_failures.py::test_loading_state_then_data[chromium] PASSED    [100%]

============================== 3 passed in 3.25s ==============================

The last test shows a powerful pattern: a handler that stores the route instead of answering keeps the request pending for as long as you like. You can assert the loading state at leisure, then release it with continue_() or fulfill(). This is deterministic, unlike adding real delays.

💡 Tip: route.abort() accepts an error code such as "failed" (default), "timedout", "connectionrefused" or "internetdisconnected", so you can simulate the exact failure your error handling distinguishes.


✏️ Modify a Real Response with route.fetch

Sometimes you want real data with one change, for example a price that triggers a formatting bug. route.fetch() performs the real request and returns the response; you edit its JSON and fulfil with it:

📄 tests/test_modify.py

from playwright.sync_api import Page, expect

from tests.conftest import API


def test_first_product_price_changed(page: Page, open_catalog):
    def handler(route):
        response = route.fetch()                   # the real API response
        body = response.json()
        body["data"][0]["price"] = 1234567
        route.fulfill(response=response, json=body)  # keep status and headers, replace the body

    page.route(API, handler)
    open_catalog()
    expect(page.get_by_test_id("product").first).to_have_text("Wireless Mouse — ₹1234567")

⌨️ Terminal

pytest tests/test_modify.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
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_modify.py::test_first_product_price_changed[chromium] PASSED  [100%]

============================== 1 passed in 2.57s ==============================

The output exposes a real presentation issue: large prices are printed without digit grouping (₹1234567 rather than ₹12,34,567). That is exactly the kind of bug this technique is for.

route.continue_() can also change the request before it goes out, for example to add a header or point at another environment:

page.route("**/api/**", lambda route: route.continue_(headers={**route.request.headers, "X-Test-Run": "nightly"}))

Advertisement

🔎 Check What the Page Sends

Mocking responses is half of it; often you must verify the request: the right URL, method and body. page.expect_request() waits for a matching request while you trigger it:

📄 tests/test_requests.py

from playwright.sync_api import Page, expect


def test_subscribe_sends_email(page: Page, open_catalog):
    open_catalog()
    with page.expect_request("**/sqa-api/v1/echo") as request_info:
        page.get_by_role("button", name="Subscribe").click()
    request = request_info.value
    assert request.method == "POST"
    assert request.post_data_json == {"email": "tester@example.com", "source": "catalog"}
    expect(page.get_by_test_id("msg")).to_have_text("Subscribed tester@example.com")


def test_reload_calls_api_again(page: Page, open_catalog):
    open_catalog()
    expect(page.get_by_test_id("product")).to_have_count(5)
    with page.expect_response(lambda r: "/products" in r.url and r.status == 200) as response_info:
        page.get_by_role("button", name="Reload").click()
    body = response_info.value.json()
    assert body["meta"]["per_page"] == 5

⌨️ Terminal

pytest tests/test_requests.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
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_requests.py::test_subscribe_sends_email[chromium] PASSED      [ 50%]
tests/test_requests.py::test_reload_calls_api_again[chromium] PASSED     [100%]

============================== 2 passed in 4.90s ==============================
  • expect_request / expect_response take a glob, a regex or a predicate function.
  • The with block starts listening before the click, so a fast response is never missed.
  • request.post_data_json parses the JSON body; response.json() parses the response.

For a log of everything, listen to events instead: page.on("request", ...), page.on("response", ...) and page.on("requestfailed", ...).


🚫 Block Ads, Analytics and Heavy Files

Third-party scripts (analytics, ads, chat widgets) slow tests down and make them flaky, and they are not what you are testing. Block them for the whole context:

📄 tests/test_block.py

import re

from playwright.sync_api import BrowserContext, Page, expect

THIRD_PARTY = re.compile(r"googlesyndication|google-analytics|googletagmanager|doubleclick|adtrafficquality")


def test_practice_page_without_third_parties(context: BrowserContext, page: Page):
    blocked = []

    def handler(route):
        blocked.append(route.request.url.split("/")[2])
        route.abort()

    context.route(THIRD_PARTY, handler)
    context.route("**/*.{png,jpg,jpeg,webp,gif}", lambda route: route.abort())   # skip images too
    page.goto("https://sqatools.in/automation-practice-page/")
    expect(page.locator("#username")).to_be_visible()
    print("\nblocked hosts:", sorted(set(blocked)))

⌨️ Terminal

pytest tests/test_block.py -q -s

🖥️ Output

blocked hosts: ['pagead2.googlesyndication.com', 'sqatools.in', 'www.googletagmanager.com']
.
1 passed in 1.98s

The sqatools.in entry is not a mistake: it is the site’s own copy of an analytics plugin script (.../google-analytics-for-wordpress/.../frontend-gtag.min.js), matched because the regex checks the whole URL, not only the host. That is usually what you want, but check the list once so you do not block something your test needs.

Blocking by host or URL with a regular expression and by file extension with a glob are the two most common patterns. Do not block resources your test checks, of course.


🧩 Patterns, Order, times and unroute

  • Glob: "**/api/products*" (* matches within a path segment, ** across segments, {a,b} alternatives).
  • Regex: re.compile(r"/api/products\?.*page=2") for query strings and alternatives.
  • Predicate: lambda url: "products" in url for anything else.
  • Order: when several routes match, the last registered handler runs first; it can pass the request on with route.fallback().
  • times: page.route(API, handler, times=1) handles only the first matching request, perfect for “fail once, then succeed” retry tests.
  • Removing: page.unroute(API) removes the handler; page.unroute_all() removes all.

📄 tests/test_times.py

from playwright.sync_api import Page, expect

from tests.conftest import API


def test_retry_after_one_failure(page: Page, open_catalog):
    page.route(API, lambda route: route.fulfill(status=503), times=1)   # only the first call fails
    open_catalog()
    expect(page.get_by_test_id("status")).to_have_text("Could not load products: HTTP 503")
    page.get_by_role("button", name="Reload").click()                    # second call reaches the real API
    expect(page.get_by_test_id("product")).to_have_count(5)

⌨️ Terminal

pytest tests/test_times.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
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_times.py::test_retry_after_one_failure[chromium] PASSED       [100%]

============================== 1 passed in 6.57s ==============================

⚖️ When to Mock (and When Not To)

Mock it Do not mock it
Edge cases that are hard to create: empty lists, errors, timeouts The main happy path in your end-to-end smoke tests
Third-party services you do not control (payments, maps, ads) The API contract itself: test it with API tests (Module 9)
Slow or rate-limited dependencies in UI tests Behaviour that depends on real server logic you need to verify

A healthy suite has both: fast UI tests with mocked edge cases and a smaller set of end-to-end tests against real services. Keep mock data realistic (copy a real response and edit it), or your tests will pass against data the server never sends. The next lesson automates that copying with HAR files.


Advertisement

🏋️ 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 mocks the products API so it returns one product with a 300-character name, and checks the list shows exactly one item.

Show answer
def test_very_long_name(page, open_catalog):
    long_name = "Super " * 50
    page.route(API, lambda route: route.fulfill(json={"data": [{"id": 9, "name": long_name, "price": 1, "in_stock": True}], "meta": {"total": 1}}))
    open_catalog()
    expect(page.get_by_test_id("product")).to_have_count(1)

Follow it with a screenshot or a layout assertion to see whether the long name breaks the design.

Exercise 2: Write a route handler that adds an Authorization: Bearer test-token header to every request to **/sqa-api/** and lets it continue to the server.

Show answer
def add_token(route):
    route.continue_(headers={**route.request.headers, "Authorization": "Bearer test-token"})

page.route("**/sqa-api/**", add_token)

Copy the original headers with {**route.request.headers, ...}; passing only the new header would drop the others.

Exercise 3: Test that the catalog shows the timeout error text when the products request times out. Use the right abort error code.

Show answer
def test_timeout(page, open_catalog):
    page.route(API, lambda route: route.abort("timedout"))
    open_catalog()
    expect(page.get_by_test_id("status")).to_contain_text("Could not load products")

The browser reports a network error to fetch, which rejects, so the page shows its error branch.

Exercise 4: Collect the URLs of every failed request during a test and print them at the end. Which event do you use?

Show answer
def test_log_failures(page):
    failed = []
    page.on("requestfailed", lambda request: failed.append(f"{request.url} {request.failure}"))
    page.goto("https://sqatools.in/automation-practice-page/")
    print("\n".join(failed))

requestfailed fires for aborted or network-failed requests; request.failure holds the error text. HTTP errors such as 404 are responses, so check those with page.on("response", ...) and response.status.


🧠 MCQ Quiz: Network Interception and API Mocking

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. What does route.fulfill(json={...}) do?
  2. When must you register a route that mocks the first API call of a page?
  3. How do you simulate a dropped network connection?
  4. What does a handler that only stores the route (and does not answer it) achieve?
  5. How do you change one field of a real API response?
  6. Which method verifies the body the page sent in a POST?
  7. Why is page.expect_response(...) used as a with block around the click?
  8. Several routes match the same URL. Which handler runs first?
  9. What does page.route(pattern, handler, times=1) do?
  10. Which is a good reason NOT to mock an API in a test?

Want a longer, timed test? Take the Module 8 mock interview (20 MCQs in 20 minutes).


Advertisement

❓ Frequently Asked Questions

🤔 Does page.route work for requests from service workers?

Requests made by a service worker are not seen by page.route(). Use context.route() or block service workers with browser_context_args = {..., "service_workers": "block"} when you need to mock them.

🤔 Can I mock WebSockets?

Yes. Playwright has page.route_web_socket(), which lets you intercept a WebSocket and send your own messages. It is a separate API from page.route().

🤔 Why is my route not called?

Usually the pattern does not match (check query strings: a glob such as **/products does not match /products?page=1; use **/products*), the route was registered after the request was made, or the request comes from a service worker.

🤔 Can I use route with the async API?

Yes. In the async API the handler is async def handler(route): await route.fulfill(...) and you await page.route(...). Lesson 69 covers the async API.

🤔 Should mocks live in the test or in fixtures?

Put reusable mocks (for example “catalog with an out-of-stock item”) in fixtures or a small helper module, and keep one-off edge cases in the test that needs them.


🏁 Summary

  • page.route(pattern, handler) intercepts matching requests; register it before the request happens.
  • route.fulfill(json=..., status=..., path=...) mocks responses; route.abort() simulates network failures.
  • Hold a route to test loading states; use route.fetch() to modify real responses and route.continue_() to change requests.
  • expect_request / expect_response verify traffic; context.route() blocks ads, analytics and heavy files for every page.
  • Mock edge cases and third parties, but keep real end-to-end tests and API contract tests.

🎬 Watch the Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on the SQA Tools Automation Practice Page