Record and Replay Network Traffic with HAR in Playwright Python
Hand-written mocks drift away from what the real server sends. A HAR file (HTTP Archive) fixes that: Playwright records the real requests and responses once, saves them to a file, and later serves them back to the page, so tests run with realistic data, no network and no surprises. In this lesson you will record API traffic to a HAR file, replay it with page.route_from_har(), prove the replay works without the server, control what happens to unrecorded requests, edit recorded data to create edge cases, and add a --update-har option to refresh recordings.
📖 What You’ll Learn: what a HAR file is, recording with record_har_path and record_har_url_filter, recording with route_from_har(update=True), update_content and update_mode, replaying with route_from_har, not_found=”abort” vs “fallback”, how requests are matched, proving a test runs offline, editing HAR responses, a pytest –update-har option, keeping HAR files small and safe, and when HAR is the right tool.
📼 What Is a HAR File?
A HAR (HTTP Archive) file is a JSON document that lists HTTP requests and their responses: URL, method, headers, body, status and timing. Browsers’ DevTools can export one (“Save all as HAR”), and Playwright can both write and read them.
In tests, HAR files give you recorded mocks:
- Record once against the real server.
- Replay in every test run: Playwright answers matching requests from the file.
- Refresh the recording when the API changes.
This lesson uses the mini catalog page from the previous lesson, which loads products from the SQA Tools practice API.
📄 tests/conftest.py
from pathlib import Path
import pytest
from playwright.sync_api import Page
HERE = Path(__file__).parent
CATALOG_URL = "https://sqatools.in/pw-demo/catalog"
API = "**/wp-json/sqa-api/v1/**"
@pytest.fixture
def open_catalog(page: Page):
page.route(CATALOG_URL, lambda route: route.fulfill(path=HERE / "catalog.html"))
def _open():
page.goto(CATALOG_URL)
return page
return _open
🎙️ Recording, Option 1: record_har_path
The simplest way to record is a context option. Everything the context requests (filtered by URL) is written to the file when the context closes:
📄 record_context.py
from pathlib import Path
from playwright.sync_api import expect, sync_playwright
CATALOG_URL = "https://sqatools.in/pw-demo/catalog"
with sync_playwright() as p:
browser = p.chromium.launch()
context = browser.new_context(record_har_path="hars/catalog_full.har", record_har_url_filter="**/sqa-api/**")
page = context.new_page()
page.route(CATALOG_URL, lambda route: route.fulfill(path=Path("tests/catalog.html")))
page.goto(CATALOG_URL)
expect(page.get_by_test_id("product")).to_have_count(5)
context.close() # the HAR file is written here
browser.close()
import json
har = json.load(open("hars/catalog_full.har", encoding="utf-8"))
for entry in har["log"]["entries"]:
print(entry["request"]["method"], entry["request"]["url"], "->", entry["response"]["status"])
⌨️ Terminal
python record_context.py
🖥️ Output
GET https://sqatools.in/wp-json/sqa-api/v1/products?per_page=5 -> 200
record_har_url_filter keeps the file small and free of unrelated traffic (fonts, analytics). Without it, every request of the page would be recorded.
⚠️ Watch out: Forgetting context.close() is the most common reason for an empty or missing HAR file: Playwright writes the archive only when the context is closed.
🎙️ Recording, Option 2: route_from_har(update=True)
The method you will use in tests is route_from_har(). With update=True it records instead of replaying, so the same line of code serves both purposes:
📄 tests/test_record.py
from playwright.sync_api import Page, expect
from tests.conftest import API, HERE
def test_record_catalog(page: Page, open_catalog):
page.route_from_har(HERE / "hars" / "catalog.har", url=API, update=True, update_content="embed")
page = open_catalog()
expect(page.get_by_test_id("product")).to_have_count(5)
⌨️ Terminal
pytest tests/test_record.py -q
🖥️ Output
. [100%]
1 passed in 3.18s
📄 show_har.py
import json
har = json.load(open("tests/hars/catalog.har", encoding="utf-8"))
entry = har["log"]["entries"][0]
print("entries:", len(har["log"]["entries"]))
print("url: ", entry["request"]["url"])
print("status: ", entry["response"]["status"], entry["response"]["content"]["mimeType"])
print("body: ", entry["response"]["content"]["text"][:120], "...")
⌨️ Terminal
python show_har.py
🖥️ Output
entries: 1
url: https://sqatools.in/wp-json/sqa-api/v1/products?per_page=5
status: 200 application/json; charset=UTF-8
body: {"data":[{"id":101,"name":"Wireless Mouse","category":"electronics","price":799,"currency":"INR","in_stock":true,"rating ...
Two options shape the file:
| Option | Values | Meaning |
|---|---|---|
update_content |
"embed" / "attach" |
Put response bodies inside the HAR (one readable file) or in separate files next to it (smaller HAR, binary-friendly) |
update_mode |
"minimal" (default) / "full" |
Record only what replay needs, or everything including timings and cookies |
Use embed for small JSON APIs (easy to read and edit in code review) and attach when responses are large or binary.
▶️ Replaying
Without update=True, route_from_har() serves matching requests from the file. The server is never contacted:
📄 tests/test_replay.py
from playwright.sync_api import Page, expect
from tests.conftest import API, HERE
def test_replay_catalog(page: Page, open_catalog):
page.route_from_har(HERE / "hars" / "catalog.har", url=API)
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")
def test_replay_works_without_the_api(page: Page, open_catalog):
page.route("**/sqa-api/**", lambda route: route.abort()) # "server down" for anything not in the HAR
page.route_from_har(HERE / "hars" / "catalog.har", url=API) # registered last, so it is asked first
page = open_catalog()
expect(page.get_by_test_id("product").first).to_have_text("Wireless Mouse — ₹799")
⌨️ Terminal
pytest tests/test_replay.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_replay.py::test_replay_catalog[chromium] PASSED [ 50%]
tests/test_replay.py::test_replay_works_without_the_api[chromium] PASSED [100%]
============================== 2 passed in 2.27s ==============================
The second test proves the point: the real API is blocked, and the page still shows the products, because the HAR answered first (the most recently registered route runs first, as you saw in the previous lesson).
❔ Requests That Are Not in the HAR
What happens when the page requests something the recording does not contain? The not_found option decides:
not_found |
Unmatched request |
|---|---|
"abort" (default) |
Fails, like a network error |
"fallback" |
Passes to the next route handler, or to the real network |
📄 tests/test_not_found.py
from playwright.sync_api import Page, expect
from tests.conftest import HERE
CATALOG_URL = "https://sqatools.in/pw-demo/catalog"
def other_page(page: Page, per_page: int):
html = (HERE / "catalog.html").read_text(encoding="utf-8").replace("per_page=5", f"per_page={per_page}")
page.route(CATALOG_URL, lambda route: route.fulfill(body=html, content_type="text/html"))
page.goto(CATALOG_URL)
def test_unrecorded_request_is_aborted(page: Page):
page.route_from_har(HERE / "hars" / "catalog.har", url="**/sqa-api/**") # not_found="abort"
other_page(page, per_page=3) # a URL the HAR never saw
expect(page.get_by_test_id("status")).to_contain_text("Could not load products")
def test_unrecorded_request_falls_back_to_network(page: Page):
page.route_from_har(HERE / "hars" / "catalog.har", url="**/sqa-api/**", not_found="fallback")
other_page(page, per_page=3)
expect(page.get_by_test_id("product")).to_have_count(3) # real API answered
⌨️ Terminal
pytest tests/test_not_found.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_not_found.py::test_unrecorded_request_is_aborted[chromium] PASSED [ 50%]
tests/test_not_found.py::test_unrecorded_request_falls_back_to_network[chromium] PASSED [100%]
============================== 2 passed in 4.52s ==============================
Matching is done on the URL including the query string and the HTTP method (and, for POST requests, the body). per_page=3 is a different URL from per_page=5, so it is not in the archive. Use "abort" in CI so a missing recording fails loudly; use "fallback" when only some calls are recorded on purpose.
✏️ Edit Recorded Data for Edge Cases
A HAR file is just JSON, so you can derive edge cases from real data: copy the file, change a value, replay the copy. This keeps the overall shape of the response real while you control one detail:
📄 tests/test_edited_har.py
import json
from playwright.sync_api import Page, expect
from tests.conftest import API, HERE
def make_out_of_stock_har(tmp_path):
har = json.loads((HERE / "hars" / "catalog.har").read_text(encoding="utf-8"))
content = har["log"]["entries"][0]["response"]["content"]
body = json.loads(content["text"])
for product in body["data"]:
product["in_stock"] = False
content["text"] = json.dumps(body)
path = tmp_path / "all_out_of_stock.har"
path.write_text(json.dumps(har), encoding="utf-8")
return path
def test_everything_out_of_stock(page: Page, open_catalog, tmp_path):
page.route_from_har(make_out_of_stock_har(tmp_path), url=API)
page = open_catalog()
expect(page.get_by_test_id("product")).to_have_count(5)
for item in page.get_by_test_id("product").all():
expect(item).to_contain_text("(out of stock)")
⌨️ Terminal
pytest tests/test_edited_har.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_edited_har.py::test_everything_out_of_stock[chromium] PASSED [100%]
============================== 1 passed in 1.64s ==============================
tmp_path is a built-in pytest fixture that gives each test its own temporary folder, so edited copies never overwrite the original recording.
🔄 Refresh Recordings with –update-har
APIs change, and stale recordings hide real breakages. Make refreshing a one-flag operation:
import pytest
def pytest_addoption(parser):
parser.addoption("--update-har", action="store_true", help="re-record HAR files from the real servers")
@pytest.fixture
def har_mode(request) -> dict:
"""Pass to route_from_har(**har_mode): records with --update-har, replays otherwise."""
if request.config.getoption("--update-har"):
return {"update": True, "update_content": "embed"}
return {"not_found": "abort"}
A test then calls page.route_from_har(path, url=API, **har_mode). Normal runs replay; pytest --update-har re-records every HAR the tests use. Review the diff in Git before committing new recordings, exactly as you would review code.
📌 Note: pytest_addoption only works in a root conftest.py (or a plugin). In a real project move the two functions above into your top-level conftest.py.
🧹 Keep HAR Files Small and Safe
- Filter: always record with a URL filter (
record_har_url_filterorurl=inroute_from_har). - Minimal mode: the default
update_mode="minimal"drops timings and other data replay does not need. - Secrets: a HAR contains headers and bodies, which may include cookies, tokens and personal data. Record with test accounts, search the file for
AuthorizationandCookiebefore committing, and never record production user data. - One HAR per feature (catalog, checkout, profile) keeps diffs readable.
⚖️ HAR vs Hand-Written Mocks vs Real API
| Real API | HAR replay | Hand-written route.fulfill |
|
|---|---|---|---|
| Realistic data | Yes | Yes (as of recording) | Only if you copy it |
| Works offline / deterministic | No | Yes | Yes |
| Effort to create | None | One recording run | Write each response |
| Edge cases (errors, empty) | Hard | Edit the file | Easy |
| Detects API changes | Yes | Only when re-recorded | No |
A practical mix: HAR replay for pages that need lots of realistic data, route.fulfill for small edge cases, and a smaller set of tests (plus API tests in Module 9) against the real API.
🏋️ 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: Record all requests to **/sqa-api/** made while opening the catalog into hars/catalog.har using a context option, and make sure the file is actually written.
Show answer
context = browser.new_context(record_har_path="hars/catalog.har", record_har_url_filter="**/sqa-api/**")
page = context.new_page()
# ... open the page and wait for the data ...
context.close() # writes the HARExercise 2: Your replay test fails with “Could not load products” after a developer changed the page to request per_page=10. Why, and what are two ways to fix it?
Show answer
HAR matching includes the query string, so per_page=10 is not in the recording and the default not_found="abort" fails it. Fix: (1) re-record the HAR (pytest --update-har) so it contains the new URL, or (2) temporarily use not_found="fallback" to let unrecorded requests reach the real API. Re-recording is the right long-term fix.
Exercise 3: Write a helper har_with_status(path, status, tmp_path) that copies a HAR and sets the first entry’s response status, so you can test a 503 page from a real recording.
Show answer
import json
def har_with_status(path, status, tmp_path):
har = json.loads(path.read_text(encoding="utf-8"))
har["log"]["entries"][0]["response"]["status"] = status
copy = tmp_path / f"status_{status}.har"
copy.write_text(json.dumps(har), encoding="utf-8")
return copyThen page.route_from_har(har_with_status(HERE / "hars" / "catalog.har", 503, tmp_path), url=API) and expect “HTTP 503”.
Exercise 4: Which two things should you check in a HAR file before committing it?
Show answer
(1) That it contains only the traffic you need (URL filter applied, no analytics or unrelated hosts), and (2) that it contains no secrets or personal data: search for Authorization, Cookie, Set-Cookie, tokens and real emails, and re-record with test accounts if you find any.
🧠 MCQ Quiz: Record and Replay Network Traffic with HAR
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
- What is a HAR file?Answer: A JSON archive of HTTP requests and responses. HTTP Archive files store URLs, methods, headers, bodies, statuses and timings.
- When does a context created with
record_har_pathwrite the file?Answer: When the context is closed. The archive is finalised and saved oncontext.close(). - What does
page.route_from_har(path, update=True)do?Answer: Records matching traffic into the HAR file instead of replaying it.update=Trueswitches the method from replay to recording. - With the default settings, what happens to a request that is not in the HAR?Answer: It is aborted.
not_founddefaults to"abort"; use"fallback"to let it continue. - Which request detail is part of HAR matching?Answer: The full URL including the query string, and the method. A different query string, such as
per_page=3instead ofper_page=5, is a different request. - What does
update_content="attach"do?Answer: Stores response bodies as separate files next to the HAR.attachkeeps bodies in files;embedputs them inside the HAR JSON. - Why is
record_har_url_filter(orurl=) important when recording?Answer: It keeps the file small and free of unrelated or sensitive traffic. Without a filter, fonts, analytics and every other request would be recorded. - In the lesson, how was replay proven to work without the API?Answer: By aborting all API requests with a route registered before route_from_har. The HAR route, registered last, answered first; anything not in the HAR would have hit the abort route.
- What is the risk of committing HAR files without checking them?Answer: They may contain cookies, tokens or personal data. HARs store headers and bodies as recorded, including credentials if present.
- When should you re-record HAR files?Answer: When the API changes, ideally with a one-flag option such as
--update-harand a reviewed diff. Stale recordings hide real API changes; refreshing should be easy and reviewed.
Want a longer, timed test? Take the Module 8 mock interview (20 MCQs in 20 minutes).
❓ Frequently Asked Questions
🤔 Can I replay a HAR exported from Chrome DevTools?
Yes. route_from_har() reads standard HAR files. DevTools exports can be large and contain unrelated traffic, so filter with url= when replaying and remove sensitive headers first.
🤔 Does HAR replay work for the page HTML itself?
Yes, if the document requests are in the HAR and match the url pattern. Most teams replay only API calls and let the real page load, which keeps the front end under test real.
🤔 Can I record with the Playwright CLI?
Yes: playwright open --save-har=example.har --save-har-glob="**/api/**" https://example.com opens a browser, and the HAR is saved when you close it.
🤔 Does route_from_har work at context level?
Yes, context.route_from_har(...) applies the recording to every page in the context, including pop-ups.
🤔 How is HAR different from Playwright’s trace?
A trace (Lesson 62) records actions, DOM snapshots, console and network for debugging after the fact. A HAR stores network traffic in a standard format that can be replayed. You can open a trace’s network tab, but you replay HARs.
🏁 Summary
- A HAR file records real requests and responses; Playwright can write and replay it.
- Record with
record_har_path(written oncontext.close()) orroute_from_har(..., update=True). - Replay with
route_from_har(path, url=...); matching uses method, full URL and body;not_foundchooses abort or fallback. - Edit copies of recordings to create realistic edge cases; refresh recordings with an
--update-haroption and review the diff. - Filter recordings, keep them per feature, and check them for secrets before committing.
🎬 Watch the Playwright tutorial series on YouTube!
Subscribe to SqaToolsByDY • Practice on the SQA Tools Automation Practice Page