Skip to content

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:

  1. Who is the current user?
  2. Which document may that user access?

Only after those questions succeed will FastAPI call the route.


We’ll add one module to the structure from the previous tutorial:

app/
├── main.py
├── data.py
├── security.py
├── dependencies.py
└── routers/
└── documents.py

The 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.


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
→ denied

It does not read cookies, raise redirects, or construct responses. Those belong closer to the HTTP layer.


Here is app/dependencies.py:

from typing import Annotated
from fastapi import Depends, HTTPException, Request, status
from .data import documents_by_id, users_by_id
from .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_user
get_authorized_document

The second depends on the first. This creates a dependency graph:

document_page
├── get_current_user
└── get_authorized_document
└── get_current_user

FastAPI’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 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: Request

FastAPI 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.session

Suppose 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 Unauthorized
Content-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.


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:

None

That 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 user

For 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.


The reusable declaration is:

CurrentUser = Annotated[
dict,
Depends(get_current_user),
]

Annotated combines a Python type with additional metadata.

The first part:

dict

says 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 immediately

FastAPI 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


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_id
current_user

FastAPI gets document_id from the URL.

For:

GET /documents/101

FastAPI converts the path text "101" into:

101

The second parameter is another dependency:

current_user: CurrentUser

Before 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.


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.


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
# True

Authorization succeeds.

For Max and document 202, it becomes:

10 == 20
# False

The 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 document

The 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:

AuthorizedDocument

The document router can now be much smaller:

from html import escape
from fastapi import APIRouter
from 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 authenticated
document exists and is authorized

That 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.


Look again at the graph:

document_page
├── CurrentUser
└── AuthorizedDocument
└── CurrentUser

The 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 again

Each 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.


Suppose Max’s browser sends:

GET /documents/101 HTTP/1.1
Host: 127.0.0.1:8000
Cookie: app_session=...

For this successful request, the important preparation steps are:

  1. The browser constructs the HTTP request and includes its session cookie.
  2. The server receives the request.
  3. SessionMiddleware verifies and decodes the signed cookie.
  4. The middleware makes {"user_id": 1} available through request.session.
  5. FastAPI’s combined routing table matches GET /documents/{document_id}.
  6. FastAPI examines the route’s dependency graph.
  7. get_current_user() receives the current Request.
  8. Python reads user ID 1 from request.session.
  9. Python retrieves user 1 from users_by_id.
  10. get_current_user() returns Max’s user dictionary.
  11. FastAPI stores that dependency result for this request.
  12. FastAPI validates "101" as the integer 101 for the document dependency.
  13. get_authorized_document() receives document_id=101 and Max’s user object.
  14. Python retrieves document 101.
  15. user_can_view_document() compares the user’s firm with the document’s firm.
  16. Authorization succeeds.
  17. get_authorized_document() returns the document.
  18. FastAPI calls document_page() with both prepared objects.
  19. Python escapes the title and username and builds the HTML string.
  20. FastAPI packages it into an HTMLResponse.
  21. The response travels outward through middleware.
  22. The server sends the HTTP response.
  23. 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.


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 headers

Dependencies belong to selected routes or routers:

Document routes
→ authenticated user
→ authorized document

Middleware 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_user
document

Middleware usually modifies the request or response and passes control onward.


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: CurrentUser

FastAPI 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.


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: CurrentUser

Router-level dependencies are most useful for requirements that must run but whose return value the route does not need directly.


Depends turns route preparation into an explicit graph.

The route declares the valid state it requires:

an authenticated user
an existing, authorized document

FastAPI 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.


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.

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_user
Expected type: dict
FastAPI 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 in current_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.username
current_user.firm_id
document.title

The 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.


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_user

FastAPI currently recommends the Annotated form when possible. It keeps the actual type separate from FastAPI’s dependency metadata. FastAPI dependency documentation


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

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 = CurrentUser
AuthorizedDocumentDep = AuthorizedDocument

These 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.

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:

# Traditional
current_user: User = Depends(get_current_user)
# Modern inline
current_user: Annotated[
User,
Depends(get_current_user),
]
# Modern reusable alias
CurrentUserDep = Annotated[
User,
Depends(get_current_user),
]
current_user: CurrentUserDep

All three tell FastAPI to perform the same essential operation.

My practical preference for a production modular monolith would be:

dependencies.py
CurrentUserDep = Annotated[
User,
Depends(get_current_user),
]
routers/documents.py
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.