Course topics

By WebNest Studio Engineering Team

Python Tutorial

Dependency Injection and APIRouter

Many endpoints need the same things: a database session, the current user, pagination settings, an API key check. FastAPI's dependency injection system lets you write that logic once as a function (or class) and ask for it with Depends(). FastAPI calls the dependency, passes the result into your endpoint, handles cleanup, and even documents the parameters the dependency needs.

As an application grows, APIRouter lets you split endpoints into modules — books.py, users.py — with shared prefixes, tags and dependencies. This lesson covers both.

Why it matters

Database sessions, the current user, pagination settings and permission checks are needed by many endpoints. FastAPI's Depends lets you write each once and declare it where it is needed, and it is also what makes endpoints easy to test. Routers then split a growing application into files, which every real project has to do.

Depends()

A dependency is any callable whose parameters FastAPI can fill (query parameters, headers, other dependencies…). Declare it with Annotated[Type, Depends(func)]; a type alias such as Pagination = Annotated[dict, Depends(pagination)] keeps signatures short. Dependencies can depend on other dependencies, forming a tree; within one request each dependency is called once and its result is cached. Classes work too — Depends(MyClass) calls the constructor.

Dependencies with yield

A dependency that uses yield runs setup code, gives a value to the endpoint, and runs cleanup after the response is built — exactly what a database session or a file handle needs. Put cleanup in finally so it always runs. Dependencies can also raise HTTPException, which is how authentication and permission checks are usually implemented.

APIRouter and Project Structure

Create router = APIRouter(prefix="/books", tags=["books"]) in its own module, decorate endpoints with @router.get(...), and add it to the app with app.include_router(router). Routers and include_router accept dependencies=[Depends(...)] to protect a whole group of endpoints. A common layout is app/main.py, app/routers/, app/schemas.py (Pydantic models), app/models.py (database models), app/dependencies.py and app/config.py.

Examples

Reusable dependencies: functions, classes and sub-dependencies

Python
from typing import Annotated
from fastapi import Depends, FastAPI, Header, HTTPException, Query
from fastapi.testclient import TestClient

app = FastAPI()
PRODUCTS = [f"product-{n:02d}" for n in range(1, 26)]

def pagination(page: Annotated[int, Query(ge=1)] = 1, size: Annotated[int, Query(ge=1, le=50)] = 10):
    return {"offset": (page - 1) * size, "limit": size}

Pagination = Annotated[dict, Depends(pagination)]

class SortOptions:                                   # a class used as a dependency
    def __init__(self, sort: str = "name", desc: bool = False):
        self.sort = sort
        self.desc = desc

def api_key(x_api_key: Annotated[str | None, Header()] = None):   # reads the X-API-Key header
    if x_api_key != "demo-key":
        raise HTTPException(status_code=401, detail="Invalid or missing API key")
    return "partner-42"

def current_partner(partner_id: Annotated[str, Depends(api_key)]):   # depends on api_key
    return {"id": partner_id, "plan": "gold"}

@app.get("/products")
def list_products(page: Pagination, sorting: Annotated[SortOptions, Depends()]):
    items = sorted(PRODUCTS, reverse=sorting.desc)
    return items[page["offset"]: page["offset"] + page["limit"]]

@app.get("/partner/report")
def report(partner: Annotated[dict, Depends(current_partner)], page: Pagination):
    return {"partner": partner, "page": page}

client = TestClient(app)
print(client.get("/products?page=3&size=4").json())
print(client.get("/products?size=3&desc=true").json())
print(client.get("/partner/report").json())
print(client.get("/partner/report", headers={"X-API-Key": "demo-key"}).json())
Output
['product-09', 'product-10', 'product-11', 'product-12']
['product-25', 'product-24', 'product-23']
{'detail': 'Invalid or missing API key'}
{'partner': {'id': 'partner-42', 'plan': 'gold'}, 'page': {'offset': 0, 'limit': 10}}

A yield dependency with setup and cleanup

Python
from typing import Annotated
from fastapi import Depends, FastAPI, HTTPException
from fastapi.testclient import TestClient

app = FastAPI()
log = []

class FakeSession:
    def __init__(self):
        log.append("open session")
    def query(self, book_id):
        if book_id > 2:
            raise LookupError(book_id)
        return {"id": book_id, "title": ["Python Basics", "Deep Python"][book_id - 1]}
    def close(self):
        log.append("close session")

def get_session():
    session = FakeSession()
    try:
        yield session                     # the endpoint runs here
    finally:
        session.close()                   # always runs, even after errors

@app.get("/books/{book_id}")
def get_book(book_id: int, session: Annotated[FakeSession, Depends(get_session)]):
    try:
        return session.query(book_id)
    except LookupError:
        raise HTTPException(404, "Book not found")

client = TestClient(app)
print(client.get("/books/2").json())
print(client.get("/books/5").status_code)
print(log)
Output
{'id': 2, 'title': 'Deep Python'}
404
['open session', 'close session', 'open session', 'close session']

Splitting an application with APIRouter

Python
from typing import Annotated
from fastapi import APIRouter, Depends, FastAPI, Header, HTTPException
from fastapi.testclient import TestClient

