---
title: "Playwright Network Interception: Capturing API Calls and Modifying Requests"
description: "Master Playwright's network interception API to capture API responses, log request/response data, mock endpoints, and extract structured data from XHR and fetch calls in your AI agents."
canonical: https://callsphere.ai/blog/playwright-network-interception-capturing-api-calls-modifying-requests
category: "Learn Agentic AI"
tags: ["Playwright", "Network Interception", "API Capture", "Request Mocking", "AI Agents"]
author: "CallSphere Team"
published: 2026-03-18T00:00:00.000Z
updated: 2026-05-06T01:02:46.153Z
---

# Playwright Network Interception: Capturing API Calls and Modifying Requests

> Master Playwright's network interception API to capture API responses, log request/response data, mock endpoints, and extract structured data from XHR and fetch calls in your AI agents.

## Why Network Interception Matters for AI Agents

Modern web applications load data through API calls — REST endpoints, GraphQL queries, and WebSocket connections. Rather than scraping the rendered HTML, an AI agent can intercept these network requests and access the structured JSON data directly. This is faster, more reliable, and produces cleaner data than DOM parsing.

Playwright's `route()` API provides full control over network traffic: intercepting requests, modifying headers, mocking responses, and logging all API activity. This post covers practical patterns for AI agents that need to work with network traffic.

## Listening to Network Events

The simplest approach is passively listening to requests and responses:

```mermaid
flowchart LR
    INPUT(["User intent"])
    PARSE["Parse plus
classify"]
    PLAN["Plan and tool
selection"]
    AGENT["Agent loop
LLM plus tools"]
    GUARD{"Guardrails
and policy"}
    EXEC["Execute and
verify result"]
    OBS[("Trace and metrics")]
    OUT(["Outcome plus
next action"])
    INPUT --> PARSE --> PLAN --> AGENT --> GUARD
    GUARD -->|Pass| EXEC --> OUT
    GUARD -->|Fail| AGENT
    AGENT --> OBS
    style AGENT fill:#4f46e5,stroke:#4338ca,color:#fff
    style GUARD fill:#f59e0b,stroke:#d97706,color:#1f2937
    style OBS fill:#ede9fe,stroke:#7c3aed,color:#1e1b4b
    style OUT fill:#059669,stroke:#047857,color:#fff
```

```python
from playwright.sync_api import sync_playwright

def log_request(request):
    if "api" in request.url:
        print(f">> {request.method} {request.url}")

def log_response(response):
    if "api" in response.url:
        print(f" list[APICapture]:
        with sync_playwright() as p:
            browser = p.chromium.launch()
            page = browser.new_page()
            page.on("response", self._on_response)

            page.goto(url, wait_until="networkidle")

            if actions:
                actions(page)
                page.wait_for_load_state("networkidle")

            browser.close()

        return [c for c in self.captures if c.body is not None]

# Usage
agent = APIExtractorAgent()
api_data = agent.extract(
    "https://example.com",
    actions=lambda page: page.get_by_text("Load Data").click()
)

for capture in api_data:
    print(f"{capture.method} {capture.url} -> {capture.status}")
    if isinstance(capture.body, dict):
        print(f"  Keys: {list(capture.body.keys())}")
```

## Handling WebSocket Connections

Playwright can also monitor WebSocket traffic:

```python
with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page()

    def on_websocket(ws):
        print(f"WebSocket opened: {ws.url}")
        ws.on("framereceived", lambda payload: print(
            f"  WS received: {payload[:100]}"
        ))
        ws.on("framesent", lambda payload: print(
            f"  WS sent: {payload[:100]}"
        ))
        ws.on("close", lambda: print("  WS closed"))

    page.on("websocket", on_websocket)
    page.goto("https://example.com")
    page.wait_for_timeout(5000)

    browser.close()
```

## FAQ

### How do I capture API calls that happen during page load versus after user interaction?

Register your event listeners before calling `page.goto()` to capture load-time API calls. For calls triggered by user interaction, use `page.expect_response()` wrapped around the triggering action. Combining both gives you complete visibility into all network activity throughout the session.

### Can I modify POST request bodies with route interception?

Yes. In your route handler, access the original request body with `route.request.post_data`, parse it, modify the data, and pass it to `route.continue_(post_data=modified_body)`. This is useful for AI agents that need to inject additional parameters into form submissions or API calls.

### Does network interception work with HTTP/2 and HTTP/3?

Playwright handles HTTP/2 transparently — all interception APIs work the same regardless of the HTTP version. HTTP/3 (QUIC) support depends on the browser being used and is still evolving. For most practical purposes, the interception API abstracts away protocol differences entirely.

---

#NetworkInterception #APICapture #Playwright #RequestMocking #WebScraping #AIAgents #HTTPMonitoring

---

Source: https://callsphere.ai/blog/playwright-network-interception-capturing-api-calls-modifying-requests
