As a lead, would you have FastAPI endpoints declare authentication one by one, or make it the default through router- or app-level dependencies, and where would public routes go?
answer
- a forgotten parameter is an open endpoint
- protected routers by default
- public routes on their own router
- app-wide has no per-route opt-out
- docs, add_route and mounts sit outside it
basics
~20 sMake it the default: attach the auth dependency to each protected APIRouter so new routes are covered without anyone remembering, keep public routes on one separate router, and inject the user as a parameter only where a handler needs it.
solid answer
~40 sPer-endpoint parameters read well but fail open: the endpoint someone forgets is public, and review has to spot an absence. `APIRouter(dependencies=[Depends(require_user)])` makes protection a property of where a route lives, and the per-request cache lets a handler still declare `user: CurrentUser` without a second check. `FastAPI(dependencies=[...])` is stricter but has no per-route opt-out, so the login and health endpoints must become plain Starlette routes or a mounted app, and it never covers `/docs`, `/openapi.json` or mounts anyway. I would use protected routers by default, one reviewed public router, and a CI test that calls every documented operation without credentials and expects 401 outside an allowlist.
code
python · 38 linesimport secrets
from typing import Annotated
from fastapi import APIRouter, Depends, FastAPI, Header, HTTPException
def require_user(authorization: Annotated[str | None, Header()] = None) -> str:
# stand-in for real token verification
if not secrets.compare_digest(authorization or "", "Bearer demo-token"):
raise HTTPException(status_code=401, detail="Not authenticated",
headers={"WWW-Authenticate": "Bearer"})
return "ada"
CurrentUser = Annotated[str, Depends(require_user)]
public = APIRouter()
protected = APIRouter(dependencies=[Depends(require_user)])
@public.get("/health")
def health():
return {"status": "ok"}
@protected.get("/orders")
def list_orders():
return [] # protected without naming require_user
@protected.get("/me")
def me(user: CurrentUser):
return {"user": user} # same dependency, cached: one check per request
app = FastAPI()
app.include_router(public)
app.include_router(protected)go deeper
Know that a FastAPI dependency runs only where it is declared, on a parameter, a decorator, a router or the app.
Explain how router-level dependencies cover every route on the router and how the cache avoids a second check.
Point out what app-wide dependencies do not cover and why per-endpoint auth fails open.
Set the layout rule, protected and public routers, and back it with a CI test generated from the app's own schema.
## The failure the decision is about Authentication in FastAPI is a dependency, and a dependency only runs where it is declared. If each endpoint declares its own `user: CurrentUser` parameter, every new endpoint is public until its author remembers the parameter, and a reviewer has to notice something that is **missing**. That is a fail-open design. The lead's question is where the declaration lives so that forgetting it fails closed. ## The placements | Placement | A new route is covered automatically | Opt-out for one route | Handler gets the user | |---|---|---|---| | Parameter on each endpoint | no | n/a | yes | | `dependencies=[...]` on the decorator | no | n/a | no | | `APIRouter(dependencies=[...])` | yes, for routes on that router | move the route to another router | add the parameter too | | `FastAPI(dependencies=[...])` | yes, for every path operation | none | add the parameter too | Declaring the same dependency on the router and as a parameter is cheap: FastAPI caches a dependency per request, so a handler that needs the user object can ask for it without a second check. ## What app-wide dependencies do not cover `FastAPI(dependencies=[Depends(require_user)])` looks like the strictest option, and for path operations it is: there is no per-route opt-out, and an empty `dependencies=[]` on a decorator does not remove it. That strictness has two sides. - **Endpoints that must be public** (the login or token endpoint, a health check) cannot be path operations of that app. They end up as plain Starlette routes added with `app.add_route`, or in a mounted sub-app, both of which bypass FastAPI's dependencies entirely. - **Some routes are never covered**: `/docs`, `/openapi.json` and the ReDoc page are Starlette routes, and mounted applications do not see the parent's dependencies. Unknown paths get their 404 without running anything. So "app-wide" does not mean "everything", and the exceptions are scattered in two different mechanisms. ## A layout that fails closed What I would standardize instead: - a **public router** holding the few operations that must be open, each one reviewed as a deliberate choice; - **protected routers** created with `dependencies=[Depends(require_user)]`, which is where every new module's router starts; - **coarse role routers** where useful, such as an admin router with `dependencies=[Depends(require_admin)]`; - handlers that need the caller inject `user: CurrentUser` as a parameter, deduplicated by the cache. A new route added to a protected router is protected without anyone writing anything, and making something public means moving it to the public router, a visible change in review. ## Keeping it honest A layout is a convention; a test makes it a guarantee. Generate the list of operations from `app.openapi()`, send each one a request without credentials, and assert 401 for all but an explicit allowlist of public operations. Because the list comes from the app itself, a route is tested the day it is added, and adding to the allowlist is a reviewed diff. ## What this does not decide Router-level dependencies answer "is there an authenticated caller". Checks that depend on the object, such as whether this user may see this order, need the loaded resource and belong where it is loaded, in the handler or a service layer. Scope checks follow the same placement logic but carry their own rules. ## When per-endpoint is fine A tiny service with two endpoints, or one where public and private operations interleave so much that routers would be artificial, can live with per-endpoint parameters, provided the CI test above exists. Without the test, I would not accept it for anything that holds user data.
- How would you check in CI that only the intended FastAPI routes are public?Build the list from the app: for each operation in `app.openapi()["paths"]`, send a request without credentials and assert 401, except for an explicit allowlist of public operations. A new route is then tested the day it is added, and widening the allowlist is a reviewed change.
- Would you put role checks at the router level too?Coarse ones, yes: an admin router can require an admin role for everything under it. Checks that depend on the object, such as whether this user owns this order, need the loaded resource, so they stay in the handler or the service layer that loads it; a router dependency cannot see which row the handler will fetch.
It is the difference between locking each office door and hoping nobody forgets one, and putting the lock on the corridor, with the public rooms deliberately placed outside it.
- Declaring the user parameter on every endpoint is as safe as router-level auth
- An app-wide dependency also protects /docs and mounted sub-apps
- dependencies=[] on a decorator opts a route out of app-wide dependencies
- A router dependency plus the same parameter runs the check twice per request
- Public endpoints are best handled by path exceptions inside the auth dependency