After upgrading FastAPI past 0.122, partner clients that expected 403 from APIKeyHeader for a missing key now get 401: what changed, and how do you respond?
answer
- a release note about status codes
- unauthenticated versus unauthorised
- a challenge header the spec requires
- override a method that returns, not raises
- scheme_name keeps the docs name stable
basics
~20 sFastAPI 0.122 made its security classes answer a missing credential with 401 and a WWW-Authenticate challenge instead of 403. Update clients and tests; if one cannot change yet, subclass and override make_not_authenticated_error to return a 403.
solid answer
~40 sSince FastAPI 0.122, and so in 0.143, `APIKeyHeader`, `APIKeyQuery`, `APIKeyCookie` and `HTTPBearer` answer a missing credential with 401 `Not authenticated` and a challenge, `WWW-Authenticate: APIKey` for the key classes and `Bearer` for `HTTPBearer`, because HTTP reserves 401 for missing or invalid credentials and requires the challenge, while 403 means an identified caller was refused. The fix is to update partner clients and tests to treat 401 as "send a valid key". If a client cannot change in time, FastAPI documents a per-scheme escape hatch: subclass the class and override `make_not_authenticated_error` to return an `HTTPException(403)`; FastAPI raises it. Pass `scheme_name` so `/docs` keeps its scheme name, record the override with a removal trigger, and avoid a global handler that turns every 401 into 403, since it would also rewrite your own wrong-key 401s.
code
python · 22 linesfrom typing import Annotated
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import APIKeyHeader
class APIKeyHeader403(APIKeyHeader):
def make_not_authenticated_error(self) -> HTTPException:
# return the exception; FastAPI's security code raises it
return HTTPException(
status_code=status.HTTP_403_FORBIDDEN, detail="Not authenticated"
)
legacy_key = APIKeyHeader403(name="X-API-Key", scheme_name="PartnerKey")
app = FastAPI()
@app.get("/partner/stock")
def stock(key: Annotated[str, Depends(legacy_key)]) -> dict[str, int]:
return {"units": 12}go deeper
Recall that current FastAPI answers a missing key or token with 401 and a WWW-Authenticate header, not 403.
Explain the 401 versus 403 meaning, the challenge values per class, and how make_not_authenticated_error restores the old status.
Diagnose the broken clients and tests after the upgrade, scope any 403 override to one scheme, and keep your own error codes consistent.
Weigh forcing partners to adapt against carrying a dated compatibility override, and set the 401 and 403 contract clients can rely on.
## What changed FastAPI **0.122.0** (November 2025) changed how its security classes answer a missing credential. Before it, classes such as `APIKeyHeader` and `HTTPBearer` answered with **403 Forbidden** and `detail` `"Not authenticated"`. Since then, and in FastAPI 0.143, they answer with **401 Unauthorized** plus a `WWW-Authenticate` header: | Class | 401 challenge in 0.143 | |---|---| | `APIKeyHeader`, `APIKeyQuery`, `APIKeyCookie` | `WWW-Authenticate: APIKey` | | `HTTPBearer` | `WWW-Authenticate: Bearer` | | `HTTPBasic` | `WWW-Authenticate: Basic`, or `Basic realm="..."` with a realm | The release note calls the old status "less correct". The reasoning, from FastAPI's docs and source: - **401** means the request lacks valid credentials, and HTTP requires a 401 to carry a `WWW-Authenticate` challenge. - **403** means the server understood who is asking and refuses anyway. A missing key is the first case. API keys have no standard challenge, so the API key classes send the custom value `APIKey`, as a comment in their source explains. ## Who it breaks The upgrade broke callers that treated 403 as "no credentials": - partner client code that checks `status == 403` to decide it must attach a key, or retries on 401 as if it were transient; - tests in your own suite that assert 403 for a request without a key; - gateway or monitoring rules keyed to the old status. Your own code did not change: any `HTTPException` you raise yourself keeps whatever status you gave it. ## How to respond In order of preference: 1. **Update the clients and tests.** The new behaviour is the HTTP-correct one, and every later release builds on it. For tests, assert `401` and the `WWW-Authenticate` value. 2. **Restore 403 for one scheme, if a client cannot change in time.** FastAPI documents an override: subclass the class and override **`make_not_authenticated_error`**. The method **returns** an `HTTPException`; FastAPI's own code raises it. 3. **Do not pin FastAPI below 0.122** to avoid the change; that forfeits every later fix and feature. 4. **Avoid a global `exception_handler(HTTPException)` that rewrites 401 to 403.** It also rewrites the 401s your own dependencies raise for wrong keys, and those are correct. When you subclass, two details matter: - `scheme_name` defaults to the class's name, so `APIKeyHeader403(...)` appears in OpenAPI and `/docs` as `APIKeyHeader403`. Pass `scheme_name` to keep a stable name. - The 403 you return has no challenge header unless you add one, matching the docs' own example of the old behaviour. Write the override down as a **dated compatibility step** with a trigger for its removal, such as the last partner client upgrading. ## Updating the test suite The tests that broke are usually small, and the fix is to assert the new contract fully rather than just swap the number: ```python def test_missing_key_is_unauthenticated(client): response = client.get("/partner/stock") assert response.status_code == 401 assert response.headers["www-authenticate"] == "APIKey" assert response.json() == {"detail": "Not authenticated"} ``` Asserting the challenge header as well as the status means the next behaviour change in a 0.x release shows up as a failing test in your pipeline, not as a partner's support ticket. The release notes are the record to read before each upgrade, because FastAPI changes behaviour in minor releases. ## 401 and 403 in your own dependencies The change is also a prompt to make your own errors consistent: - **Missing key**: the class's 401 with `APIKey`. - **Unknown or revoked key**: a 401 from your verifying dependency, with the same challenge. - **Valid key, not allowed to do this**: a 403 from your code, because the caller is identified. A team that keeps these three apart gives clients a simple rule: on 401, fix the credential; on 403, stop and ask for access.
- Why does make_not_authenticated_error return the exception instead of raising it?FastAPI's own code calls it and raises the result at each point where authentication fails, as its how-to guide notes. Returning lets one method define the error while the class keeps control of when it fires, including returning `None` instead when `auto_error=False` and the credential is absent.
- What should your own verifying dependency return for a key that is valid but not allowed to cancel orders?403. The key identified the partner, so authentication succeeded and the refusal is about permission. Keep 401, with `WWW-Authenticate: APIKey`, for keys that are unknown or revoked, so clients can tell "fix your credential" from "you may not do this".
- A missing key should get 403 because the client is forbidden to proceed
- FastAPI 0.143 still returns 403 from APIKeyHeader by default
- auto_error=False is the switch that restores the old 403
- Rewriting every 401 to 403 in a global exception handler is a safe shim
- Pinning FastAPI below 0.122 is a reasonable long-term fix
Assumes FastAPI 0.143; since 0.122 the security classes answer a missing credential with 401 and WWW-Authenticate, where API key and Bearer classes previously sent 403.