Playwright + Python · Lesson 31 of 37

0/37 done

Module 31: Network Interception & Mocking

31. Network Interception & API Mocking with page.route()

18 minlesson

Your task

Implement mock_empty_json(route):

  1. route.fulfill(status=200, content_type="application/json", body="[]")

Write it in the editor, then press Check answer (Ctrl + Enter).

Mocking Network Calls in Python

python
# Mock 500 error on checkout API:
page.route("**/api/checkout", lambda route: route.fulfill(
    status=500,
    content_type="application/json",
    body='{"error": "Payment system down"}'
))

# Abort third-party tracking analytics:
page.route("**/*google-analytics.com/**", lambda route: route.abort())

# Fulfill empty list for search:
page.route("**/api/search?*", lambda route: route.fulfill(
    status=200,
    content_type="application/json",
    body="[]"
))

Key Takeaways & Walkthrough Summary

Testing edge cases like 500 internal server errors or network disconnects is easy with Playwright's page.route(). In this lesson, you will intercept HTTP requests, fulfill custom mock JSON payloads, and abort third-party tracking scripts. Let's master network mocking!

Part of the Playwright + Python course (Playwright with Python). Practice this concept live in the Playwright Online Compiler or explore our free automation practice form.

Common Doubts & Lesson Q&A

Can I mock network requests for an entire browser context?

Yes! Use context.route(...) to intercept and mock requests across all pages and tabs in that context.

Ready? Solve the task in the editor

Use Check answer to mark it complete. Hints are there if you need them.

Python
Skip