Your Target Wants Special Headers: Send Them Through
Some pages only render for the right headers. Learn how to pass your own Accept-Language, Referer, and auth headers through a scraping API request.
On this page
It’s Your Headers, Not Your IP
Some pages don’t block you with a captcha or a challenge page. They just quietly serve you the wrong thing. You request a product page and get a 403. You request a localized storefront and get English prices when you asked for German. You request an account page and get bounced to a login form. Nine times out of ten, the difference between the version that works and the version that doesn’t isn’t your IP — it’s your headers.
This post walks through the three headers that cause most of that pain (Accept-Language, Referer, and Authorization), how servers actually validate them, and how to forward your own header set through a scraping API so the target site sees the request you meant to send.
Why Pages Silently Block Requests Without the Right Headers
Anti-bot systems fingerprint more than IPs. A request arriving with Accept-Language: *, no Referer, and a default Python requests user agent looks nothing like a browser, and plenty of origin servers act on that. Some return 403. Worse, some return 200 with a block page — if you haven’t read your 200 OK responses that are actually block pages, that failure mode will cost you a weekend.
Here’s the same URL, two header sets, two outcomes:
| Header | Browser-like set | Default client set |
|---|---|---|
User-Agent | Chrome on Windows | python-requests/2.x |
Accept | text/html,application/xhtml+xml | */* |
Accept-Language | en-US,en;q=0.9 | (absent) |
Referer | https://example.com/products | (absent) |
| Result | 200, full product page | 403 Forbidden |
The raw request that fails looks innocent enough:
curl -i https://example.com/product/123
HTTP/1.1 403 Forbidden
content-type: text/html
<!-- 41 bytes of "you are not authorized" and nothing else -->
No error message. No retry hint. The server decided from the header fingerprint alone that this request wasn’t worth serving. Your retry loop will hammer that 403 forever, which is why service-side retries and client-side retries behave so differently — retrying a header-shaped failure never fixes it.
The Three Headers That Matter Most: Accept-Language, Referer, and Authorization
Most header pass-through problems collapse into three buckets. Here’s a full, annotated header set for a request to example.com:
# Language negotiation — server picks locale from this
Accept-Language: de-DE,de;q=0.9,en;q=0.8
# Referrer check — some paths only render when you "came from" the right place
Referer: https://example.com/plans
# Session or API auth — required for account-scoped pages
Authorization: Bearer eyJhbGciOi...
# Standard browser headers — missing these is itself a signal
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding: gzip, deflate, br
What each one triggers server-side:
| Header | Server-side check it triggers | When scraping needs it |
|---|---|---|
Accept-Language | Locale routing: content negotiation picks language, currency, date formats | Localized storefronts, region-specific pricing |
Referer | Referrer allowlists: deep paths (step-two forms, download links) that check the hop origin | Multi-step flows, “continue” pages, some download links |
Authorization / Cookie | Session or token validation: account-scoped content, personalized pricing | Logged-in views, API-backed pages you already have credentials for |
A note on scope: I’m deliberately ignoring User-Agent here. Most scraping APIs inject a coherent browser fingerprint for you — TLS, headers, and all — and overriding just the user agent string while the TLS handshake says something else makes you more detectable, not less. If you want the background on that mismatch, TLS fingerprinting explained covers it in detail. The three headers above are the ones you should be setting yourself, because only you know which locale, which hop, and which token the request needs.
Passing Custom Headers Through a Scraping API Request
The naive fix is to run your own HTTP client with the right headers:
import requests
resp = requests.get(
"https://example.com/pricing",
headers={
"Accept-Language": "en-US,en;q=0.9",
"Referer": "https://example.com/plans",
"Authorization": "Bearer eyJhbGciOiJIUzI1NiIs...",
},
timeout=30,
)
That works until you need proxy rotation, JS rendering, or geographic exits — at which point your headers and your infrastructure split into two things you have to keep in sync. The cleaner move is to declare the headers in the scrape request payload and let the API forward them to the target.
The sync endpoint takes a headers object in the request body:
import requests
payload = {
"url": "https://example.com/pricing",
"use_js_render": True,
"formats": ["markdown"],
"headers": {
"Accept-Language": "en-US,en;q=0.9",
"Referer": "https://example.com/plans",
"Authorization": "Bearer eyJhbGciOiJIUzI1NiIs..."
}
}
resp = requests.post(
"https://api.finedata.ai/api/v1/scrape",
json=payload,
headers={"Authorization": "Bearer fd_your_api_key"},
timeout=180,
)
data = resp.json()
Whatever you put in headers gets attached to the outgoing request to the target URL. The same field exists on the async endpoint (POST /api/v1/async/scrape) and on batch items, so a batch of 500 URLs can each carry their own header set — useful when half your URLs need German and half need French.
To verify the pass-through actually happened, point the request at an echo endpoint and read back what arrived:
payload["url"] = "https://example.com/headers-debug"
echo = requests.post(
"https://api.finedata.ai/api/v1/scrape",
json=payload,
headers={"Authorization": "Bearer fd_your_api_key"},
timeout=180,
).json()
# The echoed page shows the target received exactly what you sent:
# "accept-language": "en-US,en;q=0.9"
# "referer": "https://example.com/plans"
# "authorization": "Bearer eyJhbGciOiJIUzI1NiIs..."
If the echo shows your headers, they went through. If it shows defaults, something upstream dropped them — jump to the debugging section below before you waste an afternoon blaming the target site.
Matching Accept-Language to the Content You Actually Want
Accept-Language is the header people forget most and regret most. Plenty of storefronts ignore your URL path and negotiate content purely from the header. You request https://example.com/en/pricing and get English, sure. But you request the German page with an English header and half the time you get English anyway — or worse, German text with USD prices.
Same URL, two headers, two different pages:
Accept-Language: en-US | Accept-Language: de-DE | |
|---|---|---|
| Price format | $49.00 | 49,00 € |
| Currency | USD | EUR |
| Date format | 12/01 (month/day) | 01.12. (day.month) |
| Legal links | US terms | DE impressum |
If you’re building price comparison or market coverage across locales, you need deliberate control over this header per request. Here’s a rotation pattern for locale coverage:
locales = ["en-US", "de-DE", "fr-FR", "ja-JP"]
for locale in locales:
payload = {
"url": "https://example.com/pricing",
"formats": ["markdown"],
"headers": {"Accept-Language": f"{locale},{locale.split('-')[0]};q=0.9"},
}
result = requests.post(
"https://api.finedata.ai/api/v1/scrape",
json=payload,
headers={"Authorization": "Bearer fd_your_api_key"},
timeout=180,
).json()
# store result keyed by locale, not just by URL
One caveat from experience: some sites route locale by geo-IP first and header second. If your exit IP is in Frankfurt, no header will convince the site you’re a US visitor. In that case pair Accept-Language with proxy_country: "US" on the same request — the header and the exit have to agree, or the geo check wins. That pairing is covered properly in scraping localized storefronts with a country exit code.
Setting a Referer That Passes Referrer Checks
Some pages check where you came from. Step-two forms are the classic case: request example.com/signup cold and you get a redirect back to the plans page. Arrive from the plans page and it renders. The server isn’t checking your identity — it’s checking the hop.
Without the header:
payload = {"url": "https://example.com/signup", "formats": ["markdown"]}
# Result: redirect to /plans, no signup content
With it:
payload = {
"url": "https://example.com/signup",
"formats": ["markdown"],
"headers": {
"Referer": "https://example.com/plans"
}
}
# Result: 200, full signup page
Which referer values pass, in rough order of reliability:
Usually passes:
- Same-domain path one step earlier in the real flow (
/plans→/signup) - Same-domain category or listing page for product detail URLs
- A search engine result page referer, for sites that treat organic traffic generously
Usually trips something:
- Empty referer on a path that requires one (obvious, but it’s the default state)
- Cross-origin referers from unrelated domains —
https://blog.randomsite.netpointing at a step-two form is a red flag on its face - Referer values that don’t parse as URLs, or contain obvious template artifacts like
{referer}left in from a config bug
My honest opinion: I don’t bother fabricating search-engine referers. If a same-domain referer from the natural previous step doesn’t pass the check, the site is doing something smarter than referrer matching, and a fake Google URL won’t save you — you’ll need the sticky session approach instead (keeping one exit IP across multi-step scrape requests covers the session side of that).
Forwarding Authorization Headers and Cookies Without Leaking Them
Now the part where people get burned. Passing an auth token through a scraping API means your session credential leaves your infrastructure and rides along on a request you don’t fully control. That’s sometimes exactly what you need — account-scoped pages, personalized pricing, saved preferences — but treat the token like a production secret, because it is one.
The mechanics are simple. Authorization and Cookie are just headers:
payload = {
"url": "https://example.com/account",
"formats": ["markdown"],
"headers": {
"Authorization": "Bearer eyJhbGciOiJIUzI1NiIs...",
"Cookie": "session_id=abc123; locale=de-DE",
"Accept-Language": "de-DE,de;q=0.9"
}
}
result = requests.post(
"https://api.finedata.ai/api/v1/scrape",
json=payload,
headers={"Authorization": "Bearer fd_your_api_key"},
timeout=180,
).json()
Note the two Authorization headers doing two completely different jobs there. The outer one authenticates you to the scraping API. The inner one, inside payload["headers"], is what gets forwarded to the target site. Keep them straight in your head, because a script that accidentally puts the target token in the outer header is a script that leaks a credential to a third party and fails the scrape simultaneously.
Now the failure handling. A 401 from the target can mean three different things, and your retry logic should tell them apart:
import base64
import json
import time
TOKEN_TTL = 3600 # seconds — set this to your token's actual lifetime
def token_age(token):
"""Seconds since the JWT was issued, read from its `iat` claim."""
part = token.split(".")[1]
part += "=" * (-len(part) % 4) # re-pad the base64
claims = json.loads(base64.urlsafe_b64decode(part))
return time.time() - claims["iat"]
token = payload["headers"]["Authorization"].split(" ", 1)[1]
status = result.get("status")
if status == "failed":
http_code = result.get("http_code")
if http_code == 401:
# Distinguish: token expired vs. token never sent vs. token wrong scope
if "Authorization" not in payload["headers"]:
print("missing header — pass-through bug, not a credential problem")
elif token_age(token) > TOKEN_TTL:
print("expired token — refresh and resubmit")
else:
print("token rejected — check scope/audience for this endpoint")
# Do NOT auto-retry. A 401 will 401 again.
The distinction matters because an expired token is recoverable — refresh and resubmit — while a scope problem means you’re asking the token for something it was never granted, and no number of retries fixes that. Blindly retrying 401s also hammers a target’s auth endpoint, which is exactly the kind of traffic pattern that gets your token revoked outright.
One more thing on cookies: prefer Cookie headers over trying to replay a login flow through the scraper unless you genuinely need fresh sessions. A captured cookie is one moving part; a scripted login is five (credentials, CSRF token, redirect chain, session cookie extraction, expiry handling). If you do need the login flow, the fix for scraper login sessions walks through it.
Debugging Header Pass-Through: Verifying What the Target Actually Received
When a header-dependent scrape fails, you need to answer one question fast: did my headers arrive? Everything else is downstream of that.
The echo test is your first move. Send the exact payload you’re debugging against an endpoint that reflects headers back:
debug_payload = dict(payload) # your real payload
debug_payload["url"] = "https://example.com/headers-debug"
echo = requests.post(
"https://api.finedata.ai/api/v1/scrape",
json=debug_payload,
headers={"Authorization": "Bearer fd_your_api_key"},
timeout=180,
).json()
# Parse the echoed header list into a dict — one "name: value" per line
received = {}
for line in echo["data"]["markdown"].splitlines():
name, sep, value = line.partition(":")
if sep:
received[name.strip().lower()] = value.strip()
# Membership test against the parsed echo, not a loose substring match
intended = payload["headers"]
for name, value in intended.items():
got = received.get(name.lower())
if got == value:
print(f"{name}: OK")
else:
print(f"{name}: DROPPED (echoed as {got!r})")
Diff the echo against your intended set header by header. If everything’s present and the scrape still fails, the problem is the header values, not the transport — and that’s a much narrower search.
The failure modes you’ll actually hit, with their signatures:
| Symptom | Likely cause | Fix |
|---|---|---|
| Header absent from echo | Sent in the wrong place (query params instead of payload, or outer request instead of headers) | Move it into the headers object of the JSON body |
| Value truncated in echo | Header value too large — big cookies or long JWTs can hit size limits | Split the cookie, or use a shorter-lived token |
| 400 from the scraping API | Malformed header name (space, newline, non-ASCII) | Validate names against RFC 7230 token rules before submitting |
| Target sees different casing | Some stacks normalize to lowercase | Match on lowercase names in your echo-diff, casing isn’t the problem |
| Works in curl, fails in Python | curl sends from your IP with your locale defaults; the Python path differs elsewhere | Diff everything — headers, exit geo, TLS — not just headers |
That last row is the one that eats hours. Your local curl request succeeds for reasons that have nothing to do with your header set — your residential IP, your system locale, your existing cookies. The echo test through the scraping API removes those confounders because you’re comparing the forwarded request against itself.
For deeper verification, I keep a local echo server for exactly this purpose — auditing what your scraper sends with a local echo server has the harness.
Best Practices: Header Hygiene, Rotation, and Staying Polite
Headers should be boring. A request whose headers tell a coherent story — one locale, one plausible referer, one consistent device profile — draws less attention than a request with a grab-bag of “browser-like” values that no real client would ever send together.
I keep header sets as named profiles, applied per target:
HEADER_PROFILES = {
"example.com": {
"Accept-Language": "en-US,en;q=0.9",
"Referer": "https://example.com/plans",
},
"www.example.com": {
"Accept-Language": "de-DE,de;q=0.9,en;q=0.8",
},
}
def build_payload(url, extra=None):
domain = url.split("/")[2]
headers = dict(HEADER_PROFILES.get(domain, {}))
if extra:
headers.update(extra)
return {"url": url, "formats": ["markdown"], "headers": headers}
# Two targets, two coherent profiles, one code path:
for url in ["https://example.com/signup",
"https://www.example.com/en/pricing"]:
payload = build_payload(url)
requests.post(
"https://api.finedata.ai/api/v1/scrape",
json=payload,
headers={"Authorization": "Bearer fd_your_api_key"},
timeout=180,
)
On rotation: you’ll see advice to randomize Accept-Language and Referer per request. Mostly don’t. Rotating Accept-Language breaks locale determinism — you lose the ability to say “this row is the German price” — and rotating referers buys you almost nothing because referrer checks validate plausibility, not uniqueness. The header that genuinely benefits from variation is your auth token, when you have several valid sessions: rotate those per request so no single token generates your entire traffic pattern.
| Hardcoded single set | Rotated pool | |
|---|---|---|
| Locale determinism | Exact, reproducible | Random — hard to attribute rows |
| Auth token load | One token takes all traffic | Spread across sessions |
| When to use | Almost always | Only for multi-token account scraping |
And the obvious closing point that still needs saying: header spoofing doesn’t exempt you from a site’s terms of service. If a page requires auth, you presumably have an account there; read the terms before you scrape it at volume, and keep request rates at something a polite human session would generate. The web scraping legal guide is the reference I point people to.
Wrap-Up
The failing scrapes that look like IP blocks are often header blocks. Before you escalate to residential proxies or premium stealth modes, spend ten minutes with an echo endpoint and find out what the target actually received. The workflow:
- Build a header profile per target domain —
Accept-Languagefor locale,Refererfor hop checks,Authorization/Cookiefor account scope. - Pass it through the
headersfield onPOST /api/v1/scrape(or the async/batch equivalents). - Verify with an echo endpoint before blaming the target.
- Handle 401s by cause, not by retry count.
The header pass-through field is small, but it’s the difference between a request the server tolerates and a request it actually serves. Next step if you’re building locale coverage: pair each Accept-Language value with a matching proxy_country and confirm the exit geo with a local check before you trust the price data.
Related Articles
Keep Every Version of a Page: Build an SCD History Table
Re-scraping overwrites history. Build a merge step that keeps every record version with validity dates, so you can query past states of any scraped page.
TutorialRoute Scraping Traffic Through Proxies You Already Own
When targets allowlist your IPs or you already pay for residential proxies, attach a proxy profile so scrape requests exit through your pool.
TutorialDead-Letter Failed URLs, Then Replay Them Safely
Build a scraping pipeline that parks failed URLs in a dead-letter queue, inspects why each one failed, and replays them without losing rows or duplicating work.