← Back to FastAPI
Lesson 4.1 · Dependencies

What is Dependency Injection?

Stop copying the same parameters and checks into every endpoint. Write them once as a dependency, ask for it with Depends, and FastAPI runs it before your endpoint. We start with three copy-pasted endpoints - one with a real bug - and fix all three with one function.

Intermediate25 min

What you will be able to do

  • Explain dependency injection in plain words
  • Write a dependency function and use it with Depends
  • Make a short reusable type with Annotated
  • Know when the dependency runs, and what happens when its input is wrong
  • See the dependency’s parameters in /docs
  • Replace a dependency in a test with dependency_overrides

The idea, in plain English

Many endpoints need the same things before they can work: paging values, the logged-in user, a database session, a settings object. Copying that code into every endpoint is slow, and sooner or later one copy is different - a bug.

Dependency injection means: the endpoint does not make what it needs; it asks for it, and someone else gives it. In FastAPI you write a normal function (the dependency) and ask for it with Depends(). For every request FastAPI calls the dependency first - with its own query parameters, headers and checks - and passes the result to your endpoint.

In this lesson we see the problem with three copy-pasted endpoints, fix it with one pagination dependency, and replace that dependency in a test. FastAPI 0.143.0.

Worked example: A book shop API with three list endpoints that all need paging - first copy-pasted, then with one pagination dependency.

workflowOne dependency, many endpointsstep 1 / 3

1 - Copy-paste: one copy is wrong

reviews() was copied without the rules. limit=1000 returned everything, and skip=-5 returned the LAST reviews.

/books?limit=1000
422
/reviews?limit=1000
200, 300 items
/reviews?skip=-5
review 296, 297

FastAPI calls pagination() for every request and passes the result in. Real results from our book shop.

Words you will see in this module

Module 4 is about dependencies. These words come up in every lesson.

Small dictionary
DependencySomething an endpoint needs to do its work - and the function that makes it.
Dependency injectionGiving a function what it needs from outside, instead of it making it itself.
Depends()FastAPI’s marker: "call this function and give me the result".
AnnotatedAdds extra information to a type: Annotated[dict, Depends(pagination)].
OverrideUse a different function in place of a dependency - usually in tests.

An everyday example: a car wash

At a car wash, the washer does not bring water, soap and power from home:

  • The washer says what they need: "water and soap".
  • The car wash gives it to them - the same supply for every washer.
  • If the soap changes, nobody retrains the washers.
  • For a training day you can give them practice soap instead.
  • Your endpoint is the washer, Depends() is "I need this", FastAPI is the car wash, and the practice soap is an override in a test.

The problem: copy-paste

Three list endpoints - books, authors, reviews - all need skip and limit with the same rules (skip at least 0, limit 1 to 50). copy_paste.py writes them three times, and reviews() was copied in a hurry without the rules:

  • /books?limit=1000 was refused (422) - the rule worked.
  • /reviews?limit=1000 returned all 300 reviews. On a big table this is a slow, heavy answer.
  • /reviews?skip=-5&limit=2 returned review 296 and 297 - the LAST ones. In Python, a negative slice index counts from the end. No error, just wrong data.
  • Change the limit to 100 tomorrow, and you must find every copy.
copy_paste.py
from typing import Annotated from fastapi import FastAPI, Query app = FastAPI() BOOKS = [f"book {n}" for n in range(1, 101)] AUTHORS = [f"author {n}" for n in range(1, 41)] REVIEWS = [f"review {n}" for n in range(1, 301)] @app.get("/books") def books(skip: Annotated[int, Query(ge=0)] = 0, limit: Annotated[int, Query(ge=1, le=50)] = 10): return BOOKS[skip: skip + limit] @app.get("/authors") def authors(skip: Annotated[int, Query(ge=0)] = 0, limit: Annotated[int, Query(ge=1, le=50)] = 10): return AUTHORS[skip: skip + limit] @app.get("/reviews") def reviews(skip: int = 0, limit: int = 10): # copied in a hurry - the rules are missing return REVIEWS[skip: skip + limit]

Example 1 - one pagination dependency

paging.py writes the rules once:

  • pagination() is a normal function. Its arguments are normal query parameters with rules - exactly what we had in each endpoint before.
  • It returns a dict with the checked values. The print shows when it runs.
  • Page = Annotated[dict, Depends(pagination)] gives the whole thing a short name: "a dict, made by pagination()".
  • Each endpoint just says page: Page. FastAPI sees Depends, calls pagination() with the query string, and passes the dict in.
  • Do not call it yourself: Depends(pagination), not Depends(pagination()).
Example 1 - paging.py
from typing import Annotated from fastapi import Depends, FastAPI, Query app = FastAPI() BOOKS = [f"book {n}" for n in range(1, 101)] AUTHORS = [f"author {n}" for n in range(1, 41)] REVIEWS = [f"review {n}" for n in range(1, 301)] def pagination(skip: Annotated[int, Query(ge=0)] = 0, limit: Annotated[int, Query(ge=1, le=50)] = 10) -> dict: print(f" pagination() ran: skip={skip} limit={limit}") return {"skip": skip, "limit": limit} Page = Annotated[dict, Depends(pagination)] # write it once, use it everywhere @app.get("/books") def books(page: Page): print(" books() ran") return BOOKS[page["skip"]: page["skip"] + page["limit"]] @app.get("/authors") def authors(page: Page): return AUTHORS[page["skip"]: page["skip"] + page["limit"]] @app.get("/reviews") def reviews(page: Page): return REVIEWS[page["skip"]: page["skip"] + page["limit"]]
try_paging.py
from fastapi.testclient import TestClient import copy_paste import paging def call(app, url): r = TestClient(app).get(url) body = r.json() if r.status_code == 200: body = f"{len(body)} items: {body[0]} ... {body[-1]}" if len(body) > 2 else body else: body = [(e["loc"], e["msg"]) for e in body["detail"]] print(f"{url:<28} -> {r.status_code} {body}") print("--- copy_paste.py") for url in ["/books?limit=1000", "/reviews?limit=1000", "/reviews?skip=-5&limit=2"]: call(copy_paste.app, url) print("--- paging.py") for url in ["/books", "/books?skip=20&limit=3", "/books?limit=1000", "/reviews?limit=1000", "/authors?skip=38"]: print(url) call(paging.app, url)

Reading the output

  • For /books, "pagination() ran" comes before "books() ran" - the dependency runs first.
  • ?skip=20&limit=3 gave book 21 to book 23.
  • /books?limit=1000 and /reviews?limit=1000 both gave the same 422 now - and nothing was printed. FastAPI checks the input first; pagination() never ran.
  • /authors?skip=38 gave the last two authors. Only 40 exist, so the list is short - not an error.
  • The bug in reviews() is gone, and it was fixed in one place.
Output
--- copy_paste.py /books?limit=1000 -> 422 [(['query', 'limit'], 'Input should be less than or equal to 50')] /reviews?limit=1000 -> 200 300 items: review 1 ... review 300 /reviews?skip=-5&limit=2 -> 200 ['review 296', 'review 297'] --- paging.py /books pagination() ran: skip=0 limit=10 books() ran /books -> 200 10 items: book 1 ... book 10 /books?skip=20&limit=3 pagination() ran: skip=20 limit=3 books() ran /books?skip=20&limit=3 -> 200 3 items: book 21 ... book 23 /books?limit=1000 /books?limit=1000 -> 422 [(['query', 'limit'], 'Input should be less than or equal to 50')] /reviews?limit=1000 /reviews?limit=1000 -> 422 [(['query', 'limit'], 'Input should be less than or equal to 50')] /authors?skip=38 pagination() ran: skip=38 limit=10 /authors?skip=38 -> 200 ['author 39', 'author 40']

The dependency’s parameters are in /docs

FastAPI reads the dependency’s arguments too. Every endpoint that uses Page shows skip and limit in /docs, with their rules - although the endpoint itself has no such arguments.

Output - parameters in /openapi.json
/books [('skip', 'query', {'minimum': 0, 'default': 0}), ('limit', 'query', {'maximum': 50, 'minimum': 1, 'default': 10})] /authors [('skip', 'query', {'minimum': 0, 'default': 0}), ('limit', 'query', {'maximum': 50, 'minimum': 1, 'default': 10})] /reviews [('skip', 'query', {'minimum': 0, 'default': 0}), ('limit', 'query', {'maximum': 50, 'minimum': 1, 'default': 10})]

Two easy mistakes

  • Annotated[dict, pagination] without Depends: FastAPI does not know it is a dependency. It treats "page: dict" as a JSON body - GET /no-depends answered 422 "Field required" at ["body"], and /docs shows a required body.
  • Depends(pagination()) - with brackets: Python calls pagination() at once, while the file loads, and passes its dict to Depends. The app did not even start: "TypeError: {'skip': 0, 'limit': 10} is not a callable object".
  • Rule: Depends(the_function) - the function itself, without ().
Output
no Depends, GET /no-depends -> 422 {"detail":[{"type":"missing","loc":["body"],"msg":"Field required","input":null}]} no Depends, POST body -> True Depends(pagination()) -> TypeError: {'skip': 0, 'limit': 10} is not a callable object

Why "injection": swap it in a test

