tezvyn:

FastAPI's Security Utility: Dependencies for Auth

AI-drafted, machine-checkedSource: fastapi.tiangolo.comadvanced

FastAPI's `Security` utility is a specialized `Depends` for authentication. It signals to OpenAPI that a dependency is required for security, enabling interactive docs. Use it to protect endpoints by injecting the authenticated user.

WHY IT EXISTS Security is complex, and integrating it with endpoint logic and API documentation often requires significant boilerplate. FastAPI needed a way to handle security that was consistent with its dependency injection system and automatically integrated with OpenAPI standards for clear, interactive documentation.

THE MENTAL MODEL The Security utility is a sibling to Depends. While Depends says "this endpoint needs this object," Security says "this endpoint needs this object, AND getting it is a security requirement." This distinction is crucial for OpenAPI, which uses it to display a lock icon and provide UI for authentication, like an "Authorize" button to enter a bearer token.

HOW IT WORKS Security() is a function that you use as the default value for a path operation parameter. It takes another function (your actual security logic) as its argument. When a request hits a protected endpoint, FastAPI's dependency injection system runs your security logic function. If the function returns a value (like a user model), the request proceeds. If it raises an HTTPException, FastAPI halts and returns a 401 or 403 error automatically. For example: current_user: User = Security(get_current_user_from_token).

WHEN TO USE IT Use Security() whenever an endpoint requires authentication or authorization. This is the standard FastAPI way to protect routes, whether you're verifying a JWT from an Authorization header, checking an X-API-Key, or implementing a full OAuth2 flow. It makes security requirements explicit and self-documenting.

WHEN NOT TO USE IT If a dependency is not directly related to authentication or authorization, use the standard Depends() instead. Using Security() for a non-security dependency, like a database session, is semantically incorrect and would create a misleading API schema for your users.

ONE CANONICAL EXAMPLE A common use case is protecting an endpoint so only logged-in users can access it. You would define a dependency function, say get_current_user, that extracts a token from the request header, decodes it, and fetches the user from the database. In your path operation, you'd write: async def get_my_profile(current_user: User = Security(get_current_user)). FastAPI handles the rest, either injecting the user object or returning an authentication error.

Read the original → fastapi.tiangolo.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.