Rate limiting with fastapi-users¶
Compose paceapi key dependencies directly with fastapi-users current_user() dependencies:
# These two lines are fastapi-users' own.
current_active_user = fastapi_users.current_user(active=True)
current_user_if_any = fastapi_users.current_user(active=True, optional=True)
async def user_key(user: Annotated[User, Depends(current_active_user)]) -> str:
# The id is a UUID with one database and something else with another.
return f"user:{user.id}"
async def user_key_if_any(
user: Annotated[User | None, Depends(current_user_if_any)],
) -> str | None:
return None if user is None else f"user:{user.id}"
per_user = limiter.limit("3/minute", key=user_key)
# Someone who is signed in is counted as that user, and anyone else by address.
per_caller = limiter.limit("3/minute", key=first_of(user_key_if_any, client_ip))
@app.get("/me", dependencies=[Depends(per_user)])
async def me(user: Annotated[User, Depends(current_active_user)]) -> dict[str, str]:
return {"email": user.email}
@app.get("/articles", dependencies=[Depends(per_caller)])
async def articles() -> list[str]:
return ["On counting", "On waiting"]
Key details¶
- Single auth check per request: FastAPI deduplicates
current_useracross the key dependency and endpoint; unauthenticated callers getfastapi-users's401before any quota is consumed. - Stringify user IDs: Format
f"user:{user.id}"so UUID, integer, and string primary keys all work uniformly. - Mixed anonymous/authenticated routes: Use
current_user(active=True, optional=True)withfirst_ofto fall back toclient_ipfor unauthenticated callers. - Auth routers (
/auth/register,/auth/login): Attach IP-based limits when callingapp.include_router(..., dependencies=[Depends(...)]). Note that infastapi-users15, login accepts form data (not JSON), returns400on invalid credentials (usefailures={400}), and shares a router with logout (handle requests without a username field gracefully). - Self-contained example:
examples/fastapi_users.pyuses a lightweight stub matchingfastapi-users'scurrent_user(active=..., optional=...)signature so it runs in CI without installingfastapi-users.