# app/dependencies.py
def require_admin(x_role: Annotated[str, Header()] = "user"):
    if x_role != "admin":
        raise HTTPException(403, "Admins only")

# app/routers/books.py
books_router = APIRouter(prefix="/books", tags=["books"])

@books_router.get("/")
def list_books():
    return ["Python Basics", "Deep Python"]

@books_router.get("/{book_id}")
def get_book(book_id: int):
    return {"id": book_id}

# app/routers/admin.py — every route here requires an admin
admin_router = APIRouter(prefix="/admin", tags=["admin"], dependencies=[Depends(require_admin)])

@admin_router.get("/stats")
def stats():
    return {"books": 2, "users": 10}

# app/main.py
app = FastAPI()
app.include_router(books_router)
app.include_router(admin_router, prefix="/api")      # final path: /api/admin/stats

client = TestClient(app)
print(client.get("/books/").json(), client.get("/books/7").json())
print(client.get("/api/admin/stats").status_code)
print(client.get("/api/admin/stats", headers={"X-Role": "admin"}).json())
print(client.get("/admin/stats").status_code)                 # only mounted under /api
Output
['Python Basics', 'Deep Python'] {'id': 7}
403
{'books': 2, 'users': 10}
404

Common Mistakes

  • Creating database sessions or clients inside every endpoint instead of using a dependency.
  • Forgetting try/finally in a yield dependency, so cleanup is skipped when the endpoint fails.
  • Calling the dependency yourself (Depends(get_db())) instead of passing the function (Depends(get_db)).
  • Putting all endpoints in one huge main.py instead of APIRouter modules.
  • Repeating auth checks in each endpoint instead of router-level dependencies.

Exercise

Write a pagination dependency that reads skip and limit from the query string, with defaults of 0 and 10, and use it in GET /items. Then create a router with the prefix /users, add a GET /me endpoint to it, and include it in the application.

Expected output: {'skip': 5, 'limit': 10} then {'user': 'me'}

Python · starter code
from fastapi import APIRouter, Depends, FastAPI
from fastapi.testclient import TestClient

app = FastAPI()


# TODO: def pagination(skip: int = 0, limit: int = 10) returning a dict

# TODO: GET /items that receives the dict through Depends and returns it

# TODO: an APIRouter with prefix "/users" and a GET "/me" returning {"user": "me"}
# TODO: include the router in the app


client = TestClient(app)
print(client.get("/items?skip=5").json())
print(client.get("/users/me").json())
Show hints
  • A dependency is used as a default value: def read_items(page: dict = Depends(pagination)):.
  • Create the router with APIRouter(prefix="/users") and add it with app.include_router(router).
Show solution
Python · solution
from fastapi import APIRouter, Depends, FastAPI
from fastapi.testclient import TestClient

app = FastAPI()


def pagination(skip: int = 0, limit: int = 10):
    return {"skip": skip, "limit": limit}


@app.get("/items")
def read_items(page: dict = Depends(pagination)):
    return page


router = APIRouter(prefix="/users")


@router.get("/me")
def read_me():
    return {"user": "me"}


app.include_router(router)


client = TestClient(app)
print(client.get("/items?skip=5").json())
print(client.get("/users/me").json())

Quick quiz

1. What does Depends(get_db) do in a parameter list?

  • A. Imports a module
  • B. Creates a database
  • C. Calls get_db for the request and passes its result to the function
  • D. Marks the parameter as optional
Show answer

C. The dependency can itself have parameters and other dependencies.

2. In a dependency written with yield, when does the code after the yield run?

  • A. Before the endpoint
  • B. Only on errors
  • C. Never
  • D. After the response has been produced, for clean-up
Show answer

D. This is how a database session is closed after each request.

3. What is APIRouter used for?

  • A. Grouping related endpoints so an application can be split across files
  • B. Load balancing
  • C. Routing emails
  • D. Caching
Show answer

A. Each router is added to the application with include_router.

Interview questions

What is dependency injection in FastAPI?

Show answer

An endpoint declares what it needs as parameters with Depends(...), and FastAPI calls those functions for each request and supplies the results. Dependencies can depend on other dependencies, can read request data themselves, and can clean up after the response with yield. Shared logic such as authentication or a database session is written once and reused.

How do dependencies help with testing?

Show answer

Any dependency can be replaced through app.dependency_overrides. A test can substitute the function that provides the database session with one that uses a test database, or the function that returns the current user with one that returns a fixed user, without changing the application code or needing real credentials.

Key Points to Remember

  • Depends() injects reusable logic: sessions, current user, pagination, permission checks.
  • Dependencies can have their own parameters and sub-dependencies; results are cached per request.
  • yield dependencies provide setup and guaranteed cleanup.
  • APIRouter groups endpoints with a shared prefix, tags and dependencies.
  • Annotated type aliases keep endpoint signatures short and consistent.

Practice in the playground

Write and run your own code for this topic, or start from the exercise or an example. A layered FastAPI project with a SQLite database, running in your browser. Your code for each topic is kept in this browser.

Run the examples

Change an input, predict the result, then compare it with the output. Explain why the result changes.

WebNest Studio

Written by

WebNest Studio Engineering Team

Practical lessons from developers working with Java, Python, React, databases and production systems.

Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering