API Works in the Browser but Returns 403 in Python? Capture the Response Instead
You found the request in DevTools: Network tab, Fetch/XHR filter, and a JSON response containing the products, prices or listings you need. You copy the URL and headers into Python, run the request, and get this:
403 Forbidden
Or you get 401. Or 200 with an HTML challenge instead of JSON. The page made the call successfully a second earlier, but your HTTP client cannot reproduce it.
If you have not found the endpoint yet, start with how to find the hidden JSON API behind a JavaScript website. Here, you already know the endpoint. The problem is replaying its requests.
Identify What the Refusal Actually Means
The status code alone does not tell you why the request failed. Start with two tests: change the HTTP client, then supply the cookies from the working browser session.
| Test | Result | Likely Explanation |
|---|---|---|
Same URL and headers with curl_cffi and impersonate="chrome" | Now 200 | The server rejected characteristics of your HTTP client |
| Same request plus the cookies the page received | Now 200 | The endpoint requires browser session state |
| Both of the above | Still refused, or works once and then fails | The request may depend on state maintained by the site’s JavaScript |
Also check the response body. A 200 challenge page is not a successful API response.
Client Fingerprinting
Copying Chrome’s HTTP headers does not copy its TLS handshake. Python requests presents a different TLS fingerprint, which services such as Cloudflare can use when deciding whether to accept a request.
If curl_cffi with impersonate="chrome" succeeds without additional session state, browser response capture may be unnecessary. See the TLS fingerprinting guide for the underlying mechanism.
Missing Session Tokens
Target’s store lookup illustrates a different failure. In a test on 2 December 2026, a request to api.target.com/location_fulfillment_aggregations/v1/secured/preferred_stores returned 401, even with every header recorded from the page:
{"message": "Unauthorized", "errors": [{"reason": "[GSP] No authorization header, nor auth cookies found"}]}
Adding the accessToken cookie, which Target set on the first page view, changed the result to 200 with the JSON the page received. curl_cffi without that cookie returned the same 401, so changing the client alone did not solve it.
You do not need a browser for every API call in this case. Obtain the cookie, reuse it until it expires, and refresh the session when necessary. The session persistence guide covers that approach.
State Maintained by Page JavaScript
Bot-defense products such as HUMAN (formerly PerimeterX), Kasada and F5 Distributed Cloud Bot Defense run scripts that collect browser signals. Protected requests can depend on cookies those scripts refresh or additional headers they generate.
A copied request may contain values that are no longer valid when you replay it. Reverse engineering the script also ties your implementation to code that can change between deployments.
When that is the dependency, let the page execute its own JavaScript and make the request. Capture the response rather than reconstructing the request.
Let the Page Make the Call
Playwright can observe responses received by a page. Open the page, perform the action that triggers the API call, and read the bodies of responses whose URLs match your endpoint.
The examples use quotes.toscrape.com/scroll, a practice site that does not block scraping. Its infinite scroll requests /api/quotes?page=N, so you can test the capture logic independently of bot protection.
Install Playwright with pip install playwright, then install its browser with playwright install chromium. The code was run on Playwright 1.59.
Why a Per-Action Wait Can Miss Responses
page.expect_response() waits for a matching response. This version wraps each scroll in that wait, reads the JSON and stops when has_next is false:
from playwright.sync_api import sync_playwright
URL = "https://quotes.toscrape.com/scroll"
FRAGMENT = "/api/quotes"
def is_api_call(response):
return (
FRAGMENT in response.url
and response.request.resource_type in ("xhr", "fetch")
)
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page()
with page.expect_response(is_api_call) as first:
page.goto(URL)
pages = [first.value.json()]
while pages[-1]["has_next"]:
with page.expect_response(is_api_call, timeout=15_000) as nxt:
page.mouse.wheel(0, 20_000) # the page loads more on scroll
pages.append(nxt.value.json())
browser.close()
print([d["page"] for d in pages])
It completes without an exception. But two runs printed:
[1, 2, 3, 4, 6, 8, 9, 11]
[1, 2, 3, 4, 6, 8, 9, 10]
Both runs missed pages 5 and 7; one also missed page 10.
The problem is the assumption that one scroll produces one API response. A scroll sometimes triggered two calls. expect_response() resolved with the first matching response, and this code did not retain the second response if it arrived between waits.
The result was 70 or 80 quotes out of 100, without an error. A successful run of the script was not evidence of a complete dataset.
Keep a Listener Active for the Whole Capture
Register the response listener before triggering requests, retain every matching response, and keep driving the page until the API indicates completion. This version also checks for missing pages:
from playwright.sync_api import sync_playwright
URL = "https://quotes.toscrape.com/scroll"
FRAGMENT = "/api/quotes"
def capture_all(url, fragment, max_scrolls=30):
captured = {} # response URL -> parsed JSON
refused = []
def on_response(response):
if fragment not in response.url:
return
if response.request.resource_type not in ("xhr", "fetch"):
return
if response.status != 200:
refused.append((response.status, response.url))
return
captured[response.url] = response.json()
with sync_playwright() as p:
browser = p.chromium.launch()
context = browser.new_context(service_workers="block")
page = context.new_page()
page.on("response", on_response)
page.goto(url)
for _ in range(max_scrolls):
page.mouse.wheel(0, 20_000)
page.wait_for_timeout(1_000)
done = any(not d["has_next"] for d in captured.values())
if refused or done:
break
browser.close()
if refused:
raise RuntimeError(f"the site refused the page's own calls: {refused[:3]}")
pages = sorted(captured.values(), key=lambda d: d["page"])
missing = set(range(1, pages[-1]["page"] + 1)) - {d["page"] for d in pages}
if missing:
raise RuntimeError(f"pages never arrived: {sorted(missing)}")
return pages
pages = capture_all(URL, FRAGMENT)
quotes = [q for d in pages for q in d["quotes"]]
print(f"{len(pages)} API pages, {len(quotes)} quotes")
Three consecutive runs printed 10 API pages, 100 quotes.
The important choices are:
- Deduplicate by response URL. For this endpoint, each page has a distinct URL. Repeated calls to the same page should not duplicate its records. If your endpoint sends pagination in a request body, URL alone is not a sufficient key.
- Reject unexpected statuses. This example treats anything other than
200as a failure. Do not check only for403; protected endpoints can return other statuses. - Validate completeness. The
missingcheck catches the gaps the first version silently accepted. Use the API’s page numbers, cursors or total count to validate your own capture. - Block service workers. Playwright’s docs recommend
service_workers="block"for network interception because requests a service worker handles can bypasspage.route(). Blocking them also keeps the site’s calls going straight from the page, where the listener sees them.
For an endpoint triggered by a button, replace the scroll with page.get_by_role("button", name="Load more").click(). For search, use page.fill() followed by page.keyboard.press("Enter").
The capture listener stays active regardless of which action triggered the request.
Two Playwright Details That Affect Request Inspection
Use all_headers() When You Need Cookies
request.headers omits security-related headers, including cookie. If you log that dictionary and later replay it, you may leave out the state that made the browser request succeed.
Use request.all_headers() when you need the full header set. In the Target test, the initially logged headers contained no cookie even though the successful request depended on one.
Read Binary Request Bodies as Bytes
request.post_data reads the body as text. A binary payload, such as one used by protobuf or gRPC-web, can raise UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb3.
Use request.post_data_buffer to retrieve the raw bytes. Do not assume every captured API request contains JSON just because the endpoint looks like an API.
Where Response Capture Stops Helping
A response listener gives you what the page received. It cannot turn a browser’s refused request into a successful one.
During the same Target visit, the page’s product search request to redsky.target.com/.../plp_search_v2 failed inside headless Chromium on a cloud server. It returned HTTP 435, a nonstandard status, with a JSON body pointing to captcha.px-cdn.net, HUMAN’s challenge script.
The failure was already present in the browser. Changing the listener would not fix it.
At that point, investigate the browser and connection rather than the response-capture code:
- Test a residential IP instead of a datacenter IP.
- Test a real Chrome build in headed mode instead of headless Chromium. See what separates a Playwright browser from real Chrome.
- Reduce the request pace and preserve the session between pages instead of launching a fresh browser each time.
These are variables to test, not guarantees of access.
Account for the operating cost too. Loading a page in a browser uses more memory and bandwidth than making a direct HTTP request. If supplying the session cookie made your test succeed, obtain it through the browser and make subsequent API calls with curl_cffi. Reserve browser capture for requests that actually depend on page execution.
FAQ
Why does the API URL work when I paste it into my browser’s address bar?
Your browser may already hold the required cookies, and its TLS fingerprint differs from Python’s HTTP client. Python does not automatically inherit either property.
Try the URL in a private window. If it fails there, that points toward session state in your regular browser profile. It is a useful diagnostic, not proof that cookies are the only difference.
Does this work in Node.js?
Yes. Register page.on("response", ...) and read matching bodies with await response.json().
page.waitForResponse() resolves for a matching response; it does not collect every response caused by an action. Repeated one-response waits can leave the same gaps as Python’s expect_response(), so use a persistent listener when one action can trigger several calls.
Can I capture responses without loading images and fonts?
Yes. Use page.route() to abort requests whose resource_type is image, font or media, while allowing the API requests through.
This reduces bandwidth, but test it against your target. Blocking those resources can change the page’s behavior or affect bot checks.
Is it legal to capture a site’s API responses?
Capturing a response does not by itself establish permission to collect or use its contents. Public visibility is not a complete legal test.
Check the site’s terms, avoid personal data and logged-in areas, and keep the request rate close to ordinary browsing. The guide to web scraping legality covers the broader considerations.
Run It on Your Own Target
In Chrome DevTools, identify the API call and choose a URL fragment specific enough to match only the responses you need. Run the client and cookie tests before committing to browser capture.
If capture is necessary, set URL and FRAGMENT in the example. Replace scrolling with the action your page requires, then replace the has_next condition and completeness check with the pagination signals your API exposes.
If you prefer not to operate the browsers yourself, ScrapeUnblocker’s /getPageSource accepts that URL fragment through capture_xhr. It opens the page in a real browser and returns each matching call’s status and body alongside the HTML. Use steps to trigger scrolls or clicks:
import json, requests
r = requests.post(
"https://api.scrapeunblocker.com/getPageSource",
params={"url": "https://quotes.toscrape.com/scroll", "capture_xhr": "/api/quotes"},
headers={"x-scrapeunblocker-key": "YOUR_API_KEY"},
timeout=120,
)
for call in r.json()["xhr"]:
if call["status"] == 200:
data = json.loads(call["body"])
If the site refuses every matching call with 403 or 429, the request is not billed. Check the capture guide for response fields and limits. API keys are available at app.scrapeunblocker.com.
Try ScrapeUnblocker free
95%+ success rate · from 0.55€ per 1,000 calls (VAT may apply) · 500 free requests on signup.