401 Unauthorized when scraping: your key or login was refused
What you see
401 UnauthorizedHTTP/1.1 401 Unauthorized401 Client Error: Unauthorized for urlRequest failed with status code 401
More error strings (8)
Unauthorized: Invalid tokenUnauthorized request, please make sure your API key is valid.Invalid API keyInvalid tokenUser authentication is requiredAuth method is not supportedAUTH001 API Key MissingWWW-Authenticate: Bearer error="invalid_token"
What it means
401 Unauthorized means the server wants to know who you are. You sent no login, or one it does not accept: a missing, wrong or expired key, token or cookie. Sending the same request again won’t help. Fix the login first.
“Unauthorized” is a slightly odd name. The standard (RFC 9110) defines 401 as a request that “lacks valid authentication credentials”. So the problem is not what you may do. The server simply doesn’t know who you actually are.
Two things can happen here:
- You didn’t send a login. Send one.
- You sent one. Then the 401 means the server refused that login. Trying again only helps with a fresh or different credential.
The server must also say which kind of login it wants, using a WWW-Authenticate header. Scraping APIs mostly use an API key: one long secret string that is tied to your whole account. A Bearer token works like a concert wristband. Whoever holds it gets in, no other proof needed (RFC 6750).
Why it happens
First find out who said no, since a 401 comes from one of two places:
- Your scraping API (ZenRows, ScraperAPI, Firecrawl, Bright Data…) does not accept your API key. The body carries the vendor’s error.
- The target site wants a login, and your session or token is gone. The vendor just passes its reply along to you.
Here are the usual causes, most common first:
- No key reached the server. An empty environment variable, or a header your code never set; ZenRows calls this
AUTH001. Bright Data saysUser authentication is required. Firecrawl even answers 401 to anAuthorizationheader that carries an empty token. - The key is typed wrong. A missing character, an extra space or a broken string join. ZenRows calls this
AUTH002. - The key got revoked or regenerated. The old one stops working. ZenRows answers:
AUTH003. Firecrawl:Unauthorized: Invalid token. - The key is in the wrong place. Each vendor wants it somewhere else (table in Dev details). ZenRows Batch, for example, takes it only as an
X-API-Keyheader, not in the URL. - The header has the wrong shape. Bright Data refuses a bare key,
Token <key>, lowercasebeareror even two spaces afterBearer. Basic auth getsCredentials are invalidthere. - Your token expired. OAuth tokens (short-lived keys from a login) run out of time. The server then says
invalid_token(RFC 6750). - Your login cookie ran out. Behind a site login, your session lives in a cookie. A cookie with
ExpiresorMax-Ageis deleted after that time and no longer sent (MDN). The site suddenly sees a stranger. - Your IP is not on the allowlist for the key. Scrapfly answers 401 when a project only allows certain client IPs and yours is not one of them.
Not every vendor uses 401 for money problems. Out of credits, ScraperAPI answers 403, ZenRows and Firecrawl answer 402. One exception: ZenRows Batch sends 401 subscription_inactive when a valid key’s subscription needs a billing fix.
Python requests has a couple of quiet traps of its own:
- It removes the
Authorizationheader if a redirect sends you to another host. - An
Authorizationyou set throughheaders=is overridden by a.netrcfile, and.netrcbyauth=.
How 401 differs from each of its neighbours:
| code | who says no | what it means | page |
|---|---|---|---|
| 401 | the server you called | “Who are you?” No valid login | this one |
| 403 | the server you called | “I know, and still no.” A better login may not help | 403 Forbidden |
| 407 | the proxy in between | “Log in to me first.” The site never saw you | 407 Proxy Authentication Required |
Fix it
- Read the body. A vendor’s JSON or text names the reason (
AUTH001,Invalid API key,Unauthorized: Invalid token). An HTML login page means the target site sent it. - Check the key your code really sends. Print its length and first 4 characters, but never the entire key. Empty or
Nonemeans the environment variable did not load. - Copy the key once more from the vendor’s dashboard. If someone regenerated it, the old one is dead.
- Send it the way your vendor wants (table in Dev details). For a Bearer header, write it exactly:
Authorization: Bearer <key>, capital B, one space. - Token expired? Get a new one at the login or token endpoint, then retry once. RFC 6750 allows exactly that.
- Behind a site login? Log in again and take the fresh cookies, then check the session cookie’s
ExpiresorMax-Ageso you know when to refresh it next time. - Using an IP allowlist (Scrapfly)? Add the IP the error message names to the project settings or clear the field.
- Don’t retry in a loop. Firecrawl marks its 401 as not retryable. The same key will get the same answer.
Using a vendor as a proxy (host:port plus a username and password)? A bad login there comes back as 407, not 401. See 407 Proxy Authentication Required.
Why the body comes first: vendors put the exact reason there, and RFC 9110 tells clients to show it. Guessing costs more time than simply reading it.
Treat your key as a password:
- Put it in an environment variable or a secrets manager, and never in git (ZenRows).
- Keep it out of URLs when the vendor allows a header. RFC 6750 says bearer tokens should not go in page URLs, because browser history and server logs may keep them.
- Asking for help? Replace the key with
KEYbefore you share a request URL anywhere. - Leaked it? Make a fresh key in the dashboard. That kills the old one, which is cause 3 by design.
One trap for AI agent templates: Firecrawl’s /v1/scrape and /v1/search work without a key, with limits. But only if you leave the Authorization header out, because a header with a blank token gets 401.
Paste this into your AI
My scraper gets this error: "<paste the exact error line>".
Explain in plain words what a 401 means.
First tell me how to see who sent it: my scraping API (my key) or the target site (its login).
Then list the likely causes in order, most likely first.
For each cause, give one quick test and one fix.
My setup: <language + library>, <scraping API or proxy vendor, or none>,
how I send the key (<query parameter / Authorization: Bearer / X-API-Key / cookie>),
the URL pattern I call: <URL, with the key replaced by KEY>.
Response headers and the first 20 lines of the body: <paste them>.
Never ask me to paste my real key, token or cookie.Dev details
The challenge header. A server that sends 401 MUST send a WWW-Authenticate header with at least one challenge, which names the login scheme it wants (RFC 9110). You answer with an Authorization header.
HTTP/1.1 401 Unauthorized
Date: Tue, 02 Jul 2024 12:18:47 GMT
WWW-Authenticate: Bearer
With an expired OAuth token, RFC 6750 shows this example:
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="example",
error="invalid_token",
error_description="The access token expired"
If you already sent a credential and get the same challenge back, RFC 9110 says the client should show the body to the user, since that body usually explains what went wrong.
Where each vendor wants the credential:
| vendor | how to send it | 401 body or code |
|---|---|---|
| ZenRows Fetch | apikey query parameter |
AUTH001 missing · AUTH002 malformed · AUTH003 not found |
| ZenRows Batch | X-API-Key header only |
unauthenticated |
| Firecrawl | Authorization: Bearer fc-... |
{"success": false, "error": "Unauthorized: Invalid token"} |
| Bright Data Web Unlocker (Direct API) | Authorization: Bearer <API key> |
plain text, see below |
| ScraperAPI | api_key query parameter |
Unauthorized request, please make sure your API key is valid. |
| Scrapfly | key query parameter |
JSON with "http_code": 401, "message": "Invalid API key" |
# ZenRows Fetch: key in the query string
curl "https://api.zenrows.com/v1/?apikey=YOUR_ZENROWS_API_KEY&url=https%3A%2F%2Fhttpbin.io%2Fanything"
Bright Data Web Unlocker. Key checks happen before the unlocker runs, so on api.brightdata.com/request you get a real outer 401 with a plain-text message body and no x-brd-* headers:
| body | cause |
|---|---|
Invalid token |
well-formed, but not a valid key (revoked, mistyped) |
Auth method is not supported |
not the Bearer scheme: bare key, Token <key>, lowercase bearer, extra spaces |
Credentials are invalid |
Basic auth instead of Bearer |
User authentication is required |
no Authorization header |
Once a request passes those checks, a missing x-brd-error header tells you the response came from the target site itself.
Scrapfly sends back a JSON error:
{
"status": "error",
"http_code": 401,
"reason": "Unauthorized",
"error_id": "301e2d9e-b4f5-4289-85ea-e452143338df",
"message": "Invalid API key"
}
What your HTTP client prints.
| library | message |
|---|---|
Python requests (raise_for_status()) |
401 Client Error: Unauthorized for url: <url> |
| Axios | Request failed with status code 401 |
Python requests and a Bearer key from an environment variable:
import os
import requests
key = os.environ.get("FIRECRAWL_API_KEY")
print(len(key or ""), (key or "")[:4]) # check it loaded, never print it all
r = requests.post(
"https://api.firecrawl.dev/v2/scrape",
headers={"Authorization": f"Bearer {key}"},
json={"url": "https://example.com"},
)
if r.status_code == 401:
print(r.text) # the vendor's reason
r.raise_for_status()
Basic auth is not a lock. The Basic scheme sends user:password written in Base64 (RFC 7617). Base64 is a way of spelling bytes, which means anyone who sees the header can read it back. RFC 7617’s own example: user test, password 123£ becomes dGVzdDoxMjPCow==. The RFC calls Basic unsafe unless it runs inside TLS, so only use it over https://.
Branch on the code, not the text. Bright Data’s messages carry request-specific details, so it asks you to check its error code instead. The same goes for ZenRows’ AUTH00x codes and Firecrawl’s optional code field.
Agents can read their way out. ZenRows’ remote MCP server answers a headless agent that has no key with a 401. Its body names a signup endpoint in an agent_signup field, and one network can create 3 such agent accounts in 24 hours.
Questions
What is the difference between 401 and 403?
401 means the server has no valid login from you: send one, or a better one. 403 means it understood the request and still says no, even if your login is fine (MDN, RFC 9110).
What is the difference between 401 and 407?
401 comes from the server you called and wants an Authorization header. 407 comes from a proxy in between and wants a Proxy-Authorization header (RFC 9110).
Does a 401 from a scraping API mean I ran out of credits?
Usually not. ScraperAPI answers 403 when your monthly credits run out, ZenRows and Firecrawl answer 402. A 401 points at the key itself: missing, mistyped or revoked.
Related
Tools that get past it
| Tool | Price |
|---|---|
| $1.50/1k req | |
| $3.80/1k req | |
| Free | |
| $0.49/1k req | |
| $0.15/1k req | |
| $0.42/1k req |
Sources
RFC 9110 §15.5.2: 401 Unauthorized rfc-editor.org
RFC 9110 §11.3: Challenge and Response rfc-editor.org
RFC 9110 §15.5.4: 403 Forbidden rfc-editor.org
MDN: 401 Unauthorized developer.mozilla.org
RFC 6750: OAuth 2.0 Bearer Token Usage (invalid_token) rfc-editor.org
MDN: Using HTTP cookies (cookie lifetime) developer.mozilla.org
RFC 7617: The 'Basic' HTTP Authentication Scheme rfc-editor.org
ZenRows Docs: API Authentication docs.zenrows.com
ZenRows Docs: API Error Codes (AUTH001–AUTH003) docs.zenrows.com
ScraperAPI Docs: API Status Codes docs.scraperapi.com
Firecrawl Docs: Errors docs.firecrawl.dev
Firecrawl Docs: API Introduction (authentication) docs.firecrawl.dev
Bright Data Docs: Web Unlocker API error codes docs.brightdata.com
Scrapfly Docs: Web Scraping API Errors scrapfly.io
Scrapfly Docs: Getting Started (key parameter) scrapfly.io
ScraperAPI Docs: Using the API Endpoint (api_key) docs.scraperapi.com
Requests docs: Custom Headers (Authorization precedence) requests.readthedocs.io
psf/requests source: models.py (raise_for_status message) github.com
Axios source: settle.js error message github.com