Skip to Content

What is FastAPI Depends() and how does it enable clean RBAC wiring?

Category: Backend & API

Answer

Depends() is FastAPI’s dependency injection primitive. You write a callable that returns a value, then put it in the route signature; FastAPI calls the callable before your handler runs and the return value is passed as a parameter. This makes authentication, scope checks, and database session injection a single line at the route.

Concrete examples from the fca project context

Example 1

get_current_user dependency decodes JWT and returns the typed User; the same callable is reused across all routes.

Example 2

get_current_active_user adds a status check on top of get_current_user; routes that need a “live” account depend on it.

Example 3

Security(scope=[…]) declares the OAuth2 scopes; Depends() composes with Security to enforce them.

Data flow / flow chart

Request -> Security scopes -> Depends(get_current_user) -> Depends(get_current_active_user) -> Route handler

Takeaway

Depends() turns cross-cutting wiring into a composable call chain; one reusable callable, no duplicate code.