Lab-tested: Python 3.13.5 mock API (lab) · 2 Dec 2026 · Reproduced and fixed in our lab
Fix Box — Try This First (10 Seconds)
An API key 401 has three usual causes: the key header is missing, the key value is wrong, or the key was revoked. Read the response first — good APIs name which one in the body or the WWW-Authenticate header.
Check the header name your API expects (X-Api-Key, Authorization: ApiKey, or similar) before you rotate anything. Then confirm the key is active in the provider dashboard. Still stuck? Test the endpoint with the 401 Checker or start from the pillar 401 Unauthorized: Causes and How to Fix It.
Table of Contents
- Why API Key 401s Are Harder to Read
- The Exact Messages (Verbatim from Our Lab)
- Cause 1: Key Header Missing
- Cause 2: Wrong Key Value
- Cause 3: Wrong Header Name or Format
- Cause 4: Revoked, Rotated, or Wrong-Environment Key
- Our Lab Reproduction
- The Fix, Step by Step
- What Did Not Work
- Prevention
- FAQ
- Sources and Date
- References
Why API Key 401s Are Harder to Read
Unlike Bearer tokens, API keys have no single standard. RFC 9110 defines the 401 status and the WWW-Authenticate challenge, but no RFC defines an ApiKey scheme.
Every provider invents its own header name and error wording. That is why two APIs can return the same 401 for different mistakes. Your first job is to learn what this API calls the header and what its errors mean.
There is a second trap. Many APIs return 401 for a missing key and 403 for a valid key without permission.
Others return 401 for both. Never assume; read the body. A well-built API distinguishes "no key", "bad key", and "key lacks scope" in its error text even when the status code is identical.
The Exact Messages (Verbatim from Our Lab)
We reproduced the three key failures against a local mock API on 2 Dec 2026. Our lab API uses an X-Api-Key header and answers with an ApiKey challenge. These captures are verbatim, with the lab key value removed:
HTTP/1.0 401 Unauthorized
WWW-Authenticate: ApiKey realm="api", error="missing_api_key"
{"error": "missing_api_key", "error_description": "X-Api-Key header missing"}
HTTP/1.0 401 Unauthorized
WWW-Authenticate: ApiKey realm="api", error="invalid_api_key"
{"error": "invalid_api_key", "error_description": "API key not recognized"}
# AFTER (correct key)
HTTP/1.0 200 OK
{"ok": true, "data": "lab payload"}
Your provider's wording will differ. The structure — missing vs invalid — is what you should look for. If your API returns a bare 401 with no body, test one variable at a time.
Cause 1: Key Header Missing
The request arrived without any key. In our lab, omitting X-Api-Key produced missing_api_key immediately.
In real code this happens when config fails to load, an environment variable is empty in one environment, or a proxy strips unknown headers. An empty string header is the sneaky variant: the header exists, the value does not.
Log whether the header is present and its length, never the value. If length is zero in production but not locally, your secret injection is broken, not your key.
Cause 2: Wrong Key Value
The header arrived, the value did not match. Our lab sent wrong-key-123 and got invalid_api_key with "API key not recognized." Real-world versions: a key copied with a trailing space or newline, a truncated key from a wrapped config line, or an old key left in a second config file.
Keys are opaque strings; one character off is a different key.
Compare a hash or the last four characters against the dashboard value. Never paste the full key into logs, tickets, or chat to compare it. If you suspect the key leaked, rotate first and debug second.
Cause 3: Wrong Header Name or Format
You sent a valid key in the wrong place. Providers differ: X-Api-Key, Api-Key, Authorization: ApiKey <key>, Authorization: Bearer <key>, or a query parameter.
Sending the right key under the wrong name looks exactly like a missing key to the server. It returns the missing-key error, which sends you debugging in the wrong direction.
Read the provider's authentication docs for the exact header name and casing. Then send one test request with curl, changing nothing else. Our lab accepts only X-Api-Key; a correct key in Authorization still failed there, by design.
Cause 4: Revoked, Rotated, or Wrong-Environment Key
The key was real once. Someone rotated it, revoked it after a leak, or you are using a test key against production (or the reverse).
The server cannot tell a revoked key from a typo — both are "not recognized." Only the dashboard can. Check key status, environment, and creation date there before touching code.
Also check scope and IP allowlists. Some providers reject a valid key from an unlisted IP with 401 instead of 403. The error body usually says so; if it does not, test from an allowlisted network to isolate it.
Our Lab Reproduction
Stack: Python 3.13.5 mock API on localhost, tested 2 Dec 2026. Endpoint /api/key requires the X-Api-Key header.
We captured three states: no header, wrong value, correct value. Before: both failures returned 401 with distinct error values (missing_api_key, invalid_api_key). After: the correct key returned 200 OK with the payload.
Honest lab note: the ApiKey challenge scheme here is our lab's convention, modeled on common provider practice. There is no IETF standard for it.
What transfers to real APIs is the diagnostic order: presence, then value, then header name, then key status. Full captures are stored with this package.
The Fix, Step by Step
- Send one clean test request and read everything:
curl -si https://your-api.example/endpoint
curl -si -H "X-Api-Key: YOUR_KEY" https://your-api.example/endpoint
- If the error says missing, fix config loading and header name first. Confirm the header name from the provider docs, not from memory.
- If the error says invalid, compare the key's last four characters with the dashboard. Check for whitespace, truncation, and environment mismatch.
- If the key looks right, check dashboard status: active, not revoked, correct environment, IP allowlist, and scope.
- In code, load the key from one place and fail fast when it is empty:
import os, urllib.request, urllib.error
api_key = os.environ.get("API_KEY", "").strip()
if not api_key:
raise RuntimeError("API_KEY is not set")
req = urllib.request.Request(
"https://your-api.example/endpoint",
headers={"X-Api-Key": api_key},
)
try:
with urllib.request.urlopen(req) as r:
print(r.status, r.read().decode())
except urllib.error.HTTPError as e:
print(e.code, e.headers.get("WWW-Authenticate"), e.read().decode())
- Verify 200, then keep the error body logging (without the key) permanently.
What Did Not Work
Rotating the key before reading the error did not help in our lab scenario design: a missing header stays missing with a brand-new key. Rotation also breaks every other client still using the old key.
Diagnose first, rotate only on evidence of a bad or leaked value.
Sending the correct key in the Authorization header failed against our lab API, which only reads X-Api-Key. The server reported the key as missing. Wrong-header failures disguise themselves as missing-key failures; that is the trap.
Adding the key as a query parameter (?api_key=...) is accepted by some APIs and rejected by others.
Even where accepted, it leaks into access logs and proxies. Use the header the docs specify.
Prevention
Store keys in one secret manager per environment, never in code or shared docs. Alert on 401 rate by error type, not just status.
Rotate on a schedule with an overlap window, and revoke immediately on suspected leak. For the cross-scheme view, see the pillar 401 Unauthorized: Causes and How to Fix It, the 401 Checker, 401 JWT/Bearer Token Errors, and 401 Basic Auth Failures.
FAQ
Is an invalid API key a 401 or a 403? Usually 401: the credentials were not accepted.
A valid key without permission for the action is typically 403. Providers vary, so read the error body.
Why did my key stop working overnight? Rotation, revocation, expiry, or an IP allowlist change are the usual causes. Check the key's status and last-used data in the dashboard before changing code.
Can I put the API key in the URL? Some APIs allow it, but it leaks into logs and history.
Prefer the documented header. If you must use a query parameter, treat the URL as a secret.
How do I debug without exposing the key? Log presence, length, and last four characters only.
Compare hashes between environments. Never log or paste the full value.
My key works in curl but fails in my app. Why? Your app is sending something different: wrong header name, empty env var, or whitespace. Print the header name and key length from the app and diff against the working curl request.
Sources and Date
Lab tests run 2 Dec 2026 on Python 3.13.5 (mock API, localhost). Captures are from that run with the lab key value removed. References verified live on 2 Dec 2026.
References
- RFC 9110, HTTP Semantics, Section 15.5.2 (401 Unauthorized): https://www.rfc-editor.org/rfc/rfc9110.html
- MDN Web Docs, 401 Unauthorized: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401
- MDN Web Docs, WWW-Authenticate: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/WWW-Authenticate
- MDN Web Docs, Authorization: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization
- RFC 6750, OAuth 2.0 Bearer Token Usage (contrast with Bearer scheme): https://www.rfc-editor.org/rfc/rfc6750.html






Leave a Reply