06 · Depends and the Dependency Graph
Previously, the document route manually performed authentication and authorization:
user = get_authenticated_user(request)document = documents_by_id.get(document_id)
if user is None: ...
if not user_can_view_document(user, document): ...Today, FastAPI will perform those preparations before entering the route body.
The lifecycle becomes:
Browser → session middleware → router → dependency graph → route → response → browser
The dependency graph will answer two questions:
- Who is the current user?
- Which document may that user access?
Only after those questions succeed will FastAPI call the route.
Where today’s code lives
Section titled “Where today’s code lives”We’ll add one module to the structure from the previous tutorial:
app/├── main.py├── data.py├── security.py├── dependencies.py└── routers/ └── documents.pyThe responsibilities are now:
| Module | Responsibility |
|---|---|
main.py |
Assemble the application |
data.py |
Temporary in-memory data |
security.py |
Pure authorization policy |
dependencies.py |
Prepare request-specific objects |
routers/documents.py |
Handle document-related HTTP requests |
The database is not participating yet. Our dictionaries still stand in for SQLite tables. Later, a database-backed dependency can obtain a SQLAlchemy session and query SQLite instead.
The code below continues the application from the previous lesson. main.py still installs SessionMiddleware and includes the documents router. Today we are replacing the manual preparation inside that router, not assembling a second application.
The authorization policy
Section titled “The authorization policy”First, app/security.py contains one ordinary Python rule:
def user_can_view_document( user: dict, document: dict,) -> bool: if user["role"] == "admin": return True
return user["firm_id"] == document["firm_id"]This function knows nothing about FastAPI.
It receives two dictionaries and returns a Boolean. That makes it a business policy rather than an HTTP component:
admin → allowed
ordinary user in same firm → allowed
ordinary user in different firm → deniedIt does not read cookies, raise redirects, or construct responses. Those belong closer to the HTTP layer.
The dependency module
Section titled “The dependency module”Here is app/dependencies.py:
from typing import Annotated
from fastapi import Depends, HTTPException, Request, status
from .data import documents_by_id, users_by_idfrom .security import user_can_view_document
def get_current_user(request: Request) -> dict: user_id = request.session.get("user_id")
if user_id is None: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Authentication required", )
user = users_by_id.get(user_id)
if user is None: request.session.clear()
raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Authentication required", )
return user
CurrentUser = Annotated[ dict, Depends(get_current_user),]
def get_authorized_document( document_id: int, current_user: CurrentUser,) -> dict: document = documents_by_id.get(document_id)
if document is None: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Document not found", )
if not user_can_view_document( current_user, document, ): raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Document not found", )
return document
AuthorizedDocument = Annotated[ dict, Depends(get_authorized_document),]This module defines two dependencies:
get_current_userget_authorized_documentThe second depends on the first. This creates a dependency graph:
document_page├── get_current_user└── get_authorized_document └── get_current_userFastAPI’s dependency system lets a route declare what it needs, while FastAPI calls the necessary functions and supplies their results. Dependencies can themselves declare dependencies, producing this graph of prerequisites. FastAPI dependency documentation
The first dependency: authentication
Section titled “The first dependency: authentication”The function begins:
def get_current_user(request: Request) -> dict:A dependency is still an ordinary Python callable.
It becomes a FastAPI dependency only when something declares:
Depends(get_current_user)Because get_current_user asks for:
request: RequestFastAPI supplies the current request object, just as it would for a route function.
By the time this runs, SessionMiddleware has already examined the browser’s cookie and reconstructed:
request.sessionSuppose the browser is logged in as Max:
request.session == {"user_id": 1}The dependency reads the identifier:
user_id = request.session.get("user_id")If there is no identifier, authentication fails:
if user_id is None: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Authentication required", )Raising the exception immediately stops dependency resolution.
FastAPI does not call the route afterward. Instead, it converts the exception into an HTTP response:
HTTP/1.1 401 UnauthorizedContent-Type: application/json
{"detail": "Authentication required"}A server-rendered application might later install an exception handler that turns this into a login page or redirect. For now, the 401 makes the control flow especially clear.
Retrieving the authoritative user
Section titled “Retrieving the authoritative user”If a user ID exists, the dependency performs a lookup:
user = users_by_id.get(user_id)The session says:
The browser previously logged in as user 1.The application data says:
User 1 still exists and currently has these attributes.Those are different claims.
If the account was deleted after the cookie was created, the session could still contain:
{"user_id": 1}while the lookup returns:
NoneThat case is handled here:
if user is None: request.session.clear()
raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Authentication required", )The stale session is cleared, and authentication fails.
When the lookup succeeds, the dependency returns the user:
return userFor Max, the returned object might be:
{ "id": 1, "username": "max", "firm_id": 10, "role": "member",}That return value becomes the value FastAPI injects wherever CurrentUser is requested.
Understanding Annotated and Depends
Section titled “Understanding Annotated and Depends”The reusable declaration is:
CurrentUser = Annotated[ dict, Depends(get_current_user),]Annotated combines a Python type with additional metadata.
The first part:
dictsays that the resulting value is a dictionary.
The second part:
Depends(get_current_user)tells FastAPI how to obtain that dictionary.
Notice that we pass the function itself:
Depends(get_current_user)We do not call it:
Depends(get_current_user())The distinction is:
get_current_user → the function object
get_current_user() → call the function immediatelyFastAPI needs the function object so it can call that function later, once an actual request exists.
During application startup, FastAPI examines this metadata and constructs its dependency graph. During request handling, it executes the graph.
The official documentation recommends the Annotated form and supports storing it as a reusable type alias such as CurrentUser. FastAPI’s dependency guide
The second dependency: authorization
Section titled “The second dependency: authorization”Authentication gives us the actor. Now the next dependency retrieves and authorizes the resource:
def get_authorized_document( document_id: int, current_user: CurrentUser,) -> dict:This dependency has two requirements:
document_idcurrent_userFastAPI gets document_id from the URL.
For:
GET /documents/101FastAPI converts the path text "101" into:
101The second parameter is another dependency:
current_user: CurrentUserBefore FastAPI can call get_authorized_document, it must resolve CurrentUser. That means it calls get_current_user first.
Conceptually, FastAPI performs:
current_user = get_current_user( request=current_request,)
document = get_authorized_document( document_id=101, current_user=current_user,)Your code does not write those calls. They illustrate what FastAPI’s dependency system arranges.
Retrieving the document
Section titled “Retrieving the document”The dependency looks up the requested resource:
document = documents_by_id.get(document_id)If document 101 exists, the result might be:
{ "id": 101, "firm_id": 10, "title": "Northstar Studio Website Review",}If it does not exist, the dependency raises:
if document is None: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Document not found", )Again, the route body never runs after this exception.
Applying the authorization policy
Section titled “Applying the authorization policy”If the document exists, the dependency asks the pure policy function:
if not user_can_view_document( current_user, document,):For Max and document 101, the comparison is:
current_user["firm_id"] == document["firm_id"]
# 10 == 10# TrueAuthorization succeeds.
For Max and document 202, it becomes:
10 == 20
# FalseThe dependency raises the same 404 used for a nonexistent document:
raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Document not found",)As discussed previously, this avoids confirming that another firm’s document exists.
When authorization succeeds, the dependency returns the document:
return documentThe resulting object is now more meaningful than merely “a document.”
It is:
A document that exists and that the current user is permitted to view.That is why the alias is called:
AuthorizedDocumentThe simplified route
Section titled “The simplified route”The document router can now be much smaller:
from html import escape
from fastapi import APIRouterfrom fastapi.responses import HTMLResponse
from ..dependencies import ( AuthorizedDocument, CurrentUser,)
router = APIRouter( prefix="/documents", tags=["documents"],)
@router.get( "/{document_id}", response_class=HTMLResponse,)async def document_page( current_user: CurrentUser, document: AuthorizedDocument,): return f""" <html> <body> <h1>{escape(document["title"])}</h1> <p>Document ID: {document["id"]}</p> <p>Firm ID: {document["firm_id"]}</p> <p>Viewed by: {escape(current_user["username"])}</p> </body> </html> """The route no longer contains authentication or authorization branches.
Its signature declares:
I require an authenticated user.I require an authorized document.FastAPI resolves those requirements before calling it.
If the route body begins executing, it can rely on two facts:
current_user is authenticateddocument exists and is authorizedThat removes several partially valid states from the route.
With this signature, the route receives the document through the authorization dependency. Keeping that declaration is what preserves the check.
There is one small rendering detail in the HTML:
escape(document["title"])escape() comes from Python’s html module. It turns characters such as < and > into their HTML text representations. A document title should appear as text, even if someone entered something resembling an HTML tag.
Authorization decides whether the user may see the document. Escaping decides how its text enters the page. Those are separate boundaries. Later, Jinja will handle ordinary HTML escaping in our templates.
Why get_current_user appears twice
Section titled “Why get_current_user appears twice”Look again at the graph:
document_page├── CurrentUser└── AuthorizedDocument └── CurrentUserThe route needs the current user to display the username. The document dependency also needs that user to make its authorization decision.
It may appear that get_current_user must run twice.
By default, FastAPI caches a dependency’s result for the duration of one request. When the same dependency is required more than once in the same dependency graph, FastAPI normally calls it once and reuses the result. FastAPI sub-dependency documentation
This cache is not global.
It does not mean Max remains stored forever after one request. It means:
Request A└── get_current_user runs once
Request B└── get_current_user runs againEach new HTTP request gets fresh dependency resolution.
That matters when the dependency eventually queries SQLite. One request should not perform the identical user query twice merely because two downstream components need the same user.
The request-time sequence
Section titled “The request-time sequence”Suppose Max’s browser sends:
GET /documents/101 HTTP/1.1Host: 127.0.0.1:8000Cookie: app_session=...For this successful request, the important preparation steps are:
- The browser constructs the HTTP request and includes its session cookie.
- The server receives the request.
SessionMiddlewareverifies and decodes the signed cookie.- The middleware makes
{"user_id": 1}available throughrequest.session. - FastAPI’s combined routing table matches
GET /documents/{document_id}. - FastAPI examines the route’s dependency graph.
get_current_user()receives the currentRequest.- Python reads user ID
1fromrequest.session. - Python retrieves user
1fromusers_by_id. get_current_user()returns Max’s user dictionary.- FastAPI stores that dependency result for this request.
- FastAPI validates
"101"as the integer101for the document dependency. get_authorized_document()receivesdocument_id=101and Max’s user object.- Python retrieves document
101. user_can_view_document()compares the user’s firm with the document’s firm.- Authorization succeeds.
get_authorized_document()returns the document.- FastAPI calls
document_page()with both prepared objects. - Python escapes the title and username and builds the HTML string.
- FastAPI packages it into an
HTMLResponse. - The response travels outward through middleware.
- The server sends the HTTP response.
- The browser parses and renders the HTML.
The database does nothing in this version. The “queries” at steps 9 and 14 are Python dictionary lookups. Later, those same architectural positions can contain SQLAlchemy queries against SQLite.
The dependency relationships are the important guarantee: FastAPI must obtain the current user before calling get_authorized_document(), and both preparations must succeed before calling the route. This list follows our particular signature; it is not a universal ordering rule for every possible dependency graph.
Dependency versus middleware
Section titled “Dependency versus middleware”Middleware and dependencies can both run before a route, but they operate at different scopes.
Middleware wraps the entire HTTP application:
Every request→ session handling→ request IDs→ timing→ security headersDependencies belong to selected routes or routers:
Document routes→ authenticated user→ authorized documentMiddleware is appropriate for reconstructing the browser session because many parts of the application may need session support.
A dependency is appropriate for requiring a logged-in user because public routes such as /login should remain accessible without one.
Dependencies can also return useful values:
current_userdocumentMiddleware usually modifies the request or response and passes control onward.
Dependency versus ordinary helper call
Section titled “Dependency versus ordinary helper call”Previously, the route said:
user = get_authenticated_user(request)That is an ordinary Python call. The route decides when to call it and manually passes its arguments.
Now it says:
current_user: CurrentUserFastAPI decides how to construct the value by reading the dependency declaration.
The dependency function itself remains ordinary Python. The special part is the relationship declared by:
Depends(get_current_user)This gives FastAPI enough information to:
- Supply the
Request - Resolve nested dependencies
- Reuse dependency results within one request
- Stop the route when a dependency raises an exception
- Include relevant parameter requirements in OpenAPI
Dependency injection does not eliminate function calls. It lets the framework organize certain calls around a request.
A common router-level alternative
Section titled “A common router-level alternative”An entire router can require a dependency:
router = APIRouter( prefix="/documents", dependencies=[Depends(get_current_user)],)That would ensure get_current_user runs for every route in the router.
However, its return value is discarded. The route is protected, but it does not automatically receive the user object.
When the route needs the value, this is clearer:
current_user: CurrentUserRouter-level dependencies are most useful for requirements that must run but whose return value the route does not need directly.
The central idea
Section titled “The central idea”Depends turns route preparation into an explicit graph.
The route declares the valid state it requires:
an authenticated useran existing, authorized documentFastAPI works backward through the graph to construct that state.
If any prerequisite fails, FastAPI produces an error response and never enters the route body. If they all succeed, the route receives ready-to-use Python objects and can focus on its HTTP response.
In the next layer, Pydantic will perform a related but distinct job: turning untrusted request data into a validated application object before service-layer logic is allowed to use it.
A closer look at dependency styles
Section titled “A closer look at dependency styles”The reusable alias often prompts a useful question:
This last tutorial is interesting.
Specifically, it says this:
CurrentUser = Annotated[ dict, Depends(get_current_user),]so in the routes we’ll call it like this:
@router.get( "/{document_id}", response_class=HTMLResponse,)async def document_page( current_user: CurrentUser, document: AuthorizedDocument,):I’m actually more used to see the Depends() called in the router function, like this:
async def document_page( current_user: Depends(get_current_user), document: same_thing with Depends(get_authorized_document)):Would both ways work? Is there a preferred way? Again, real-life apps I’ve built with Codex are using the last way I showed you to call the dependency.
Yes, both styles work, with one important syntax correction.
The style you’re accustomed to should be:
async def document_page( current_user: dict = Depends(get_current_user), document: dict = Depends(get_authorized_document),):Notice the = before Depends.
This version is not correct:
current_user: Depends(get_current_user)Python can evaluate an expression in the annotation position, so this is not simply a missing-parenthesis syntax error. The problem is what the annotation means to FastAPI: Depends(...) is dependency configuration, not the declared type of current_user. Use the default-value form or put that metadata inside Annotated.
The three valid styles
Section titled “The three valid styles”1. Traditional style
Section titled “1. Traditional style”This is likely what your existing applications use:
async def document_page( current_user: dict = Depends(get_current_user), document: dict = Depends(get_authorized_document),):Read it as:
Parameter name: current_userExpected type: dictFastAPI default/dependency marker: Depends(get_current_user)Although Depends(...) occupies Python’s “default value” position, FastAPI recognizes it as an instruction:
Call
get_current_user()and place its return value incurrent_user.
This remains completely valid FastAPI code.
In a later database-backed example, you might have more specific User and Document classes instead of dictionaries:
async def document_page( current_user: User = Depends(get_current_user), document: Document = Depends(get_authorized_document),):That gives your editor proper autocomplete:
current_user.usernamecurrent_user.firm_iddocument.titleThe next examples assume those classes exist and that their dependencies return instances of them. They illustrate the declaration styles; they do not replace today’s dictionary-backed dependencies yet.
2. Modern inline Annotated style
Section titled “2. Modern inline Annotated style”The equivalent modern form is:
from typing import Annotated
async def document_page( current_user: Annotated[ User, Depends(get_current_user), ], document: Annotated[ Document, Depends(get_authorized_document), ],):Here, Annotated carries two pieces of information:
Annotated[ User, # Python type Depends(get_current_user), # FastAPI metadata]At runtime, the behavior is effectively the same:
FastAPI calls get_current_user() ↓The function returns a User ↓FastAPI assigns it to current_userFastAPI currently recommends the Annotated form when possible. It keeps the actual type separate from FastAPI’s dependency metadata. FastAPI dependency documentation
3. Reusable Annotated alias
Section titled “3. Reusable Annotated alias”The tutorial took the inline form and extracted it into a reusable alias:
CurrentUser = Annotated[ User, Depends(get_current_user),]Then the route becomes:
async def document_page( current_user: CurrentUser,):This is equivalent to writing the complete Annotated declaration directly:
async def document_page( current_user: Annotated[ User, Depends(get_current_user), ],):The alias simply packages the type and dependency metadata under one reusable name.
FastAPI explicitly documents this type-alias pattern for dependencies that appear repeatedly. FastAPI shared Annotated dependencies
Which is preferred?
Section titled “Which is preferred?”For new code, I would use this general rule.
If the dependency appears only once or twice, use inline Annotated:
async def document_page( current_user: Annotated[ User, Depends(get_current_user), ],):It is explicit. Someone reading the route can immediately see where current_user comes from.
If it is a central dependency used throughout the application, create an alias:
CurrentUser = Annotated[ User, Depends(get_current_user),]Then use:
async def dashboard(current_user: CurrentUser): ...
async def list_documents(current_user: CurrentUser): ...
async def account_page(current_user: CurrentUser): ...This avoids repeating:
Annotated[User, Depends(get_current_user)]across dozens of routes.
I might name it this way for extra clarity:
CurrentUserDep = Annotated[ User, Depends(get_current_user),]Then:
async def document_page( current_user: CurrentUserDep,):The Dep suffix makes it obvious that this is not the User class itself. It is a dependency declaration that produces a User.
For today’s dictionary-backed application, we can use that naming convention without changing the returned values:
# app/dependencies.py, after the aliases defined above
CurrentUserDep = CurrentUserAuthorizedDocumentDep = AuthorizedDocumentThese are additional names for the same declarations. CurrentUserDep still supplies a dictionary, so the route still reads:
current_user["firm_id"]The following lessons use CurrentUserDep with this meaning. A later switch to an ORM user object would also require changing the dependency’s return value and its callers; renaming the alias alone does not perform that switch.
What about your existing applications?
Section titled “What about your existing applications?”If they use this:
current_user: User = Depends(get_current_user)they are fine. There is no architectural problem, runtime penalty, or urgent reason to rewrite them.
The difference is mostly declaration style:
# Traditionalcurrent_user: User = Depends(get_current_user)# Modern inlinecurrent_user: Annotated[ User, Depends(get_current_user),]# Modern reusable aliasCurrentUserDep = Annotated[ User, Depends(get_current_user),]
current_user: CurrentUserDepAll three tell FastAPI to perform the same essential operation.
My practical preference for a production modular monolith would be:
CurrentUserDep = Annotated[ User, Depends(get_current_user),]async def document_page( current_user: CurrentUserDep, document: AuthorizedDocumentDep,):But your existing Codex-built apps using User = Depends(...) are using an established, supported pattern. I would not refactor them merely to adopt the newer spelling.