Because the endpoint only asks for "a Page", we can decide what it gets. app.dependency_overrides is a dict: original function -> replacement.

  • With first_two() in place of pagination(), /books?limit=5 returned 2 books - and pagination() did not run at all.
  • The override applies to every endpoint that uses pagination - /reviews too.
  • dependency_overrides.clear() puts the real one back.
  • This is the main reason to use dependencies for the user, the database and outside services: tests can replace them with fakes (Module 9).
try_override.py
from fastapi.testclient import TestClient from paging import app, pagination def first_two(): # a stand-in for the test return {"skip": 0, "limit": 2} client = TestClient(app) print("normal ->", client.get("/books?limit=5").json()) app.dependency_overrides[pagination] = first_two # swap the dependency print("overridden ->", client.get("/books?limit=5").json()) print("overridden ->", client.get("/reviews").json()) app.dependency_overrides.clear() # put the real one back print("cleared ->", client.get("/books?limit=5").json())
Output
pagination() ran: skip=0 limit=5 books() ran normal -> ['book 1', 'book 2', 'book 3', 'book 4', 'book 5'] books() ran overridden -> ['book 1', 'book 2'] overridden -> ['review 1', 'review 2'] pagination() ran: skip=0 limit=5 books() ran cleared -> ['book 1', 'book 2', 'book 3', 'book 4', 'book 5']

Dependencies at a glance

A dependency

A normal function.

def pagination(skip: int = 0, limit: int = 10) -> dict: ...
Ask for it

No brackets after the name.

page: Annotated[dict, Depends(pagination)]
Reuse the type

Write it once.

Page = Annotated[dict, Depends(pagination)]
def books(page: Page): ...
Swap in tests

Original -> replacement.

app.dependency_overrides[pagination] = fake
app.dependency_overrides.clear()

Try it yourself

The code does not change. Swap the content string and the program does something else entirely.

See it in /docs

“Run fastapi dev paging.py and open /docs. Which parameters does GET /authors show?”

Change a rule once

“Change le=50 to le=20 in pagination(). Which endpoints change?”

A sort option

“Add order: Literal["asc", "desc"] = "asc" to pagination() and use it in all three endpoints.”

Count the calls

“Call /books with limit=0. Does "pagination() ran" appear? Why not?”

What usually goes wrong

Calling the dependency

The app did not start: the dict is not a callable object.

✗ Depends(pagination())
✓ Depends(pagination)
Forgetting Depends

Without Depends FastAPI reads the argument as a JSON body.

✗ page: Annotated[dict, pagination]
✓ page: Annotated[dict, Depends(pagination)]
Copying parameters into every endpoint

One copy will differ. Our reviews() returned the last reviews for skip=-5.

Forgetting to clear overrides

An override stays until you clear it - the next test still gets the fake.

Practice

Write these yourself before opening anything. Getting them wrong first is most of how this sticks.

1.

Add a search dependency: q: str | None = None (at least 2 characters when given). Use it in /books and /authors to keep only items that contain q, together with Page. Then write a test that overrides search to always return "1" and checks /books.

Show hint

An endpoint can have two dependencies: def books(page: Page, q: Search). Remember dependency_overrides.clear().

Key points

  • A dependency is a normal function; Depends(func) asks FastAPI to call it.
  • FastAPI calls the dependency before the endpoint and passes its return value in.
  • The dependency’s own parameters are read from the request and checked - and shown in /docs.
  • If its input is wrong, nothing runs: 422.
  • Annotated[..., Depends(...)] gives a short reusable type, like Page.
  • dependency_overrides swaps a dependency, usually in tests.

Quick check before you move on

Which ran first for /books: pagination() or books()?
pagination().
Why did /reviews?skip=-5&limit=2 return review 296 and 297?
A negative slice index counts from the end of a Python list.
What did Depends(pagination()) do?
The app did not start: TypeError - a dict is not a callable object.
How do you put the real dependency back after a test?
app.dependency_overrides.clear().

Interview questions

What problem does dependency injection solve in FastAPI?

It removes repeated request-handling code (parsing, validation, auth, resources) from endpoints, keeps that logic in one tested place, documents its parameters automatically, and makes components replaceable in tests.

How do you replace a dependency in tests?

Set app.dependency_overrides[original] = replacement before the request, and clear it afterwards (often in a fixture). Sub-dependencies of the original are not called.

Quiz

  1. 1.

    Why did nothing print for /books?limit=1000?

  2. 2.

    Where do skip and limit appear in /docs, although books() has no such arguments?

  3. 3.

    What did GET /no-depends answer, and why?

Comments

Sign in to leave a comment. Your name and photo come from Google; nothing else is shared.

Loading comments...