Skip to content

APIRouter & Project Structure: Layers vs Features, Prefixes, Tags, Lifespan, Settings ​

"If you are building an application or a web API, it's rarely the case that you can put everything in a single file. FastAPI provides a convenience tool to structure your application while keeping all the flexibility." — FastAPI documentation, "Bigger Applications - Multiple Files", fastapi.tiangolo.com/tutorial/bigger-applications

Summary: A FastAPI service outgrows one main.py quickly. APIRouter is a "mini FastAPI" that holds the path operations of one area (catalog, orders, admin) together with the settings they share (prefix, tags, dependencies, responses, default_response_class); include_router copies those routes into the app (or into another router) and combines the prefixes, tags, dependencies and responses. Around the routers sits an app factory (create_app()) that reads typed settings once (pydantic-settings, BaseSettings, env vars, .env files, a secrets directory, cached with lru_cache and injected as a dependency), opens shared resources in the lifespan (an asynccontextmanager that runs before the first request and after the last one, storing them on app.state), adds middleware, mounts static files and sub-applications, and includes the router tree. The files on disk follow one of two shapes: by technical layer (routers/, schemas/, models/, services/, repositories/) or by feature (catalog/, orders/, each a vertical slice with its own router, schemas, models, repository and service). Focus: APIRouter and its parameters, include_router (prefix, tags, dependencies, responses, include_in_schema, nesting, including the same router twice), route order and path conflicts across routers, operationId uniqueness and generate_unique_id_function, openapi_tags, hiding internal routes, the app factory, the entry point (shop.asgi:app, uvicorn --factory, [tool.fastapi] entrypoint), lifespan (asynccontextmanager, startup and shutdown, app.state, request.app, router lifespans, mounted apps), settings (BaseSettings, SettingsConfigDict, env_prefix, env_file, secrets_dir, priority of sources, extra="forbid", SecretStr, per-environment files, the lru_cache Settings dependency), layouts (flat, by technical layer, by feature), separation of concerns between routers, services and repositories, package-relative imports, __init__.py, circular imports, src/ layout vs flat, naming conventions, API versioning with routers, app.mount for sub-applications and StaticFiles, middleware order relative to routers, and a test tree that mirrors the package. Learning goal: Split a FastAPI service into routers and packages so that each feature can be read, changed and tested in one place; build the app in a factory so tests and workers get a fresh, fully configured instance; move every configuration value into one typed, validated, cached Settings object; open and close shared resources in the lifespan; and pick the layout (by layer or by feature) that fits the size of the codebase and the team, knowing when it is time to switch.

This page owns the structure of a FastAPI codebase: routers, the app factory, lifespan, settings and folders. It does not re-teach its neighbours: routes, path and query parameters and status codes are in FastAPI Fundamentals; request bodies, headers and validation errors in Request Validation; Depends, yield dependencies and dependency_overrides in Dependency Injection; exception handlers and Problem Details in Exceptions & Responses; SQLAlchemy engines, sessions and models in SQLAlchemy 2 & SQLModel; Uvicorn and Gunicorn tuning, logging and Docker images in FastAPI in Production; fixtures, async clients and test databases in Testing FastAPI; uv, Ruff and lock files in Python Project Tooling. The end-to-end project that uses this structure is the rooms & bookings CRUD project. Version design (what counts as breaking, deprecation windows) is in API Versioning & Evolution; module boundaries as an architecture style in Modular Monolith and Clean & Hexagonal Architecture; the Go twin of this chapter is Go Project Layout, Linting & Build.

Facts below were checked against the FastAPI documentation (tutorial "Bigger Applications", "Metadata and Docs URLs", the advanced pages on lifespan events, settings, sub-applications, path operation configuration, generating clients and testing events, the APIRouter and FastAPI reference pages, and the release notes up to 0.165.0 of 2026-11-18), the source of FastAPI 0.128.8 (routing.py, utils.py, openapi/utils.py), the Pydantic Settings documentation, the Starlette docs (applications, routing, lifespan, middleware), the Python tutorial and language reference on modules and imports, PEP 328 and PEP 420, the Python Packaging User Guide on src and flat layouts, the pytest good-practices and fixtures pages, the Laravel 13 docs (routing, controllers, service providers, directory structure, configuration) and the Go module layout guide. The page is written for Python 3.12+ and current FastAPI. The snippets ran on the only interpreter on the build machine, CPython 3.9.6, so the snippet project pins the newest releases that still install there: FastAPI 0.128.8, Starlette 0.49.3, Pydantic 2.13.5, pydantic-settings 2.11.0 (2.12.0 dropped Python 3.9; the latest, 2.16.3, needs 3.11+), Uvicorn 0.39.0, httpx 0.28.1, pytest 8.4.2 and eval-type-backport for str | None on 3.9; the resolved set is in the saved requirements.lock. Every status code, error text, warning and log line marked "real" is what that run printed. Two behaviours differ in current releases and are marked where they matter: FastAPI 0.137.0 (2026-06-14) stopped copying routes at include_router time ("Adding routes (path operations) after a router is included now works, they are reflected as they are not copied"), and the current Pydantic Settings docs describe options that 2.11.0 does not have (env_file_depth, dotenv_filtering, env_prefix_target, PYDANTIC_SETTINGS_DEBUG; checked by searching the installed package).

Page map ​

If you are looking forGo to
The tables to memoriseEverything in one minute
Why routers, factories and settings existWhy it exists
Versions: Blueprints to live routersWhere it comes from
The flat app and the two packaged versionsPython
Modules, packages, __init__.pyBreaking up logic across files
router = APIRouter(...)The APIRouter class
app.include_router(...), nestingIncluding routers
/api/v1/products, docs groupsPrefix and tags
Auth for a whole router, shared 404 docsRouter dependencies and responses
HTML or plain-text routersRouter defaults
/users/me answered by /users/{id}Route order across routers
operationId, SDK method namesoperationId and generate_unique_id_function
openapi_tags, hidden routesOpenAPI organisation
create_app()The app factory
main.py, asgi.py, --factoryEntry points
Pools and clients opened onceLifespan
A router with its own startupRouter lifespans and lifespan state
BaseSettings, .envSettings with pydantic-settings
Which value wins, secrets filesSettings sources and priority
@lru_cache get_settings(), dev/staging/prodThe Settings dependency
routers/ schemas/ models/ services/ repositories/Organising by technical layer
catalog/ orders/ vertical slicesOrganising by feature
Where SQL and business rules liveSeparation of concerns
from ..core import x, import cyclesImports and circular imports
src/ or not, file namessrc layout and naming conventions
/v1 and /v2 side by sideVersioning with routers
app.mount, StaticFilesMounts and sub-applications
Where middleware runsMiddleware and routers
tests/ that mirror app/Tests mirroring packages
What include_router does internally, exact errorsMechanics
The usual structure bugsSolving the classic problems
Layer or feature, one service or severalChoosing
Monolith to distributed systemIn architecture
Run it yourselfLab
routes/api.php, controllers, service providersFor PHP/Laravel developers
cmd/, internal/The Go angle

Everything in one minute ​

The building blocks. Each row is unpacked in the concept catalogue.

PieceWhat it isPlain wordsIn the snippet
APIRouterA group of path operations plus shared settings"A mini FastAPI for one area"shop/catalog/router.py
include_routerAdds a router's routes to an app or another router"Plug the group in under a prefix"shop/api.py
prefixPath segment prepended to every route of the router"/products written once"APIRouter(prefix="/products")
tagsDocs groups (and generated SDK services)"Chapters in /docs"tags=["catalog"]
Router dependenciesDependencies run before every route of the router"One guard for the whole group"admin router, require_admin
App factoryA function that builds and returns a configured app"create_app(settings), fresh every time"shop/main.py
LifespanAsync context manager around the app's life"Open before yield, close after"shop/core/lifespan.py
app.stateAttribute bag on the app instance"Where the pool lives"app.state.db
BaseSettingsPydantic model filled from env vars, .env, secret files"Config with types"shop/core/config.py
get_settings + lru_cacheThe Settings dependency, built once"Read config once, override in tests"Depends(get_settings)
app.mountAttach a separate ASGI app under a path"A different app lives here"/static, /legacy

The two layouts of the same API (both are real packages in the snippet; a test proves they publish the same operations).

QuestionBy technical layer (layered/)By feature (shop/)
Top-level foldersrouters schemas models services repositoriescatalog/, orders/, core/, internal/
Files for "orders"5 files in 5 folders5 files in 1 folder
A new developer finds the order rules inservices/orders.py (after guessing the layer)orders/service.py
Cross-feature importsEverywhere (routers/orders.py imports repositories/products.py)Only through catalog/service.py
FitsSmall services, one team, < ~10 resourcesMonoliths with many domains, several teams
Turns into microservicesHard: every service needs a slice of every layerEasy: move one folder
Used byThe FastAPI tutorial (app/routers/), the full-stack template (app/api/routes/)fastapi-best-practices (Netflix Dispatch style)

Where a setting comes from (pydantic-settings, highest priority first; all checked in test_settings.py).

PrioritySourceExampleNotes
1Keyword argumentsSettings(app_name="x")Tests and factories
2Environment variablesSHOP_APP_NAME=xCase-insensitive by default, prefix from env_prefix
3Dotenv files.env, then .env.prodLater file wins; missing files are skipped
4Secrets directory/run/secrets/shop_app_nameFile name = variable name, content = value
5Field defaultapp_name: str = "Shop API"No default = required

What include_router combines (0.128.8 source, APIRouter.include_router).

ParameterHow it combinesEffect
prefixinclude prefix + router prefix + route path/api + /v1 + /products + /{product_id}
tagsinclude tags first, then the route's own tags["admin"] + route tags
dependenciesapp → include → router → decorator → parametersExecuted in that order (measured)
responses{**include_responses, **route.responses}The route's own entries win on the same status
default_response_classroute → router → include → parentFirst one set wins
include_in_schemaroute and router and includeAny False hides the route
deprecatedroute or include or parentAny True marks it
generate_unique_id_functionroute → router → include → parentDecides the operationId
lifespanNested inside the parent's lifespanRouter startup after app startup

Why it exists ​

The first FastAPI app is one file, and that is the right start. It stops being right at a predictable point: the file passes a few hundred lines, two people edit it in the same week, a test wants a different database, the same /api/v1 and the same tag are repeated on forty decorators, and a new route lands below a parameter route that swallows it. Configuration is read with os.environ.get(...) in five places, always as a string ("false" is truthy), and the database connection is opened when the module is imported, so importing the module in a test opens it too. The Before snippet is that file, and its test pins down each of those problems.

Three tools solve three different problems. Routers solve grouping: the routes of one area and their shared settings live together, and the app says where the group is plugged in. The app factory and the lifespan solve wiring: building an app is a function call that takes settings and returns a fresh object, and shared resources have one place where they are opened and one where they are closed. Settings solve configuration: every value that differs between laptop, CI, staging and production is a typed field, validated once at startup, read from the environment as twelve-factor apps do ("The twelve-factor app stores config in environment variables"), and injectable so a test can replace it. Folder layout (by layer or by feature) is the fourth decision, and it is the one that decides how the code ages.

One main.pyRouters + factory + settings + packages
/api/v1/products and tags=["products"] on every decoratorAPIRouter(prefix="/products", tags=["catalog"]) once
Auth copied into every admin routeinclude_router(admin.router, dependencies=[Depends(require_admin)])
os.environ.get("DEBUG", "false") is a truthy stringdocs_enabled: bool parsed and validated
Connection opened at import, never closedOpened in the lifespan, closed after yield
Tests share one module-level appcreate_app(test_settings) per test
1,500 lines, merge conflictsOne folder per feature, one owner
operationId = get_product_api_v1_products__product_id__getcatalog-get_product

An everyday picture. A department store. The building is the app, the departments are routers: each has its own floor plan (routes), its own signs (tags) and sometimes its own security desk (router dependencies), and the store directory says which floor each one is on (prefix). The opening and closing routine is the lifespan: lights, tills and the cash safe are opened before the doors open and locked after the last customer leaves, not every time someone walks in. The settings are the store manual for this branch: opening hours, currency, the safe code (a secret, kept in an envelope rather than printed in the manual). A factory is the blueprint used to open a new branch: the same building, a different manual. And the layout question is how the stock room is organised: by item type (all shelves here, all labels there, all tills over there) or by department (each department keeps its own shelves, labels and till). The first is easy when there are three departments; the second is the only thing that works when there are thirty.

Three common misunderstandings, up front ​

  1. "A router is a separate app." An APIRouter is not mounted and not isolated: its routes become part of the app's single route table and single OpenAPI document. The FastAPI docs say it directly: "The APIRouters are not 'mounted', they are not isolated from the rest of the application." A mounted app (app.mount) is the separate thing: its own docs, its own middleware stack, and no lifespan events.
  2. "Settings are read whenever I access them." Settings() reads the environment, the .env files and the secrets directory when the object is created; with @lru_cache on get_settings() that is once per process. Changing an environment variable later changes nothing until the cache is cleared (test_get_settings_is_cached_until_cleared).
  3. "Feature folders are just a different naming of the same thing." The difference is where change lands. With layers, one feature change touches every layer folder; with features, it touches one folder, and the folder boundary can be enforced (only catalog/service.py may be imported by orders/). That boundary is what later makes a module extractable into a service.

Where it comes from ​

The idea is older than FastAPI: the FastAPI tutorial notes "If you come from Flask, this would be the equivalent of Flask's Blueprints." In FastAPI itself, include_router came first and grew options over the early releases (tags in include_router, then responses, then dependencies). Version 0.62.0 (2020-11-29) moved most of them onto the router: "Up to now, for several options, the only way to apply them to a group of path operations was in include_router … Most of these settings are now supported in APIRouter, which normally lives closer to the related code, so it is recommended to use APIRouter when possible." 0.75.0 (2022-03-04) added a custom generate_unique_id_function together with the "Generate Clients" docs. 0.93.0 (2023-03-07) added lifespan context managers "superseding startup and shutdown events". 0.100.0 (2023-07-07) moved to Pydantic v2, and with it settings left Pydantic: "To use settings you should now import from pydantic_settings import BaseSettings instead of importing from pydantic directly" (pydantic-settings 2.0.0 was uploaded on 2023-06-30). 0.112.2 (2024-08-24) made include_router merge nested router lifespans ("Ensure that app.include_router merges nested lifespans"). 0.126.0 (2025-12-20) added pydantic-settings to the standard extra. 0.128.3 (2026-02-06) re-implemented on_event inside FastAPI "for compatibility with the next Starlette", and 0.133.0 (2026-02-24) added support for Starlette 1.0.0+. 0.137.0 (2026-06-14) is the big structural change for this chapter: "Refactor internals to preserve APIRouter and APIRoute instances": before it, "router.include_router(other_router) would take each path operation from other_router and 'clone' it"; after it, routes added after inclusion are visible and router.routes is a tree, not a flat list. 0.138.0 (2026-06-20) added app.frontend("/", directory="dist") for single-page front-ends, and 0.146.0 (2026-10-18) deprecated FastAPI(root_path=...) in favour of the server option.

On the Python side, explicit relative imports with leading dots come from PEP 328 (created 21 December 2003, Python-Version 2.4–2.6), and packages without __init__.py (namespace packages) from PEP 420 (created 19 April 2012, Python 3.3). The src-versus-flat layout discussion is in the Python Packaging User Guide.

1   2003-12    PEP 328 created (Python 2.4-2.6): relative imports with leading dots
2   2012       PEP 420 (Python 3.3): namespace packages without __init__.py
3   2020-11    FastAPI 0.62.0: prefix, tags, dependencies, responses on APIRouter itself
4   2022-03    FastAPI 0.75.0: generate_unique_id_function, "Generate Clients" docs
5   2023-03    FastAPI 0.93.0: lifespan= supersedes startup/shutdown events
6   2023-06/07 pydantic-settings 2.0.0; FastAPI 0.100.0 imports BaseSettings from pydantic_settings
7   2024-08    FastAPI 0.112.2: include_router merges nested router lifespans
8   2026-02    FastAPI 0.128.3 re-implements on_event; 0.133.0 supports Starlette 1.0
9   2026-06    FastAPI 0.137.0: routers kept live (no copy at include); 0.138.0 app.frontend()
10  2026-10/11 FastAPI 0.146.0 deprecates FastAPI(root_path=); 0.165.0 latest (needs Python >= 3.11)

Python ​

Before ​

The whole catalog-and-orders API in one module. Configuration is read from os.environ at import time as strings; a SQLite connection is opened at import; /api/v1 and the tag are repeated on every decorator, once as products and once as Products; /api/v1/products/featured is declared after /api/v1/products/{product_id}; an admin reset route is public and listed in /docs; startup work is in the deprecated on_event hook.

py
"""BEFORE: the whole service in one module.

It works on a quiet day. Every problem below is pinned down by tests/before/test_before.py:
config read from os.environ at import time as raw strings, a database connection opened at import,
the /api/v1 prefix and the tag repeated (and misspelled) on every route, a literal route declared
after the parameter route that swallows it, an admin route that is public and listed in the docs,
and startup work in the deprecated on_event hook.
"""
from __future__ import annotations

import os
import sqlite3

from fastapi import FastAPI, HTTPException

# Read once, at import, as strings. "false" is a non-empty string, so DEBUG is truthy.
DEBUG = os.environ.get("SHOP_DEBUG", "false")
DATABASE_URL = os.environ.get("SHOP_DATABASE_URL", ":memory:")
PAGE_SIZE = os.environ.get("SHOP_PAGE_SIZE", "20")  # a str; every caller must remember int()

# Opened when the module is imported: by uvicorn, by every test, by a script that only wants a constant.
conn = sqlite3.connect(DATABASE_URL, check_same_thread=False)
conn.execute("CREATE TABLE IF NOT EXISTS products (id INTEGER PRIMARY KEY, sku TEXT, name TEXT, price_cents INTEGER)")

app = FastAPI(debug=bool(DEBUG))


@app.on_event("startup")  # deprecated; ignored entirely once a lifespan= is added
def seed() -> None:
    conn.execute("DELETE FROM products")
    conn.executemany(
        "INSERT INTO products (id, sku, name, price_cents) VALUES (?, ?, ?, ?)",
        [(1, "BK-001", "The Pragmatic Programmer", 4200), (2, "GM-001", "Catan", 4500)],
    )


@app.get("/api/v1/products", tags=["products"])
def list_products(limit: int = int(PAGE_SIZE)):
    rows = conn.execute("SELECT id, sku, name, price_cents FROM products ORDER BY id LIMIT ?", (limit,))
    return [dict(zip(("id", "sku", "name", "price_cents"), r)) for r in rows]


@app.get("/api/v1/products/{product_id}", tags=["Products"])  # a second spelling: a second docs group
def get_product(product_id: int):
    row = conn.execute("SELECT id, sku, name, price_cents FROM products WHERE id = ?", (product_id,)).fetchone()
    if row is None:
        raise HTTPException(404, "Product not found")
    return dict(zip(("id", "sku", "name", "price_cents"), row))


@app.get("/api/v1/products/featured", tags=["products"])  # never reached: {product_id} matched first
def featured_products():
    return [{"id": 2, "sku": "GM-001"}]


@app.get("/api/v1/orders/{order_id}", tags=["orders"])
def get_order(order_id: int):
    raise HTTPException(404, "Order not found")


@app.post("/api/v1/admin/reset")  # no auth, no tag, and listed in /docs for everyone
def admin_reset():
    conn.execute("DELETE FROM products")
    return {"reset": True}

The test pins down each problem: bool("false") is True, the connection exists as soon as the module is imported, featured answers 422, the docs have two groups for one resource and list the admin route, and the default operationId is get_product_api_v1_products__product_id__get.

py
"""Pins down every problem of the flat before/main.py."""
from __future__ import annotations

from fastapi.testclient import TestClient

from before import main as before


def test_string_config_is_truthy():
    assert before.DEBUG == "false"
    assert bool(before.DEBUG) is True  # the classic bug: "false" enables debug mode
    assert before.app.debug is True
    assert isinstance(before.PAGE_SIZE, str)


def test_connection_was_opened_at_import():
    # Importing the module for a test already created a connection; nothing closes it.
    assert before.conn.execute("SELECT 1").fetchone() == (1,)


def test_literal_route_after_parameter_route_is_shadowed():
    with TestClient(before.app) as client:
        r = client.get("/api/v1/products/featured")
    assert r.status_code == 422  # "featured" was parsed as product_id: int
    assert r.json()["detail"][0]["type"] == "int_parsing"


def test_tags_are_inconsistent_and_admin_is_public():
    schema = before.app.openapi()
    tags = {t for path in schema["paths"].values() for op in path.values() for t in op.get("tags", [])}
    assert {"products", "Products"} <= tags  # two docs groups for one resource
    assert "/api/v1/admin/reset" in schema["paths"]  # listed in /docs, no auth
    with TestClient(before.app) as client:
        assert client.post("/api/v1/admin/reset").json() == {"reset": True}


def test_default_operation_ids_are_long():
    ops = before.app.openapi()["paths"]["/api/v1/products/{product_id}"]["get"]
    assert ops["operationId"] == "get_product_api_v1_products__product_id__get"

After ​

The same API twice, in the two layouts this chapter compares. By technical layer first: one package per layer, one module per resource inside each.

py
from __future__ import annotations

from contextlib import asynccontextmanager
from typing import AsyncIterator

from fastapi import APIRouter, FastAPI

from .db import Database
from .routers import orders, products


@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
    app.state.db = Database()
    app.state.db.connect()
    yield
    app.state.db.close()


def create_app(admin_token: str = "change-me") -> FastAPI:
    app = FastAPI(title="Shop API (by layer)", lifespan=lifespan)
    app.state.admin_token = admin_token
    v1 = APIRouter(prefix="/api/v1")
    v1.include_router(products.router)  # include children BEFORE including v1 in the app (copy at include, 0.128.8)
    v1.include_router(orders.router)
    app.include_router(v1)
    return app
py
from __future__ import annotations

from typing import Annotated

from fastapi import APIRouter, Depends, HTTPException, status

from ..repositories.orders import OrderRepository
from ..repositories.products import ProductRepository
from ..schemas.orders import OrderIn, OrderOut
from ..services.orders import UnknownProduct, place_order
from .deps import order_repo, product_repo

router = APIRouter(prefix="/orders", tags=["orders"])


@router.post("", response_model=OrderOut, status_code=status.HTTP_201_CREATED)
def create_order(
    body: OrderIn,
    products: Annotated[ProductRepository, Depends(product_repo)],
    orders: Annotated[OrderRepository, Depends(order_repo)],
):
    try:
        return place_order(products, orders, body.product_id, body.quantity)
    except UnknownProduct:
        raise HTTPException(422, "Unknown product") from None


@router.get("/{order_id}", response_model=OrderOut)
def get_order(order_id: int, orders: Annotated[OrderRepository, Depends(order_repo)]):
    order = orders.get(order_id)
    if order is None:
        raise HTTPException(404, "Order not found")
    return order
py
from __future__ import annotations

from ..models.orders import Order
from ..repositories.orders import OrderRepository
from ..repositories.products import ProductRepository


class UnknownProduct(Exception):
    pass


def place_order(products: ProductRepository, orders: OrderRepository, product_id: int, quantity: int) -> Order:
    """Business rule lives here, not in the router: price is looked up, never taken from the client."""
    product = products.get(product_id)
    if product is None:
        raise UnknownProduct(product_id)
    return orders.add(product_id, quantity, product.price_cents * quantity)

By feature second: shop/ with one package per business capability (catalog/, orders/), a core/ package for what every feature needs, and internal/ for a router shared with other projects. The settings:

py
from __future__ import annotations

import os
from functools import lru_cache
from typing import Literal

from pydantic import Field, SecretStr, model_validator
from pydantic_settings import BaseSettings, SettingsConfigDict

Environment = Literal["dev", "test", "staging", "prod"]


class Settings(BaseSettings):
    """Typed settings: every value arrives converted and validated, or the process refuses to start."""

    model_config = SettingsConfigDict(
        env_prefix="SHOP_",  # SHOP_DATABASE_URL -> database_url (case-insensitive by default)
        env_file=".env",  # relative to the current working directory, not to this file
        env_file_encoding="utf-8",
        extra="forbid",  # the default: a typo in .env is an error, not a silently ignored line
    )

    app_name: str = "Shop API"
    environment: Environment = "dev"
    database_url: str = "sqlite:///:memory:"
    seed_demo_data: bool = True
    docs_enabled: bool = True
    api_prefix: str = "/api"
    cors_origins: list[str] = []  # JSON in the environment: SHOP_CORS_ORIGINS='["https://shop.example"]'
    admin_token: SecretStr = SecretStr("change-me")  # repr shows '**********'
    payments_base_url: str = "https://payments.invalid"
    http_timeout_s: float = Field(default=2.0, gt=0, le=30)

    @model_validator(mode="after")
    def no_default_secrets_outside_dev(self) -> "Settings":
        """Refuse to start staging/prod with the public placeholder token: fail at startup, not at the first attack."""
        if self.environment in ("staging", "prod") and self.admin_token.get_secret_value() == "change-me":
            raise ValueError(f"SHOP_ADMIN_TOKEN must be set in {self.environment} (the default 'change-me' is public)")
        return self


def load_settings(environment: str | None = None) -> Settings:
    """Per-environment config: .env, then .env.<environment> on top; real env vars beat both.

    Secrets come from files (one file per value, file name = field name) when SHOP_SECRETS_DIR is set,
    e.g. /run/secrets in Docker or a mounted Kubernetes Secret volume.
    """
    env = environment or os.environ.get("SHOP_ENVIRONMENT", "dev")
    secrets_dir = os.environ.get("SHOP_SECRETS_DIR")  # read before Settings exists, so plain os.environ
    return Settings(_env_file=(".env", f".env.{env}"), _secrets_dir=secrets_dir)


@lru_cache
def get_settings() -> Settings:
    """The Settings dependency: built once per process, overridable in tests."""
    return load_settings()

The lifespan, which opens the database and the outbound HTTP client once per process:

py
from __future__ import annotations

from contextlib import asynccontextmanager
from typing import AsyncIterator

import httpx
from fastapi import FastAPI

from .config import Settings
from .db import Database


@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
    """Startup before `yield`, shutdown after it. Runs once per worker process, not per request."""
    settings: Settings = app.state.settings
    db = Database(settings.database_url)
    db.connect(seed=settings.seed_demo_data)
    http = httpx.AsyncClient(base_url=settings.payments_base_url, timeout=settings.http_timeout_s)
    app.state.db = db  # reached from handlers as request.app.state.db
    app.state.http = http
    app.state.events.append("startup")
    try:
        yield
    finally:  # runs on SIGTERM/SIGINT, and when `with TestClient(app)` exits
        await http.aclose()
        db.close()
        app.state.events.append("shutdown")
py
from __future__ import annotations

import secrets
from typing import Annotated

from fastapi import Depends, Header, HTTPException, Request, status

from .config import Settings, get_settings
from .db import Database

SettingsDep = Annotated[Settings, Depends(get_settings)]


def get_db(request: Request) -> Database:
    return request.app.state.db


DbDep = Annotated[Database, Depends(get_db)]


def require_admin(settings: SettingsDep, x_admin_token: Annotated[str | None, Header()] = None) -> None:
    """Router-level dependency for the admin router: runs before every admin path operation."""
    expected = settings.admin_token.get_secret_value()
    if x_admin_token is None or not secrets.compare_digest(x_admin_token, expected):
        raise HTTPException(status.HTTP_403_FORBIDDEN, "Admin token required")

The catalog feature: a router with a prefix, a tag, shared 404 docs and its own lifespan; a repository that owns the SQL; a service that is the feature's public surface.

py
from __future__ import annotations

from contextlib import asynccontextmanager
from typing import Annotated, AsyncIterator

from fastapi import APIRouter, Depends, FastAPI, HTTPException, status

from shop.core.deps import DbDep, require_admin

from .repository import ProductRepository
from .schemas import ProductIn, ProductOut


@asynccontextmanager
async def catalog_lifespan(app: FastAPI) -> AsyncIterator[None]:
    """A router-level lifespan: merged into the app's by include_router, runs inside the app's lifespan."""
    app.state.featured_ids = [p.id for p in ProductRepository(app.state.db).list(featured_only=True)]
    app.state.events.append("catalog:startup")
    yield
    app.state.events.append("catalog:shutdown")


router = APIRouter(
    prefix="/products",
    tags=["catalog"],
    responses={404: {"description": "Product not found"}},  # documented on every route of this router
    lifespan=catalog_lifespan,
)


def repo(db: DbDep) -> ProductRepository:
    return ProductRepository(db)


Repo = Annotated[ProductRepository, Depends(repo)]


@router.get("", response_model=list[ProductOut])
def list_products(repo: Repo):
    return repo.list()


@router.get("/featured", response_model=list[ProductOut])  # literal before {product_id}
def list_featured_products(repo: Repo):
    return repo.list(featured_only=True)


@router.get("/{product_id}", response_model=ProductOut)
def get_product(product_id: int, repo: Repo):
    product = repo.get(product_id)
    if product is None:
        raise HTTPException(status.HTTP_404_NOT_FOUND, "Product not found")
    return product


@router.post(
    "",
    response_model=ProductOut,
    status_code=status.HTTP_201_CREATED,
    dependencies=[Depends(require_admin)],  # one route guarded; the admin router guards all of its routes
    responses={403: {"description": "Admin token required"}},
)
def create_product(body: ProductIn, repo: Repo):
    return repo.add(body.sku, body.name, body.price_cents)
py
from __future__ import annotations

from shop.core.db import Database

from .models import Product

COLUMNS = "id, sku, name, price_cents, featured"


class ProductRepository:
    def __init__(self, db: Database) -> None:
        self.db = db

    def list(self, featured_only: bool = False) -> list[Product]:
        sql = f"SELECT {COLUMNS} FROM products" + (" WHERE featured = 1" if featured_only else "") + " ORDER BY id"
        with self.db.lock:
            return [Product(**dict(r)) for r in self.db.conn.execute(sql).fetchall()]

    def get(self, product_id: int) -> Product | None:
        with self.db.lock:
            row = self.db.conn.execute(f"SELECT {COLUMNS} FROM products WHERE id = ?", (product_id,)).fetchone()
        return Product(**dict(row)) if row else None

    def add(self, sku: str, name: str, price_cents: int) -> Product:
        with self.db.lock:
            cur = self.db.conn.execute(
                "INSERT INTO products (sku, name, price_cents) VALUES (?, ?, ?)", (sku, name, price_cents)
            )
            self.db.conn.commit()
        return Product(cur.lastrowid, sku, name, price_cents, False)
py
"""The catalog's public surface for other features. orders imports this module, never catalog.router."""
from __future__ import annotations

from shop.core.db import Database

from .models import Product
from .repository import ProductRepository


def find_product(db: Database, product_id: int) -> Product | None:
    return ProductRepository(db).get(product_id)

The orders feature, which may use the catalog only through catalog.service:

py
from __future__ import annotations

from shop.catalog.service import find_product  # across features: absolute import of the public surface
from shop.core.db import Database

from .models import Order
from .repository import OrderRepository  # inside the feature: relative import


class UnknownProduct(Exception):
    """Domain error; the router maps it to HTTP. The service knows nothing about status codes."""


def place_order(db: Database, product_id: int, quantity: int) -> Order:
    product = find_product(db, product_id)
    if product is None:
        raise UnknownProduct(product_id)
    return OrderRepository(db).add(product_id, quantity, product.price_cents * quantity)
py
from __future__ import annotations

from fastapi import APIRouter, HTTPException, status

from shop.core.deps import DbDep

from .repository import OrderRepository
from .schemas import OrderIn, OrderOut
from .service import UnknownProduct, place_order

router = APIRouter(prefix="/orders", tags=["orders"], responses={404: {"description": "Order not found"}})


@router.post("", response_model=OrderOut, status_code=status.HTTP_201_CREATED)
def create_order(body: OrderIn, db: DbDep):
    try:
        return place_order(db, body.product_id, body.quantity)
    except UnknownProduct:
        raise HTTPException(status.HTTP_422_UNPROCESSABLE_CONTENT, "Unknown product") from None


@router.get("/{order_id}", response_model=OrderOut)
def get_order(order_id: int, db: DbDep):
    order = OrderRepository(db).get(order_id)
    if order is None:
        raise HTTPException(status.HTTP_404_NOT_FOUND, "Order not found")
    return order

A router shared between projects, configured entirely by whoever includes it:

py
"""A router shared between projects: no prefix, no auth, no tags of its own.

The including app decides all of that in include_router(), so the file stays reusable as is.
"""
from __future__ import annotations

from fastapi import APIRouter, Request

router = APIRouter()


@router.get("/stats")
def stats(request: Request):
    db = request.app.state.db
    with db.lock:
        (orders,) = db.conn.execute("SELECT COUNT(*) FROM orders").fetchone()
    return {"orders": orders, "lifespan_events": request.app.state.events}

The router tree (v1 with catalog, orders and the hidden admin router; v2 with the new catalog contract):

py
from __future__ import annotations

from fastapi import APIRouter, Depends

from shop.catalog import router as catalog
from shop.catalog import router_v2 as catalog_v2
from shop.core.deps import require_admin
from shop.internal import admin
from shop.orders import router as orders


def build_api_router() -> APIRouter:
    """The route tree under the API prefix. Built in a function so every create_app() gets a fresh tree.

    FastAPI 0.128.8 copies routes at include time, so children are included into v1/v2 BEFORE
    v1/v2 are included into the app (0.137.0+ keeps the routers live and the order stops mattering).
    """
    v1 = APIRouter(prefix="/v1")
    v1.include_router(catalog.router)
    v1.include_router(orders.router)
    v1.include_router(
        admin.router,
        prefix="/admin",
        tags=["admin"],
        dependencies=[Depends(require_admin)],  # every admin route, without editing admin.py
        responses={403: {"description": "Admin token required"}},
        include_in_schema=False,  # hidden from /docs and /openapi.json; still reachable
    )

    v2 = APIRouter(prefix="/v2")
    v2.include_router(catalog_v2.router)

    api = APIRouter()
    api.include_router(v1)
    api.include_router(v2)
    return api

The app factory and the process entry point:

py
from __future__ import annotations

import time
import uuid
from pathlib import Path

from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.routing import APIRoute
from fastapi.staticfiles import StaticFiles

from shop.api import build_api_router
from shop.core.config import Settings, get_settings
from shop.core.lifespan import lifespan
from shop.core.router import router as meta_router
from shop.legacy import create_legacy_app

STATIC_DIR = Path(__file__).parent / "static"

TAGS_METADATA = [  # order here = order of the groups in /docs
    {"name": "catalog", "description": "Products, prices and the featured list."},
    {"name": "orders", "description": "Placing and reading orders. Prices come from the catalog."},
    {"name": "catalog-v2", "description": "v2 of the catalog: prices as money objects."},
    {"name": "meta", "description": "Version and environment."},
]


def unique_id(route: APIRoute) -> str:
    """operationId = '<first tag>-<function name>', e.g. 'catalog-get_product' -> SDK method getProduct."""
    return f"{route.tags[0]}-{route.name}" if route.tags else route.name


def create_app(settings: Settings | None = None) -> FastAPI:
    """App factory: build a fresh, fully wired app for this settings object (tests pass their own)."""
    settings = settings or get_settings()
    app = FastAPI(
        title=settings.app_name,
        version="1.0.0",
        lifespan=lifespan,
        openapi_tags=TAGS_METADATA,
        generate_unique_id_function=unique_id,
        openapi_url="/openapi.json" if settings.docs_enabled else None,  # None also removes /docs and /redoc
    )
    app.state.settings = settings
    app.state.events = []
    app.dependency_overrides[get_settings] = lambda: settings  # Depends(get_settings) sees the same object

    @app.middleware("http")
    async def request_id(request: Request, call_next):
        start = time.perf_counter()
        response = await call_next(request)
        response.headers["x-request-id"] = request.headers.get("x-request-id", uuid.uuid4().hex)
        response.headers["x-process-time-ms"] = f"{(time.perf_counter() - start) * 1000:.2f}"
        return response

    if settings.cors_origins:  # added last = outermost: CORS answers preflights before anything else runs
        app.add_middleware(CORSMiddleware, allow_origins=settings.cors_origins, allow_methods=["*"])

    app.include_router(build_api_router(), prefix=settings.api_prefix)  # /api/v1/..., /api/v2/...
    app.include_router(meta_router)  # /healthz (hidden), /version
    app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
    app.mount("/legacy", create_legacy_app())  # its own /legacy/docs and /legacy/openapi.json
    return app
py
"""The process entry point: `uvicorn shop.asgi:app` or `fastapi run` ([tool.fastapi] entrypoint).

Alternative without a module-level object: `uvicorn --factory shop.main:create_app`.
"""
from shop.main import create_app

app = create_app()

The tests mirror the package (tests/shop/catalog/, tests/shop/orders/, tests/shop/core/), with fixtures placed at the level that needs them:

py
"""Root conftest: fixtures every test folder can use. Folder conftests add their own on top."""
from __future__ import annotations

import pytest

from shop.core.config import Settings, get_settings


@pytest.fixture(autouse=True)
def clean_settings_cache(monkeypatch: pytest.MonkeyPatch):
    # No test may see the developer's SHOP_* variables or a cached Settings from another test.
    import os

    for key in [k for k in os.environ if k.startswith("SHOP_")]:
        monkeypatch.delenv(key)
    get_settings.cache_clear()
    yield
    get_settings.cache_clear()


@pytest.fixture()
def settings() -> Settings:
    # _env_file=None: ignore any .env in the working directory; values are explicit.
    return Settings(_env_file=None, environment="test", admin_token="test-admin", docs_enabled=True)
py
"""Fixtures for the feature package's tests: placed in tests/shop/, so tests/layered/ never sees them."""
from __future__ import annotations

from typing import Iterator

import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient

from shop.core.config import Settings
from shop.main import create_app


@pytest.fixture()
def app(settings: Settings) -> FastAPI:
    return create_app(settings)  # a fresh app per test: no state leaks between tests


@pytest.fixture()
def client(app: FastAPI) -> Iterator[TestClient]:
    with TestClient(app) as c:  # `with` runs the lifespan
        yield c


@pytest.fixture()
def admin_headers(settings: Settings) -> dict[str, str]:
    return {"x-admin-token": settings.admin_token.get_secret_value()}
py
"""What the app factory wires: OpenAPI organisation, hidden routes, mounts, static files, middleware."""
from __future__ import annotations

from fastapi.testclient import TestClient

from shop.main import create_app


def test_tags_metadata_and_operation_ids(app):
    schema = app.openapi()
    assert [t["name"] for t in schema["tags"]] == ["catalog", "orders", "catalog-v2", "meta"]
    ops = [op["operationId"] for path in schema["paths"].values() for op in path.values()]
    assert len(ops) == len(set(ops))  # unique across v1 and v2 although both functions are get_product
    assert {"catalog-get_product", "catalog-v2-get_product", "orders-create_order"} <= set(ops)


def test_router_responses_are_merged(app):
    get_op = app.openapi()["paths"]["/api/v1/products/{product_id}"]["get"]
    post_op = app.openapi()["paths"]["/api/v1/products"]["post"]
    assert "404" in get_op["responses"]  # from APIRouter(responses=...)
    assert {"201", "403", "404", "422"} <= set(post_op["responses"])  # router + route + defaults


def test_internal_routes_are_hidden_but_guarded(client, admin_headers):
    paths = client.get("/openapi.json").json()["paths"]
    assert not any(p.startswith("/api/v1/admin") for p in paths) and "/healthz" not in paths
    assert client.get("/api/v1/admin/stats").status_code == 403  # hidden is not protected; the dependency is
    assert client.get("/api/v1/admin/stats", headers=admin_headers).json()["orders"] == 0


def test_mounted_sub_application_is_independent(client):
    assert not any(p.startswith("/legacy") for p in client.get("/openapi.json").json()["paths"])
    assert "/report" in client.get("/legacy/openapi.json").json()["paths"]
    assert client.get("/legacy/docs").status_code == 200
    assert client.get("/legacy/report").json() == {"lifespan_ran": False, "root_path": "/legacy"}


def test_static_mount_and_middleware(client):
    r = client.get("/static/robots.txt")
    assert r.status_code == 200 and "Disallow: /api/" in r.text
    assert "x-request-id" in client.get("/nope").headers  # middleware wraps 404s too
    assert client.get("/version", headers={"x-request-id": "abc"}).headers["x-request-id"] == "abc"


def test_docs_can_be_switched_off(settings):
    app = create_app(settings.model_copy(update={"docs_enabled": False}))
    with TestClient(app) as client:
        assert client.get("/openapi.json").status_code == 404
        assert client.get("/docs").status_code == 404
        assert client.get("/version").json() == {"app": "Shop API", "environment": "test"}


def test_cors_is_outermost_when_enabled(settings):
    app = create_app(settings.model_copy(update={"cors_origins": ["https://shop.example"]}))
    with TestClient(app) as client:
        r = client.options(
            "/api/v1/products",
            headers={"Origin": "https://shop.example", "Access-Control-Request-Method": "GET"},
        )
    assert r.status_code == 200 and r.headers["access-control-allow-origin"] == "https://shop.example"
    assert "x-request-id" not in r.headers  # the preflight never reached the inner middleware
py
"""Where a value comes from: init kwargs > environment > .env files (later wins) > secrets dir > default."""
from __future__ import annotations

import pytest
from pydantic import ValidationError

from shop.core.config import Settings, get_settings, load_settings


def test_defaults_and_types():
    s = Settings(_env_file=None)
    assert s.environment == "dev" and s.http_timeout_s == 2.0 and s.cors_origins == []
    assert repr(s.admin_token) == "SecretStr('**********')"


def test_environment_variables_are_converted(monkeypatch):
    monkeypatch.setenv("SHOP_HTTP_TIMEOUT_S", "5")
    monkeypatch.setenv("SHOP_DOCS_ENABLED", "false")
    monkeypatch.setenv("SHOP_CORS_ORIGINS", '["https://shop.example"]')
    s = Settings(_env_file=None)
    assert s.http_timeout_s == 5.0 and s.docs_enabled is False and s.cors_origins == ["https://shop.example"]


def test_invalid_value_fails_at_startup(monkeypatch):
    monkeypatch.setenv("SHOP_ENVIRONMENT", "production")  # not one of dev/test/staging/prod
    with pytest.raises(ValidationError) as exc:
        Settings(_env_file=None)
    assert exc.value.errors()[0]["type"] == "literal_error"


def test_priority_env_over_dotenv_over_secrets(tmp_path, monkeypatch):
    monkeypatch.chdir(tmp_path)  # env_file is resolved against the working directory
    (tmp_path / ".env").write_text("SHOP_APP_NAME=from-dotenv\nSHOP_ADMIN_TOKEN=from-dotenv\n")
    secrets = tmp_path / "secrets"
    secrets.mkdir()
    (secrets / "shop_admin_token").write_text("from-secret-file")  # file name = prefix + field name
    (secrets / "shop_app_name").write_text("from-secret-file")
    (secrets / "shop_payments_base_url").write_text("https://payments.example")

    monkeypatch.setenv("SHOP_APP_NAME", "from-env")
    s = Settings(_secrets_dir=str(secrets))
    assert s.app_name == "from-env"  # real environment beats .env
    assert s.admin_token.get_secret_value() == "from-dotenv"  # .env beats the secrets dir
    assert s.payments_base_url == "https://payments.example"  # secrets dir beats the default
    assert Settings(_secrets_dir=str(secrets), app_name="from-init").app_name == "from-init"  # init beats all


def test_per_environment_file_overrides_base(tmp_path, monkeypatch):
    monkeypatch.chdir(tmp_path)
    (tmp_path / ".env").write_text("SHOP_APP_NAME=base\nSHOP_DOCS_ENABLED=true\n")
    (tmp_path / ".env.prod").write_text("SHOP_DOCS_ENABLED=false\n")
    prod = load_settings("prod")
    assert prod.app_name == "base" and prod.docs_enabled is False
    assert load_settings("dev").docs_enabled is True  # no .env.dev: only the base file


def test_typo_in_dotenv_is_an_error(tmp_path, monkeypatch):
    monkeypatch.chdir(tmp_path)
    (tmp_path / ".env").write_text("SHOP_DATABSE_URL=sqlite:///typo.db\n")
    with pytest.raises(ValidationError) as exc:
        Settings()
    assert exc.value.errors()[0]["type"] == "extra_forbidden"


def test_get_settings_is_cached_until_cleared(monkeypatch):
    monkeypatch.chdir("/")  # no .env here
    first = get_settings()
    monkeypatch.setenv("SHOP_APP_NAME", "changed")
    assert get_settings() is first  # lru_cache: read once per process
    get_settings.cache_clear()
    assert get_settings().app_name == "changed"


@pytest.mark.parametrize("environment", ["staging", "prod"])
def test_default_admin_token_is_refused_outside_dev(monkeypatch, environment):
    monkeypatch.setenv("SHOP_ENVIRONMENT", environment)
    with pytest.raises(ValidationError, match="SHOP_ADMIN_TOKEN must be set"):
        Settings(_env_file=None)
    monkeypatch.setenv("SHOP_ADMIN_TOKEN", "a-real-token")
    assert Settings(_env_file=None).environment == environment
py
from __future__ import annotations

from fastapi.testclient import TestClient

from shop.main import create_app


def test_lifespan_runs_only_inside_with(settings):
    app = create_app(settings)
    TestClient(app)  # no `with`: no startup
    assert app.state.events == []
    with TestClient(app) as client:
        assert app.state.events == ["startup", "catalog:startup"]  # app lifespan first, router lifespan inside it
        assert client.get("/healthz").json() == {"status": "ok"}
        assert app.state.featured_ids == [2, 3]
    assert app.state.events == ["startup", "catalog:startup", "catalog:shutdown", "shutdown"]
    assert app.state.db.conn is None and app.state.http.is_closed


def test_each_app_has_its_own_state(settings):
    a, b = create_app(settings), create_app(settings)
    with TestClient(a), TestClient(b):
        assert a.state.db is not b.state.db

The router rules, each as a small test on the pinned FastAPI:

py
"""APIRouter rules, each pinned down on the pinned FastAPI (0.128.8)."""
from __future__ import annotations

import warnings

import pytest
from fastapi import APIRouter, Depends, FastAPI
from fastapi.responses import HTMLResponse
from fastapi.testclient import TestClient


def test_routes_added_after_include_are_missing_on_0_128():
    router = APIRouter()
    app = FastAPI()
    app.include_router(router)  # 0.128.8 copies the routes that exist *now*

    @router.get("/late")
    def late():
        return {"ok": True}

    assert TestClient(app).get("/late").status_code == 404  # 0.137.0+: 200 (routers stay live)


def test_nested_router_must_be_complete_before_it_is_included():
    parent, child = APIRouter(prefix="/v1"), APIRouter(prefix="/items")
    app = FastAPI()
    parent.include_router(child)  # child is still empty: nothing is copied

    @child.get("")
    def list_items():
        return []

    app.include_router(parent)
    assert TestClient(app).get("/v1/items").status_code == 404


def test_route_order_across_routers():
    by_id, me = APIRouter(prefix="/users"), APIRouter(prefix="/users")

    @by_id.get("/{user_id}")
    def get_user(user_id: int):
        return {"id": user_id}

    @me.get("/me")
    def get_me():
        return {"id": "me"}

    wrong, right = FastAPI(), FastAPI()
    wrong.include_router(by_id)
    wrong.include_router(me)
    right.include_router(me)
    right.include_router(by_id)
    assert TestClient(wrong).get("/users/me").status_code == 422  # {user_id} matched first, int parsing failed
    assert TestClient(right).get("/users/me").json() == {"id": "me"}


def test_path_conflict_first_router_wins_silently():
    a, b = APIRouter(), APIRouter()

    @a.get("/ping")
    def ping_a():
        return "a"

    @b.get("/ping")
    def ping_b():
        return "b"

    app = FastAPI()
    app.include_router(a)
    app.include_router(b)  # no error, no warning at include time
    assert TestClient(app).get("/ping").json() == "a"


def test_prefix_rules():
    with pytest.raises(AssertionError, match="must not end with '/'"):
        APIRouter(prefix="/items/")
    with pytest.raises(AssertionError, match="must start with '/'"):
        FastAPI().include_router(APIRouter(), prefix="items")
    r = APIRouter()
    with pytest.raises(AssertionError, match="Cannot include the same APIRouter instance into itself"):
        r.include_router(r)


def _status_router() -> APIRouter:
    r = APIRouter()

    @r.get("/status")
    def status_():
        return "up"

    return r


def test_same_router_under_two_prefixes():
    app = FastAPI()
    r = _status_router()
    app.include_router(r, prefix="/api/v1")
    app.include_router(r, prefix="/api/latest")
    client = TestClient(app)
    assert client.get("/api/v1/status").json() == client.get("/api/latest/status").json() == "up"
    with warnings.catch_warnings(record=True) as caught:
        warnings.simplefilter("always")
        ids = [op["get"]["operationId"] for op in app.openapi()["paths"].values()]
    assert ids == ["status__api_v1_status_get", "status__api_latest_status_get"]  # default id contains the path
    assert not caught


def test_function_name_ids_collide_when_a_router_is_mounted_twice():
    app = FastAPI(generate_unique_id_function=lambda route: route.name)
    r = _status_router()
    app.include_router(r, prefix="/api/v1")
    app.include_router(r, prefix="/api/latest")
    with pytest.warns(UserWarning, match="Duplicate Operation ID status_"):
        app.openapi()


def test_duplicate_operation_id_warns_when_schema_is_built():
    r = APIRouter()

    @r.get("/a", operation_id="read")
    def read_a():
        return 1

    @r.get("/b", operation_id="read")
    def read_b():
        return 2

    app = FastAPI()
    app.include_router(r)
    with pytest.warns(UserWarning, match="Duplicate Operation ID read for function read_b"):
        app.openapi()


def test_dependency_order_router_then_decorator_then_parameters():
    calls: list[str] = []

    def app_dep():
        calls.append("app")

    def include_dep():
        calls.append("include_router")

    def router_dep():
        calls.append("APIRouter")

    def decorator_dep():
        calls.append("decorator")

    def param_dep():
        calls.append("parameter")
        return 1

    r = APIRouter(dependencies=[Depends(router_dep)])

    @r.get("/x", dependencies=[Depends(decorator_dep)])
    def x(value: int = Depends(param_dep)):
        return value

    app = FastAPI(dependencies=[Depends(app_dep)])
    app.include_router(r, dependencies=[Depends(include_dep)])
    TestClient(app).get("/x")
    assert calls == ["app", "include_router", "APIRouter", "decorator", "parameter"]


def test_router_default_response_class_and_include_in_schema():
    pages = APIRouter(default_response_class=HTMLResponse)

    @pages.get("/hello")
    def hello():
        return "<h1>hello</h1>"

    app = FastAPI()
    app.include_router(pages, include_in_schema=False)
    r = TestClient(app).get("/hello")
    assert r.headers["content-type"].startswith("text/html") and r.text == "<h1>hello</h1>"
    assert "/hello" not in app.openapi()["paths"]


def test_default_operation_ids_can_collide_after_sanitising():
    # generate_unique_id: f"{name}{path_format}", every non-word character -> "_", then "_{method}".
    dash, underscore = APIRouter(), APIRouter()

    @dash.get("/a-b")
    def read():
        return "dash"

    @underscore.get("/a_b")
    def read():  # noqa: F811  same function name in another module is common
        return "underscore"

    app = FastAPI()
    app.include_router(dash)
    app.include_router(underscore)
    with pytest.warns(UserWarning, match="Duplicate Operation ID read_a_b_get"):
        app.openapi()


def test_included_router_redirect_slashes_is_not_transferred():
    r = APIRouter(redirect_slashes=False)

    @r.get("/items/")
    def items():
        return []

    app = FastAPI()  # the app's router (redirect_slashes=True) decides, not r
    app.include_router(r)
    resp = TestClient(app).get("/items", follow_redirects=False)
    assert resp.status_code == 307 and resp.headers["location"].endswith("/items/")
    strict = FastAPI(redirect_slashes=False)
    strict.include_router(r)
    assert TestClient(strict).get("/items", follow_redirects=False).status_code == 404

and the proof that layout is an internal decision:

py
"""Layout is an internal decision: both packages publish the same catalog/orders contract."""
from __future__ import annotations

from layered.main import create_app as create_layered
from shop.main import create_app as create_shop


def _operations(app) -> set[tuple[str, str]]:
    paths = app.openapi()["paths"]
    return {(method, path) for path, ops in paths.items() for method in ops if path.startswith(("/api/v1/products", "/api/v1/orders"))}


def test_same_paths_and_methods(settings):
    layered = _operations(create_layered())
    shop = _operations(create_shop(settings))
    assert layered == shop  # identical catalog/orders operation sets, nothing subtracted
    assert len(layered) == 6

The project file (see the version note at the top of the page):

toml
[project]
name = "routers-project-structure"
version = "0.1.0"
description = "Snippets for the APIRouter & Project Structure chapter: a flat app, a layer-based package and a feature-based package"
# The page targets Python 3.12+; the pins below are the newest releases that still install on 3.9,
# the only interpreter on the build machine. On 3.12+ you can move to the latest releases.
requires-python = ">=3.9"
dependencies = [
    "fastapi==0.128.8",
    "starlette==0.49.3",
    "pydantic==2.13.5",
    # BaseSettings lives in its own package since Pydantic v2; 2.12.0 dropped Python 3.9.
    "pydantic-settings==2.11.0",
    "uvicorn[standard]==0.39.0",
    # The outbound HTTP client the lifespan opens once per process.
    "httpx==0.28.1",
    # Lets Pydantic evaluate `str | None` annotations on Python 3.9; not needed on 3.10+.
    "eval-type-backport==0.4.0; python_version < '3.10'",
]

[project.optional-dependencies]
test = [
    "pytest==8.4.2",
]

[build-system]
requires = ["setuptools>=61"]
build-backend = "setuptools.build_meta"

[tool.setuptools.packages.find]
# Flat layout: the three import packages sit next to pyproject.toml (see the page for src/).
include = ["before*", "layered*", "shop*"]

[tool.setuptools.package-data]
shop = ["static/*"]

[tool.fastapi]
# `fastapi dev` / `fastapi run` import this object; shop/asgi.py builds it with create_app().
entrypoint = "shop.asgi:app"

[tool.pytest.ini_options]
testpaths = ["tests"]
# importlib mode: test files in different folders may share a base name (pytest's recommendation for new projects).
addopts = "-q -p no:cacheprovider --import-mode=importlib"
pythonpath = ["."]

and the committed example environment file, .env.example (copied to the git-ignored .env for local work):

ini
# Copy to .env for local development. Real environment variables always win over this file.
SHOP_ENVIRONMENT=dev
SHOP_DATABASE_URL=sqlite:///./shop-dev.db
SHOP_DOCS_ENABLED=true
SHOP_CORS_ORIGINS=["http://localhost:5173"]
# Secrets do not belong here in staging/production: mount them as files under SHOP_SECRETS_DIR.
SHOP_ADMIN_TOKEN=dev-admin-token

The Python angle ​

Everything in this chapter is ordinary Python, which is why it is worth knowing which Python feature carries each piece. Modules and packages: a directory with __init__.py is a regular package, and "When a regular package is imported, this __init__.py file is implicitly executed" (language reference); every from shop.catalog import router runs the package's __init__.py first, so keep those files empty or nearly so. Import-time side effects: a decorator such as @router.get runs when the module is imported, so importing a router module is what registers its routes, and anything else at module level (a connection, an environment read) also runs then; the factory exists to move the second kind of work out of import time. contextlib.asynccontextmanager: the lifespan is a generator function with one yield, turned into an async context manager; code before yield is startup, code after is shutdown, and a try/finally makes shutdown run even when startup of a nested lifespan fails. functools.lru_cache: caches a function's result per argument combination; a zero-argument get_settings() therefore behaves like a lazily created global that can be reset with get_settings.cache_clear(). typing.Annotated: SettingsDep = Annotated[Settings, Depends(get_settings)] defines the dependency once and keeps the real type for editors and mypy. On Python 3.11+ you may use typing.Self and StrEnum; the snippets avoid them to run on 3.9.

The concept catalogue ​

include_router builds one route table; mount attaches a separate appapp = create_app(settings)FastAPI: lifespan, middleware, docsapi routerprefix="/api" (settings)meta router/version, /healthzmount /staticStaticFilesmount /legacyown docs, no lifespanv1: prefix="/v1"v2: prefix="/v2"catalog/productstag, 404, lifespanorders/orderstag, 404admin (shared file)prefix + Depends atinclude, hiddencatalog v2/productstag catalog-v2Final paths (prefixes concatenate):/api + /v1 + /products + /{product_id} = /api/v1/products/{product_id} operationId catalog-get_product/api + /v2 + /products + /{product_id} = /api/v2/products/{product_id} operationId catalog-v2-get_product0.128.8 copies routes at each include_router call: build children first. 0.137.0+ keeps routers live.

Breaking up logic across files: modules, packages and __init__.py Must-know ​

In plain words: Python finds code by module name. A file shop/catalog/router.py is the module shop.catalog.router because shop/ and shop/catalog/ are packages (directories Python treats as a namespace). Splitting a FastAPI app into files is therefore two steps: put the code in modules inside a package, and make sure the directory that contains the package is on the import path when Uvicorn or pytest starts.

Common misunderstanding: "__init__.py is a leftover from Python 2." Without it a directory can still be imported as a namespace package (PEP 420, Python 3.3), but then two directories with the same name on the path merge silently, and the FastAPI tutorial's layout puts one in every directory: "There are several __init__.py files: one in each directory or subdirectory. This is what allows importing code from one file into another." The Python tutorial gives the reason: the files "are required to make Python treat directories containing the file as packages (unless using a namespace package, a relatively advanced feature). This prevents directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path."

Definition: The FastAPI tutorial's walk-through: "The app directory contains everything. And it has an empty file app/__init__.py, so it is a 'Python package' (a collection of 'Python modules'): app"; "There's a subdirectory app/routers/ with another file __init__.py, so it's a 'Python subpackage': app.routers"; "The file app/routers/items.py is inside a package, app/routers/, so, it's a submodule: app.routers.items."

     file on disk                         module name             found because
1    shop/__init__.py                     shop                    the project root is on sys.path (pytest pythonpath = ["."])
2    shop/main.py                         shop.main               shop is a package
3    shop/catalog/__init__.py             shop.catalog            subpackage
4    shop/catalog/router.py               shop.catalog.router     submodule; importing it runs @router.get(...) -> routes registered
5    uvicorn shop.asgi:app                imports shop -> shop.asgi -> shop.main -> every router module
6    pytest (rootdir = project)           tests/shop/... import shop.main the same way

Real scenario: a 1,200-line main.py split into app/routers/products.py and app/routers/orders.py; a script under scripts/ that fails with ModuleNotFoundError: No module named 'shop' because it was started from inside scripts/; a CI job that passes locally only because the developer's working directory happened to be the project root.

ThingMeaningWhen it bites
ModuleOne .py file, named by its dotted pathTwo modules with the same name on the path
Regular packageDirectory with __init__.py (executed on import)Heavy code in __init__.py runs on every import
Namespace packageDirectory without __init__.py (PEP 420)Silent merging; some tools do not discover it
sys.pathWhere imports are searched; the script's directory or the CWD comes firstRunning from a different directory
Import string"shop.asgi:app" for Uvicorn, entrypoint for fastapiWrong CWD → ModuleNotFoundError
pythonpath = ["."]pytest adds the project root to sys.pathWithout it (and without an install) tests cannot import the package

Fix / how to use it: one top-level package per app (shop/), an empty __init__.py in each directory, start every process from the project root (or install the project), and point Uvicorn and [tool.fastapi] entrypoint at an import string.

The APIRouter class Must-know ​

In plain words: router = APIRouter() gives you an object with the same decorators as the app (@router.get, @router.post …). You declare a feature's path operations on it in the feature's own module. Nothing is served until the router is included somewhere.

Common misunderstanding: "A router needs its own FastAPI() to be tested." A router has no server-facing behaviour of its own; tests include it in a throwaway FastAPI() (as in test_router_semantics.py) or go through the real app factory. Another one: "the variable must be called router": the tutorial says "the variable is called router, but you can name it however you want", and the snippet imports the module (from shop.catalog import router as catalog) so that two modules' router variables do not overwrite each other, as the tutorial warns: "the router from users would overwrite the one from items and we wouldn't be able to use them at the same time."

Definition: The tutorial: "You can think of APIRouter as a 'mini FastAPI' class. All the same options are supported. All the same parameters, responses, dependencies, tags, etc." The 0.128.8 constructor takes prefix, tags, dependencies, default_response_class, responses, callbacks, routes, redirect_slashes, default, dependency_overrides_provider, route_class, on_startup, on_shutdown, lifespan, deprecated, include_in_schema and generate_unique_id_function (read from fastapi/routing.py). APIRouter subclasses Starlette's Router.

     shop/catalog/router.py (import time)                      what exists afterwards
1    router = APIRouter(prefix="/products", tags=["catalog"],   router.prefix, router.tags, router.responses,
         responses={404: ...}, lifespan=catalog_lifespan)       router.lifespan_context
2    @router.get("")            def list_products(...)          APIRoute path="/products"  (prefix already applied)
3    @router.get("/featured")   def list_featured_products(...) APIRoute path="/products/featured"
4    @router.get("/{product_id}") def get_product(...)          APIRoute path="/products/{product_id}"
5    @router.post("", dependencies=[Depends(require_admin)])    APIRoute path="/products" POST
6    (nothing is served yet: no app has included the router)

Real scenario: catalog/router.py, orders/router.py and users/router.py, each owned by one team; a third-party package that ships a ready APIRouter (an admin panel, a health router, an auth router) which the app includes with its own prefix and dependencies.

ParameterApplies toTypical value
prefixEvery route path"/products" (must start with /, must not end with /)
tagsEvery route's OpenAPI tags["catalog"]
dependenciesEvery route, run before it[Depends(require_admin)]
responsesEvery route's documented responses{404: {"description": "Product not found"}}
default_response_classEvery route without its own response_classHTMLResponse for a pages router
deprecated / include_in_schemaEvery routeOld router; internal router
lifespanMerged into the including app's lifespanWarm a cache, start a consumer
generate_unique_id_functionoperationIds of the router's routesPer-router naming scheme
route_classThe APIRoute subclass for its routesCustom timing or logging routes

Fix / how to use it: one router per feature module, configured where the feature lives (prefix, tags, shared responses, the feature's dependencies), imported as a module rather than as a bare router name.

Including the APIRouters: include_router and nested routers Must-know ​

In plain words: app.include_router(catalog.router) takes every route of the router and adds it to the app, combining the path prefix, tags, dependencies and responses on the way. A router can include other routers (v1.include_router(catalog.router)), so you build a tree: app → api → v1 → catalog.

Common misunderstanding: "I can include the router first and add routes later." Not on FastAPI before 0.137.0. The 0.128.8 source loops over router.routes and calls self.add_api_route(prefix + route.path, …) for each one at that moment; routes added afterwards never reach the app. The snippet proves it: test_routes_added_after_include_are_missing_on_0_128 gets a 404, and the probe printed the app's routes as only /openapi.json, /docs, /docs/oauth2-redirect, /redoc. The same applies to nesting: parent.include_router(child) before child has routes gives a 404 for the child's paths. Since 0.137.0, "Including subrouter in mainrouter can be done before adding routes (path operations) to subrouter, because now the entire object is stored instead of copying the routes", and the current tutorial says "You can do this before or after including router in the FastAPI app." Code that must run on both: build the tree bottom-up, as build_api_router() does.

Definition: The tutorial: "With app.include_router() we can add each APIRouter to the main FastAPI application. It will include all the routes from that router as part of it." It also states the cost: "You don't have to worry about performance when including routers. This is designed to be lightweight and to avoid adding overhead to each request." The current docs add a 0.137.0+ technical detail: "Avoid directly mutating router.routes after including a router. FastAPI treats router inclusion as live … Treat router.routes as a lower-level route tree … and avoid relying on it as a flat list of final path operations."

     build_api_router() then create_app(), FastAPI 0.128.8
1    v1 = APIRouter(prefix="/v1")
2    v1.include_router(catalog.router)     -> v1 gets copies: /v1/products, /v1/products/featured, /v1/products/{product_id}, POST /v1/products
3    v1.include_router(orders.router)      -> /v1/orders, /v1/orders/{order_id}
4    v1.include_router(admin.router, prefix="/admin", dependencies=[...], include_in_schema=False) -> /v1/admin/stats
5    api.include_router(v1); api.include_router(v2)
6    app.include_router(api, prefix="/api")  -> /api/v1/products ... /api/v2/products/{product_id}
7    app.routes (real, registration order): docs routes, 8 v1 routes, 1 v2 route, /healthz, /version, Mount /static, Mount /legacy

Real scenario: an api_router that aggregates feature routers (the full-stack FastAPI template's app/api/main.py does exactly api_router.include_router(login.router), users.router, utils.router, items.router, then app.include_router(api_router, prefix=settings.API_V1_STR)); a development-only router included conditionally (the same template includes private.router only when FASTAPI_ENV == "development").

CallResultRule
app.include_router(r)r's routes added to the appCopies at call time (≤ 0.136)
app.include_router(r, prefix="/api")/api + r.prefix + pathPrefix rules below
parent.include_router(child)Child's routes copied into parentInclude children first (≤ 0.136)
app.include_router(r, prefix="/v1") and again with "/latest"Same routes under two pathsDistinct default operationIds (path is part of it)
r.include_router(r)AssertionError: Cannot include the same APIRouter instance into itself.Real message
Router with a "" route included without any prefixFastAPIError: Prefix and path cannot be both empty (path operation: root)Real message
@router.get after include_routerMissing (404) on 0.128.8; visible on 0.137.0+Version-dependent

Fix / how to use it: build the router tree in a function (build_api_router()), include leaves before branches, call it from the factory, and never mutate router.routes by hand.

Configuring the APIRouter with path prefix and tags Must-know ​

In plain words: prefix="/products" is written once and prepended to every route path of the router; tags=["catalog"] puts every route of the router in the "catalog" group of /docs (and in the CatalogService of a generated TypeScript client). Both can be set on the router itself or added when including it, and they stack.

Common misunderstanding: "The prefix may end with a slash." It may not: APIRouter(prefix="/items/") raises AssertionError: A path prefix must not end with '/', as the routes will start with '/', and include_router(r, prefix="items") raises AssertionError: A path prefix must start with '/' (both real). The tutorial: "As the path of each path operation has to start with /, … the prefix must not include a final /." A second one: "tags replace each other." They are concatenated: include tags first, then the route's own ("This last path operation will have the combination of tags: ["items", "custom"]").

Definition: In include_router (0.128.8), the new path is prefix + route.path and the tags are current_tags.extend(tags) followed by current_tags.extend(route.tags). A route with path "" on a router with a prefix serves exactly the prefix (@router.get("") + prefix="/products" → /products), which avoids the 307 redirect between /products and /products/.

     source of each piece                                   value
1    app.include_router(api, prefix=settings.api_prefix)    "/api"
2    api.include_router(v1)  ; v1 = APIRouter(prefix="/v1") "/v1"
3    v1.include_router(catalog.router)                      catalog.router.prefix = "/products", tags = ["catalog"]
4    @router.get("/{product_id}")                           "/{product_id}"
5    final path                                             /api/v1/products/{product_id}
6    final tags                                             ["catalog"]   (v1 and api add none)
7    final operationId (custom unique_id)                   "catalog-get_product"

Real scenario: the API prefix as a setting (api_prefix: str = "/api") so an internal deployment can serve under /internal/shop; an admin tag added at include time to a router shipped without tags; one tag per feature so the generated SDK has one service class per feature.

Whereprefixtags
APIRouter(...)Owned by the feature (recommended by 0.62.0 notes)The feature's docs group
include_router(..., prefix=, tags=)Decided by the includer: versions, third-party routersExtra group, e.g. admin
DecoratorNot available (the path is the path)Extra tag for one route
FastAPI(...)No app-wide prefix; use an outer router (include_router(api, prefix="/api")). The server's --root-path is not a routing prefix: it tells the app which prefix an external proxy strips, the app still serves its own pathsopenapi_tags sets order and descriptions

Fix / how to use it: the feature's own prefix and tag on its router; version and API prefixes on the routers that include it; a test that asserts the final paths and the tag list (test_tags_metadata_and_operation_ids).

Router dependencies and router responses Must-know ​

In plain words: dependencies=[Depends(require_admin)] on a router (or on include_router) runs require_admin before every route of that router, without the route function receiving anything. responses={404: {...}} adds that response to the docs of every route. Both remove repetition and make "this whole group needs a token" a single line that cannot be forgotten on a new route.

Common misunderstanding: "Hiding a router (include_in_schema=False) protects it." It only removes it from /openapi.json and /docs. The snippet's admin router is hidden and guarded; test_internal_routes_are_hidden_but_guarded asserts the hidden route still answers 403 without the token and 200 with it, and the real curl run printed 403 and then {"orders":0,"lifespan_events":["startup","catalog:startup"]}.

Definition: The tutorial: "we can add a list of dependencies that will be added to all the path operations in the router and will be executed/solved for each request made to them", and "The router dependencies are executed first, then the dependencies in the decorator, and then the normal parameter dependencies." The snippet measured the full chain, including app-level and include-level dependencies: ["app", "include_router", "APIRouter", "decorator", "parameter"] (test_dependency_order_router_then_decorator_then_parameters). For responses, include_router builds combined_responses = {**responses, **route.responses}: the route's own entry wins for the same status code.

     GET /api/v1/admin/stats   with x-admin-token: lab-token   (real run)
1    app dependencies (FastAPI(dependencies=[...]))     none in the shop app
2    include_router(admin.router, dependencies=[Depends(require_admin)])
3        require_admin(settings=get_settings(), x_admin_token="lab-token") -> compare_digest -> ok
4    admin.router dependencies                          none (the shared file stays generic)
5    decorator dependencies                             none
6    parameter dependencies                             request: Request (injected)
7    stats(request) -> {"orders": 0, "lifespan_events": [...]}   200
8    same request without the header: step 3 raises HTTPException(403, "Admin token required")

Real scenario: an internal router reused by several projects, each securing it differently (the tutorial's case: "other projects could use the same APIRouter with a different authentication method"); a "requires an authenticated user" dependency on every router except the public catalog; responses={401: ..., 403: ...} documented once for a protected router.

LevelSyntaxRuns for
AppFastAPI(dependencies=[Depends(f)])Every route of the app (global dependencies)
Includeapp.include_router(r, dependencies=[...])Every route of r, in this app only
RouterAPIRouter(dependencies=[...])Every route of the router, wherever it is included
Decorator@router.get(..., dependencies=[...])One route, value not passed
Parameterx: Annotated[T, Depends(f)]One route, value passed to the function

Fix / how to use it: authorisation for a group goes on the router or on include_router; the value-returning dependencies (current user, DB session) stay parameters; a test calls a protected route without credentials. Dependency mechanics in depth: Dependency Injection.

Router defaults: default_response_class, deprecated, include_in_schema Good to know ​

In plain words: A router can set defaults for its routes beyond prefix and tags: the response class (HTMLResponse for a router of server-rendered pages), deprecated=True for a whole old version, include_in_schema=False for internal endpoints.

Common misunderstanding: "include_in_schema=False on the router is overridden by True on a route." It is an AND: in 0.128.8 the final value is route.include_in_schema and self.include_in_schema and include_in_schema, so any False hides the route. deprecated is an OR (route.deprecated or deprecated or self.deprecated).

Definition: For the response class, include_router uses the first value set in the order route → router → include call → parent (get_value_or_default(route.response_class, router.default_response_class, default_response_class, self.default_response_class)). The 0.62.0 release notes: "default_response_class: updated to handle defaults in APIRouter and include_router."

     pages = APIRouter(default_response_class=HTMLResponse); app.include_router(pages, include_in_schema=False)
1    @pages.get("/hello") returns "<h1>hello</h1>"
2    response_class: route (unset) -> router HTMLResponse  -> chosen
3    GET /hello -> 200, content-type text/html; charset=utf-8, body <h1>hello</h1>   (real test)
4    include_in_schema: True and True and False -> False -> "/hello" not in openapi()["paths"]   (real test)

Real scenario: an /admin/ui router of HTML pages next to a JSON API; v1 marked deprecated=True in the docs once v2 ships; /healthz and /metrics hidden from client SDKs.

SettingCombination ruleUse
default_response_classFirst set: route, router, include, parentHTML or plain-text routers
deprecatedAny TrueOld version, sunset period
include_in_schemaAll must be TrueInternal, health, admin routes
redirect_slashesNot transferred by include_router on 0.128.8: the routes are copied, and the app's router setting (FastAPI(redirect_slashes=...)) decides (test_included_router_redirect_slashes_is_not_transferred: APIRouter(redirect_slashes=False) in a default app still answers /items with 307)Set it on FastAPI(...)
route_classPer routerCustom APIRoute subclasses

Fix / how to use it: set group-wide behaviour on the router once; keep per-route overrides for the exceptions; assert the schema effect in a test.

Route order across routers and path conflicts Must-know ​

In plain words: After inclusion there is one flat list of routes, in the order they were added. A request is matched against that list from the top and the first match wins. So the order in which you call include_router is part of your routing: a router with /users/{user_id} included before a router with /users/me makes /users/me unreachable.

Common misunderstanding: "Routers are matched by prefix first, then inside the router." Not on 0.128.8: the routes were copied into the parent, so there is no router-level step; the whole table is scanned in order. Duplicate paths across routers are not an error either: test_path_conflict_first_router_wins_silently registers GET /ping in two routers and the first one answers, with no exception and no warning at include time.

Definition: Starlette's routing docs: "Incoming paths are matched against each Route in order. In cases where more that one route could match an incoming path, you should take care to ensure that more specific routes are listed before general cases." The real failure across routers: GET /users/me → 422 {"type":"int_parsing","loc":["path","user_id"],"msg":"Input should be a valid integer, unable to parse string as an integer","input":"me"}.

     wrong.include_router(by_id); wrong.include_router(me)        right: me first
1    routes: GET /users/{user_id}, GET /users/me                  routes: GET /users/me, GET /users/{user_id}
2    GET /users/me -> /users/{user_id} matches (path only)         GET /users/me -> /users/me matches
3    user_id = "me" -> int parsing fails                           get_me() -> {"id": "me"}
4    422 int_parsing (real)                                        200 (real)

Real scenario: a users feature router and a separate me router (profile, settings) both under /users; a v2 router that redefines a v1 path by accident because both were given the same prefix; a catch-all /{slug} page router that must be included last.

SituationWhat happensFix
Literal path after a parameter path, same routerLiteral unreachable (422 or wrong handler)Declare literals first (/featured before /{product_id})
Same, across two routersSameInclude the literal router first, or merge them
Same method + path in two routersFirst wins, second silently deadA test that lists (method, path) pairs and checks uniqueness
Same path, different methodsBoth work (405 lists the first partial match)Fine
Catch-all route (/{path:path})Swallows everything after itInclude last; or app.frontend() (0.138.0+)

Fix / how to use it: keep each path family inside one router, include routers from specific to general, and keep a route-table test (the probe's printout of app.routes is a good template).

operationId uniqueness and generate_unique_id_function Important ​

In plain words: Every path operation has an operationId in the OpenAPI document, and client generators turn it into a method name. FastAPI's default is long and path-based (read_item_api_v1_items__item_id__get); a custom generate_unique_id_function gives short names (catalog-get_product → getProduct in the CatalogService). The ids must be unique across the whole app, including across routers and versions.

Common misunderstanding: "FastAPI refuses duplicate ids." It warns, and only when the schema is generated (first /openapi.json request or app.openapi()): real output UserWarning: Duplicate Operation ID read for function read_b at …/p1_routers.py. A name-only id scheme collides as soon as one router is included twice (/api/v1 and /api/latest) or two versions use the same function name (test_function_name_ids_collide_when_a_router_is_mounted_twice).

Definition: 0.128.8 generate_unique_id: operation_id = f"{route.name}{route.path_format}", non-word characters replaced by _, then _{method} appended. The "Generate Clients" docs: "OpenAPI requires that each operation ID is unique across all the path operations, so FastAPI uses the function name, the path, and the HTTP method/operation to generate that operation ID"; a custom function "takes an APIRoute and outputs a string", e.g. "using the first tag … and the path operation name (the function name)". The advanced docs warn for the function-name scheme: "you have to make sure each one of your path operation functions has a unique name. Even if they are in different modules (Python files)."

     route                                   default id                                shop unique_id
1    GET /api/v1/items/{item_id} read_item   read_item_api_v1_items__item_id__get       (not used in the shop)
2    GET /api/v1/products/{product_id}       get_product_api_v1_products__product_id__get   catalog-get_product
3    GET /api/v2/products/{product_id}       get_product_api_v2_products__product_id__get   catalog-v2-get_product (tag keeps it unique)
4    same router at /api/v1 and /api/latest  status__api_v1_status_get / status__api_latest_status_get   lambda r: r.name -> "status_" twice -> UserWarning
     real: row 1 default (probe p1), row 2 default (Before app test), rows 2-3 shop ids (curl), row 4 (tests); row 3 default is the formula

Real scenario: a TypeScript client generated with npx @hey-api/openapi-ts -i http://localhost:8000/openapi.json -o src/client (the command in the FastAPI docs) whose method names should not change when a path changes; a mobile team that pins the OpenAPI document and diffs operationIds in CI.

SchemeExampleUnique whenBreaks when
Default (name + path + method)get_product_api_v1_products__product_id__getUsually, not always: non-word characters become _, so read on /a-b and read on /a_b both give read_a_b_get (Duplicate Operation ID warning, real test)Path renames change every SDK method
route.nameget_productFunction names unique app-wideSame router twice; v1/v2 same names
f"{route.tags[0]}-{route.name}" (full-stack template, this snippet)catalog-get_productNames unique per first tagRoute without tags (handle it)
operation_id="..." per routegetProductYou check itCopy-paste

Fix / how to use it: do not rely on the default being unique (sanitising - and _ to the same character can collide, test_default_operation_ids_can_collide_after_sanitising); set a generate_unique_id_function (tag plus name, with a fallback for untagged routes) or an explicit operation_id, give versioned routers their own tag, and keep a test that all ids are unique (test_tags_metadata_and_operation_ids).

OpenAPI organisation: openapi_tags, tags_metadata and hiding internal routes Important ​

In plain words: FastAPI(openapi_tags=TAGS_METADATA) gives each docs group a description (Markdown allowed) and fixes the order of the groups. include_in_schema=False on a route, a router or an include call removes those routes from the document. Together they turn /docs from "every route in registration order" into a curated API reference.

Common misunderstanding: "Every tag must be described." The docs: "You don't have to add metadata for all the tags that you use." Undescribed tags still appear; described ones appear in the openapi_tags order. Another one: "A sub-application's routes appear in the main docs." They do not; the mounted app has its own /legacy/docs and /legacy/openapi.json (both real 200s).

Definition: The metadata docs: openapi_tags "takes a list containing one dictionary for each tag", each with name ("the same tag name you use in the tags parameter in your path operations and APIRouters"), description ("It can have Markdown and will be shown in the docs UI") and externalDocs. The snippet's real /openapi.json tag order: ['catalog', 'orders', 'catalog-v2', 'meta'].

     what /openapi.json contains (real run, shop app)
1    info: title "Shop API", version "1.0.0"
2    tags: catalog, orders, catalog-v2, meta       <- TAGS_METADATA order and descriptions
3    paths: /api/v1/products (get, post), /featured, /{product_id}, /api/v1/orders, /{order_id}, /api/v2/products/{product_id}, /version
4    absent: /api/v1/admin/stats (include_in_schema=False), /healthz (route flag), /static, /legacy (mounts)
5    operationIds: catalog-create_product, catalog-get_product, ..., orders-get_order   (8, unique)

Real scenario: a public API whose docs list "Catalog" before "Orders" with a link to a pricing guide; a service whose /healthz, /metrics and admin routes exist but are not part of the client contract; production with openapi_url=None (docs off) while CI still exports the schema from create_app(test_settings).

GoalToolNote
Group descriptions and orderFastAPI(openapi_tags=[...])Markdown in description
Hide one route@router.get(..., include_in_schema=False)Still served
Hide a whole routerinclude_router(r, include_in_schema=False)Still served
Turn docs offopenapi_url=None (also removes /docs and /redoc; real 404s)From settings, per environment
Separate docs for a separate appapp.mount("/legacy", sub_app)Own /legacy/docs
Mark a version as oldinclude_router(v1, deprecated=True)Docs strike it through

Fix / how to use it: describe every feature tag in one TAGS_METADATA list next to the factory, hide internal routes (and whole internal routers) at include time, drive openapi_url from settings, and export the schema in CI.

The app factory: create_app() Must-know ​

In plain words: Instead of a module-level app = FastAPI() that is built when the module is imported, write def create_app(settings=None) -> FastAPI that builds a complete app (settings, lifespan, middleware, routers, mounts) and returns it. The server calls it once per worker; each test calls it with its own settings and gets an independent app.

Common misunderstanding: "A factory is only for Flask." FastAPI does not require one, but the reasons are the same: settings chosen at build time, no shared module-level state between tests (test_each_app_has_its_own_state: two apps, two databases), and import of the package without side effects. Uvicorn supports it directly: uvicorn --factory shop.main:create_app (real run).

Definition: In the snippet, create_app() takes an optional Settings, falls back to get_settings(), stores it on app.state.settings, and registers app.dependency_overrides[get_settings] = lambda: settings so that every Depends(get_settings) in the app sees the same object the factory used. It then adds middleware, includes build_api_router() under settings.api_prefix, includes the meta router and mounts /static and /legacy.

     create_app(settings)                               why here
1    settings = settings or get_settings()              one source of truth, passed in by tests
2    app = FastAPI(title=settings.app_name, lifespan=lifespan, openapi_tags=..., generate_unique_id_function=unique_id,
                   openapi_url=None if not settings.docs_enabled)
3    app.state.settings = settings; app.state.events = []
4    app.dependency_overrides[get_settings] = lambda: settings
5    @app.middleware("http") request_id; CORSMiddleware if settings.cors_origins (added last = outermost)
6    app.include_router(build_api_router(), prefix=settings.api_prefix)
7    app.include_router(meta_router); app.mount("/static", ...); app.mount("/legacy", create_legacy_app())
8    return app                                          nothing has been opened yet: that is the lifespan's job

Real scenario: a test suite that builds one app with docs_enabled=False and another with CORS origins (test_docs_can_be_switched_off, test_cors_is_outermost_when_enabled); a CLI command (python -m shop.cli export-openapi) that builds the app only to dump the schema; a worker process that imports the package without starting HTTP at all.

Module-level appcreate_app()
Built at import; settings read at importBuilt when called, with the settings given
One app per process, shared by all testsOne app per test, no leaked state
Overrides must be undone by handThrow the app away
uvicorn shop.main:appuvicorn --factory shop.main:create_app or shop.asgi:app
Fine for one fileNeeded once there are settings, mounts and tests

Fix / how to use it: one factory in main.py, a two-line asgi.py (app = create_app()) for servers and fastapi run, and tests that never import shop.asgi.

Entry points: main.py set-up, asgi.py, --factory and [tool.fastapi] Important ​

In plain words: Something has to tell the server where the app object is. The usual forms are an import string (uvicorn shop.asgi:app), a factory string (uvicorn --factory shop.main:create_app), and, for the fastapi CLI, the entrypoint in pyproject.toml. Keep the file the server imports tiny; all logic lives in the factory.

Common misunderstanding: "main.py must contain the routes." In a structured app main.py "ties everything together" (the tutorial's words: "This will be the main file in your application that ties everything together. And as most of your logic will now live in its own specific module, the main file will be quite simple"). Routes live in feature routers.

Definition: The tutorial: "As your FastAPI app object lives in app/main.py, you can configure the entrypoint in your pyproject.toml file like this: [tool.fastapi] entrypoint = "app.main:app"", because otherwise "other tools might not be able to find it, for example the VS Code Extension or FastAPI Cloud". The snippet sets entrypoint = "shop.asgi:app".

     command (from the project root)                         what is imported                    real?
1    uvicorn --factory shop.main:create_app --port 18931     shop.main, then create_app()        real: "Application startup complete."
2    uvicorn shop.asgi:app --workers 2                       shop.asgi in each worker            real: two "Application startup complete." lines
3    fastapi run   ([tool.fastapi] entrypoint)                shop.asgi:app                       expected, not run (fastapi-cli not installed here)
4    pytest                                                  shop.main.create_app in fixtures    real: 45 passed

Real scenario: the same image started as API (uvicorn shop.asgi:app) and as a worker (python -m shop.worker) that imports shop.core but no routers; a Procfile/Kubernetes command that points at the factory.

FileContainsImported by
shop/main.pycreate_app(), tags metadata, unique-id functionTests, asgi.py, tools
shop/asgi.pyapp = create_app()Uvicorn, Gunicorn, fastapi run
pyproject.toml[tool.fastapi] entrypoint, dependencies, pytest configTooling
shop/api.pybuild_api_router()main.py
Feature router.pyPath operationsapi.py

Fix / how to use it: keep import side effects in asgi.py only, point every runner at it (or at the factory), and record the entry point in pyproject.toml.

One worker's life: settings once, resources in the lifespan, nested router lifespantimeimportcreate_app()get_settings() onceroutes registeredapp lifespan (FastAPI(lifespan=...))before yield: Database.connect(), httpx.AsyncClient()app.state.db, app.state.httpcatalog router lifespan (merged by include_router)before yield: app.state.featured_ids (cache warm-up)requests served here: request.app.state.dbafter yield (SIGTERM):aclose(), close()Order recorded by tests/shop/core/test_lifespan.py (real run):startup -> catalog:startup -> [requests] -> catalog:shutdown -> shutdownWho gets lifespan eventstop-level app + included routersyes, nested in include ordermounted sub-applicationno: /legacy/report says false--workers 2everything above, once per worker

Lifespan control: asynccontextmanager, startup, shutdown, app.state Must-know ​

In plain words: The lifespan is one async function with one yield. Code before yield runs once when the server starts the app (open the database engine, create the HTTP client, load a model); code after yield runs once when the server stops it (close them). Store what you opened on app.state, and reach it from a request through request.app.state.

Common misunderstanding: "I can keep using @app.on_event("startup") next to a lifespan." The docs: "If you provide a lifespan parameter, startup and shutdown event handlers will no longer be called. It's all lifespan or all events, not both." The probe registered an on_event("startup") handler on an app with lifespan= and it was not called; on its own, on_event prints DeprecationWarning: on_event is deprecated, use lifespan event handlers instead. (real). A second one: "the lifespan runs in every test". TestClient(app) without with does not run it (real: app.state.events == []); only with TestClient(app) as client: does.

Definition: The FastAPI docs: "You can define this startup and shutdown logic using the lifespan parameter of the FastAPI app, and a 'context manager'", "The first part of the function, before the yield, will be executed before the application starts. And the part after the yield will be executed after the application has finished." The reason not to load at import: "You could load it at the top level of the module/file, but that would also mean that it would load the model even if you are just running a simple automated test". Starlette: "You can store arbitrary extra state on the application instance, using the generic app.state attribute." Underneath, this is the ASGI Lifespan Protocol with startup and shutdown events.

     uvicorn --factory shop.main:create_app   (real log lines in the right column)
1    create_app(): settings read, routes registered       INFO:     Started server process [5678]
2    lifespan startup sent by Uvicorn                       INFO:     Waiting for application startup.
3    app lifespan: Database.connect(seed=True), httpx.AsyncClient(base_url=..., timeout=2.0)
4    nested catalog lifespan: app.state.featured_ids = [2, 3]
5    yield (both)                                           INFO:     Application startup complete.
6    requests: handlers read request.app.state.db           INFO:     127.0.0.1:56644 - "GET /api/v1/products/featured HTTP/1.1" 200 OK
7    SIGTERM                                                INFO:     Shutting down / Waiting for application shutdown.
8    catalog lifespan exits, then app lifespan: await http.aclose(); db.close()
9                                                           INFO:     Application shutdown complete.

Real scenario: a SQLAlchemy AsyncEngine created at startup and disposed at shutdown (SQLAlchemy 2 & SQLModel); one httpx.AsyncClient per process to a payment provider, reusing connections; an ML model loaded once into memory; a Redis client; a background consumer task started and cancelled.

ResourceOpen (before yield)Close (after yield)Reached via
Database engine/poolcreate_async_engine(url) (SQLAlchemy 2.0 asyncio docs) / Database.connect()await engine.dispose() / close()request.app.state.db or a dependency
HTTP clienthttpx.AsyncClient(timeout=...)await client.aclose()request.app.state.http
Cache clientredis.asyncio.Redis(...) (redis-py asyncio docs)await client.aclose() ("requires an explicit disconnect")Dependency
ML modelload_model(path)Free memory/GPUapp.state.model
SettingsNot here: read in the factory—Depends(get_settings)
Per-request objectsNever here (sessions, transactions)—yield dependencies

Fix / how to use it: one lifespan in core/lifespan.py, try/finally around yield, resources on app.state and handed to routes through small dependencies (get_db), and per-request objects in yield dependencies instead (Dependency Injection).

Router lifespans and lifespan state Good to know ​

In plain words: A router can bring its own lifespan (APIRouter(lifespan=...)). When it is included, FastAPI nests it inside the parent's lifespan, so a feature can own its startup work (warm a cache, start a consumer) without the app's lifespan knowing about it. A lifespan can also yield a dictionary instead of setting app.state; that dictionary becomes request.state in each request.

Common misunderstanding: "A mounted app's lifespan runs too." It does not: the FastAPI docs warn that "these lifespan events (startup and shutdown) will only be executed for the main application, not for Sub Applications - Mounts", and the snippet's mounted /legacy app reports {"lifespan_ran": false} (real, in tests and through curl). Included routers are run; mounted apps are not.

Definition: 0.128.8 merges with _merge_lifespan_context(self.lifespan_context, router.lifespan_context): the original (parent) context is entered first and the nested one inside it; yielded states are combined as {**nested_state, **original_state}, so the parent's value wins for the same key. Real probe: app yields {"source": "app", "app_only": 1}, router yields {"source": "router", "router_only": 2}, a request sees {'source': 'app', 'app_only': 1, 'router_only': 2}; order ['app:start', 'router:start', 'router:stop', 'app:stop']. Starlette: "The state received on the requests is a shallow copy of the state received on the lifespan handler." Dictionary-style access (request.state["http_client"]) "was introduced in Starlette 0.52.0 (January 2026)", newer than the pinned 0.49.3.

     app = FastAPI(lifespan=app_ls); app.include_router(APIRouter(lifespan=router_ls))   (real probe)
1    enter app_ls       -> state {"source": "app", "app_only": 1}
2    enter router_ls    -> state {"source": "router", "router_only": 2}
3    merged state       = {**router_state, **app_state} = {"source": "app", "app_only": 1, "router_only": 2}
4    request.state.source == "app"; request.state.router_only == 2
5    shutdown: router_ls exits first, app_ls last

Real scenario: the catalog feature warming featured_ids at startup (the snippet); an events feature that starts a Kafka consumer in its router lifespan and stops it at shutdown; a typed State TypedDict yielded from the lifespan instead of untyped app.state.

MechanismScopeRuns for mounts?Access
FastAPI(lifespan=...)AppNo (only top level)app.state / yielded dict
APIRouter(lifespan=...)Merged into includer (0.112.2+)NoSame
on_event("startup")Deprecated; ignored if lifespan=NoGlobals
Yielded state dictPer request (shallow copy)—request.state.x
app.state.x = ...Process—request.app.state.x

Fix / how to use it: use router lifespans for feature-owned startup work that depends on core resources (they run inside the app lifespan), keep key names distinct, and never rely on a mounted app's lifespan.

Settings(): first source that has the field wins, then Pydantic validates1 Settings(app_name="x") keyword arguments2 environment: SHOP_APP_NAME=from-env3 dotenv: .env, then .env.prod on top4 secrets_dir: /run/secrets/shop_admin_token5 class default: app_name = "Shop API"Validation (same rules as a BaseModel)"5" -> 5.0 for http_timeout_s: float"false" -> False for docs_enabled: bool'["https://a"]' -> list for cors_origins"production" -> literal_error"60" with le=30 -> less_than_equaltypo in .env -> extra_forbiddenSecretStr repr -> '**********'failure = the process does not start@lru_cache get_settings(): built once per process; app.dependency_overrides[get_settings] in tests;get_settings.cache_clear() between tests. All five rows checked in tests/shop/core/test_settings.py.

Settings with pydantic-settings: BaseSettings, SettingsConfigDict, env_file Must-know ​

In plain words: class Settings(BaseSettings) is a Pydantic model whose fields are filled from environment variables (and optionally .env files and secret files) instead of from a dict. You declare types and defaults; Pydantic converts the strings and refuses to start the app if a value is wrong.

Common misunderstanding: "Environment variables can be booleans and numbers." They cannot; the FastAPI docs: "any value read in Python from an environment variable will be a str, and any conversion to a different type or any validation has to be done in code." That is why os.environ.get("SHOP_DEBUG", "false") in the Before app is truthy, and why docs_enabled: bool in Settings is not ("false" → False, real test). Another one: "BaseSettings is in pydantic." Since Pydantic v2 it is a separate package: from pydantic_settings import BaseSettings (FastAPI 0.100.0 notes).

Definition: FastAPI docs: "Pydantic will read the environment variables in a case-insensitive way, so, an upper-case variable APP_NAME will still be read for the attribute app_name. Next it will convert and validate the data." Configuration goes in model_config = SettingsConfigDict(...): env_prefix ("allows you to set a prefix for all environment variables"; default ''), env_file, env_file_encoding, secrets_dir, case_sensitive, env_nested_delimiter, extra. Real validation failures from the snippet: environment = "production" → Input should be 'dev', 'test', 'staging' or 'prod' [type=literal_error ...]; SHOP_HTTP_TIMEOUT_S=60 with le=30 → Input should be less than or equal to 30 [type=less_than_equal ...]; SHOP_CORS_ORIGINS=https://shop.example for a list[str] → SettingsError: error parsing value for field "cors_origins" from source "EnvSettingsSource" (complex types are read as JSON).

     process environment                 Settings field                    value after validation (real)
1    SHOP_HTTP_TIMEOUT_S=5               http_timeout_s: float (gt=0, le=30)   5.0
2    SHOP_DOCS_ENABLED=false             docs_enabled: bool                    False
3    SHOP_CORS_ORIGINS='["https://shop.example"]'  cors_origins: list[str]    ["https://shop.example"]
4    shop_app_name=lower-case-name       app_name: str                         "lower-case-name" (case-insensitive)
5    APP_NAME=no-prefix                  app_name: str                         "Shop API" (prefix required)
6    SHOP_ADMIN_TOKEN=s3cret             admin_token: SecretStr                repr: SecretStr('**********')

Real scenario: a DATABASE_URL validated as PostgresDsn and rewritten to the postgresql+psycopg:// driver in a field_validator (what the full-stack template does); feature flags as bool fields; an Environment = Literal["dev", "test", "staging", "prod"] that rejects typos at startup.

SettingsConfigDict keySnippet valueEffect
env_prefix"SHOP_"SHOP_DATABASE_URL → database_url; DATABASE_URL alone is ignored
env_file".env" (and .env.<env> from load_settings)Read relative to the CWD
env_file_encoding"utf-8"Do not depend on the OS default
extra"forbid" (the default)Unknown key in a dotenv file → extra_forbidden
secrets_dirvia _secrets_dir at instantiationOne file per value
case_sensitivedefault Falseshop_app_name works too
env_nested_delimiternot usedSHOP_DB__POOL_SIZE → nested model field

Fix / how to use it: one Settings class per service in core/config.py, a prefix per service, Literal for closed sets, SecretStr for secrets, constraints with Field, and no os.environ anywhere else in the code.

Settings sources and priority: .env vs real environment, secrets_dir Important ​

In plain words: A value can be given in five places, and the higher one wins: arguments to Settings(...), real environment variables, .env files, files in a secrets directory, and the default in the class. .env is a developer convenience; in staging and production the real environment (and mounted secret files) are the source of truth.

Common misunderstanding: ".env overrides the environment, like a config file." The opposite: "environment variables will always take priority over values loaded from a dotenv file", and "a dotenv file and environment variables will always take priority over values loaded from the secrets directory" (Pydantic Settings docs). test_priority_env_over_dotenv_over_secrets checks all of it. Another: "a typo in .env is ignored." With the default extra="forbid", SHOP_DATABSE_URL=... in .env fails: real 1 validation error for Settings | shop_databse_url | Extra inputs are not permitted [type=extra_forbidden, input_value='sqlite:///typo.db', input_type=str].

Definition: The docs list the order "in descending order of priority": CLI arguments if cli_parse_args is enabled, "Arguments passed to the Settings class initialiser", "Environment variables", "Variables loaded from a dotenv (.env) file", "Variables loaded from the secrets directory", "The default field values for the Settings model." For several dotenv files: "The files will be loaded in order, with each file overriding the previous one." A secret file "follows the same principal as a dotenv file except it only contains a single value and the file name is used as the key"; with a prefix the file name includes it (shop_admin_token, real test). "By default Docker uses /run/secrets as the target mount point." A missing secrets directory is only a warning (real: UserWarning: directory "/run/secrets-missing" does not exist).

     the same field from four places (tests/shop/core/test_settings.py, real)
1    secrets/shop_app_name = "from-secret-file"; .env SHOP_APP_NAME=from-dotenv; env SHOP_APP_NAME=from-env
2    Settings(_secrets_dir=...).app_name              -> "from-env"       (environment beats .env)
3    admin_token: .env "from-dotenv" vs secret file   -> "from-dotenv"    (.env beats secrets dir)
4    payments_base_url only in the secrets dir        -> "https://payments.example"  (beats the default)
5    Settings(..., app_name="from-init")              -> "from-init"      (init beats everything)

Real scenario: a laptop with a .env (copied from .env.example, git-ignored) and CI with real variables only; a Kubernetes pod with a ConfigMap as env vars and a Secret mounted as files under /run/secrets; Docker Swarm or Compose secrets: mounted at /run/secrets.

SourceGood forNot for
Init kwargsTests, factories, CLIsProduction values
Real environmentEvery deployed environment; twelve-factor configLarge secrets, multi-line keys
.env (git-ignored)Local development defaultsProduction (nobody should edit files on servers)
.env.example (committed)Documenting the variablesReal secrets
Secrets directoryPasswords, API keys, certificates as filesNon-secret config
Class defaultSafe defaults that work locallySecrets (change-me must not reach production)

Fix / how to use it: commit .env.example, ignore .env (this repository's .gitignore already lists .env), give production values through the real environment and secret files, keep extra="forbid", and refuse default secrets outside dev/test at startup: the snippet's Settings has a model_validator(mode="after") that raises when environment is staging or prod and admin_token is still change-me (test_default_admin_token_is_refused_outside_dev; the real prod start without a token exits with Value error, SHOP_ADMIN_TOKEN must be set in prod). Features of the current docs that 2.11.0 lacks (env_file_depth, dotenv_filtering, env_prefix_target, PYDANTIC_SETTINGS_DEBUG logging of every source) need a newer pydantic-settings on Python 3.10+/3.11+.

The Settings dependency: lru_cache, per-environment config, tests Must-know ​

In plain words: Wrap the creation of Settings in a function decorated with @lru_cache and use it as a dependency (Depends(get_settings)). The first call reads the environment and files; every later call returns the same object. Tests replace it with app.dependency_overrides[get_settings], or the factory receives a settings object and installs the override itself.

Common misunderstanding: "Settings() in the dependency is fine." Without the cache, "we would create that object for each request, and we would be reading the .env file for each request" (FastAPI docs). With the cache, a changed variable is invisible until get_settings.cache_clear() (real test). And a module-level settings = Settings() is read at import, which is exactly what the factory avoids.

Definition: FastAPI docs: "as we are using the @lru_cache decorator on top, the Settings object will be created only once, the first time it's called"; "That way, it behaves almost as if it was just a global variable. But as it uses a dependency function, then we can override it easily for testing." functools.lru_cache caches "up to the maxsize most recent calls"; a zero-argument function has one entry. Per-environment files in the snippet: load_settings(env) passes _env_file=(".env", f".env.{env}"), so .env.prod overrides .env, and a missing .env.dev is simply skipped (real test test_per_environment_file_overrides_base).

     process lifetime                                     get_settings() cache
1    first Depends(get_settings) or create_app()          miss -> load_settings() -> Settings(...) read env, .env, .env.<env>, secrets
2    every later request                                   hit  -> the same object (no file I/O)
3    test: get_settings.cache_clear(); monkeypatch.setenv(...)   next call re-reads
4    test: create_app(Settings(_env_file=None, environment="test"))  factory installs dependency_overrides[get_settings]
5    worker 2 of --workers 2                              its own cache: settings read once per process

Real scenario: GET /version returns {"app":"Shop API","environment":"staging"} when started with SHOP_ENVIRONMENT=staging (real curl) and "prod" with SHOP_ENVIRONMENT=prod (real, two workers); a test that switches docs off without touching the environment.

PatternReads configTestableVerdict
os.environ.get at call sitesEvery call, as stringsMonkeypatch everythingAvoid
settings = Settings() at module levelAt importMust reload modulesSmall scripts only
@lru_cache get_settings() + DependsOnce per processdependency_overrides, cache_clear()FastAPI docs' recommendation
create_app(settings) + overrideCaller decidesPass a Settings objectThis chapter's factory
Per-environment Python classes (ProdSettings(Settings))OnceYesWorks; files or env vars are simpler

Fix / how to use it: get_settings with @lru_cache in core/config.py, SettingsDep = Annotated[Settings, Depends(get_settings)], cache_clear() in an autouse fixture, and environment-specific values in .env.<env> locally and in real variables when deployed. "Settings dependency" is also the hook Testing FastAPI uses for test databases.

Same contract, two shapes: by technical layer vs by featurelayered/ (by technical layer)routers/products.pyorders.pydeps.pyschemas/products.pyorders.pyservices/orders.pyrepositories/products.pyorders.pymodels/products.pyorders.pya change to "orders" = the dashed column:five folders, one file in eachshop/ (by feature, vertical slices)catalog/router.py, router_v2.pyschemas.pymodels.pyrepository.pyservice.py (public)orders/router.pyschemas.pymodels.pyrepository.pyservice.pyorders -> catalog.service onlycore/ config.py db.py lifespan.py deps.pyfeatures import core; core never imports featuresa change to "orders" stays in one folder;the folder can later become a servicetests/test_layouts_equivalent.py: both packages publish the same 6 catalog/orders operationstests/ mirrors the package: tests/shop/catalog, tests/shop/orders, tests/shop/core, each folder with its conftest scope

Organizing code by technical layer Must-know ​

In plain words: One folder per kind of code: routers/ (HTTP), schemas/ (Pydantic request/response models), models/ (database models), services/ (business rules), repositories/ (queries). Inside each, one module per resource. It is the layout the FastAPI tutorial starts with (app/routers/items.py, app/routers/users.py) and the full-stack template uses (app/api/routes/, app/models.py, app/crud.py).

Common misunderstanding: "Layers mean the code is decoupled." Folders do not stop imports: in layered/, routers/orders.py imports repositories/products.py directly, and nothing prevents repositories/ from importing routers/. The layering is a convention unless a tool enforces it: import-linter checks declared contracts (its contract types include "Forbidden", "Layers" and "Independence"), and Ruff's banned-api rule (TID251, "Derived from the flake8-tidy-imports linter", configured under lint.flake8-tidy-imports.banned-api) "Checks for banned imports".

Definition: The layout of the layered/ package, and the dependency direction it intends:

1    layered/
2    ├── main.py               create_app(): lifespan, include_router(v1)
3    ├── db.py                 Database (SQLite stand-in for an engine)
4    ├── routers/              HTTP: paths, status codes, Depends      -> may import schemas, services, repositories
5    │   ├── deps.py, products.py, orders.py
6    ├── schemas/              Pydantic API models (OrderIn, OrderOut)  -> imports nothing of ours
7    ├── services/orders.py    business rules (price from catalog)      -> imports repositories, models
8    ├── repositories/         SQL                                      -> imports db, models
9    └── models/               persistence models (rows / ORM classes)  -> imports nothing of ours
10   direction: routers -> services -> repositories -> models   (schemas only at the HTTP edge)

Real scenario: a 6-endpoint internal service maintained by one developer; a CRUD API where every resource has the same shape and the layers are the useful axis; a codebase whose ORM models are shared by several resources and are easier to keep in one models/ package.

StrengthWeakness
Obvious to anyone who knows MVCOne feature change touches every layer folder
Easy to find "all the SQL" or "all the schemas"Folders grow to dozens of unrelated files
Matches tutorials and templatesCross-feature imports are invisible
Few top-level decisionsExtracting a feature into a service means slicing every layer
Good for small services and microservicesOwnership by team is unclear

Fix / how to use it: use it while the service has a handful of resources and one team; keep the dependency direction (routers → services → repositories → models); switch to features when the layer folders stop fitting on a screen.

Organizing code by feature: vertical slices and module boundaries Must-know ​

In plain words: One folder per business capability (catalog/, orders/, payments/), each containing its own router.py, schemas.py, models.py, repository.py and service.py: a vertical slice through all layers. Shared infrastructure goes into core/ (config, database, lifespan, common dependencies). Features talk to each other only through a small public module.

Common misunderstanding: "By feature means no layers." The layers are still there, one file each, inside the feature. What changes is the top-level axis: the folder you open is the business concept. The fastapi-best-practices guide explains why its authors switched: organising "by file type (e.g., crud, routers, models) … works well for microservices or smaller projects. However, this approach didn't scale well for our monolith with many domains and modules", and the structure they found "more scalable and evolvable is inspired by Netflix's Dispatch".

Definition: The shop/ package and its boundary rules, which the snippet follows:

1    shop/
2    ├── main.py, asgi.py, api.py, legacy.py    factory, entry point, router tree, mounted app
3    ├── core/            config.py, db.py, lifespan.py, deps.py, router.py   <- imported by features, imports no feature
4    ├── catalog/         router.py, router_v2.py, schemas.py, models.py, repository.py, service.py (public)
5    ├── orders/          router.py, schemas.py, models.py, repository.py, service.py
6    ├── internal/admin.py   shared router, configured at include time
7    └── static/robots.txt
8    rule 1: inside a feature, relative imports (from .repository import OrderRepository)
9    rule 2: across features, absolute imports of the public module only (from shop.catalog.service import find_product)
10   rule 3: core never imports a feature; features never import each other's router or repository

Real scenario: a shop monolith with catalog, cart, orders, payments, shipping, each owned by a team; the moment one feature (payments) needs its own deploy cadence and becomes a service, its folder moves out with its tests; a modular monolith as an architecture choice (Modular Monolith).

ConcernBy feature answer
Where are the order rules?orders/service.py
Who may call them?Other features, through orders/service.py only
Where are the order tests?tests/shop/orders/
What does a new feature need?A folder with the five files, one include_router line, one tag
Shared code?core/ (infrastructure) or a deliberately public module (domain)
How to enforce boundaries?Review + an import-linter "Forbidden" or "Independence" contract (shop.orders may not import shop.catalog.repository), or Ruff banned-api (TID251)

Fix / how to use it: one folder per capability, core/ for infrastructure, public service.py modules for cross-feature calls, tests mirroring the folders, and an import rule checked in CI once the team grows. Module boundaries as an architecture concern: Clean & Hexagonal Architecture.

data.py separation of concerns: routers, services, repositories Important ​

In plain words: Keep three jobs apart. The router speaks HTTP: it reads the request, calls one service function and turns the result or a domain error into a status code. The service holds the business rule ("the price comes from the catalog, not from the client"). The repository (the course's data.py) holds the SQL. Each can then be tested at its own level, and the router file stays short enough to read as the API's table of contents.

Common misunderstanding: "Putting the SQL in the route function is simpler." For one route, yes; for twenty, the same query is written three times, a schema change means hunting through every router, and the business rule can only be tested over HTTP. The snippet's service test runs without an app or a client (test_orders_service.py: place_order(db, product_id=1, quantity=3).total_cents == 12600).

Definition: In the snippet, orders/router.py maps UnknownProduct to 422 and missing orders to 404, orders/service.py raises UnknownProduct and computes price_cents * quantity, and orders/repository.py runs the INSERT. The service knows nothing about HTTP status codes; the repository knows nothing about business rules. The SQL that the repositories own:

sql
-- shop/core/db.py: the schema both features use (SQLite here; PostgreSQL in production)
CREATE TABLE IF NOT EXISTS products (
    id          INTEGER PRIMARY KEY,
    sku         TEXT    NOT NULL UNIQUE,
    name        TEXT    NOT NULL,
    price_cents INTEGER NOT NULL CHECK (price_cents >= 0),
    featured    INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS orders (
    id          INTEGER PRIMARY KEY,
    product_id  INTEGER NOT NULL REFERENCES products (id),
    quantity    INTEGER NOT NULL CHECK (quantity > 0),
    total_cents INTEGER NOT NULL,
    created_at  TEXT    NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS orders_product_id_idx ON orders (product_id);

-- catalog/repository.py, ProductRepository.list(featured_only=True)
SELECT id, sku, name, price_cents, featured FROM products WHERE featured = 1 ORDER BY id;

-- orders/repository.py, OrderRepository.add() (values bound, never formatted into the string)
INSERT INTO orders (product_id, quantity, total_cents) VALUES (?, ?, ?);
     POST /api/v1/orders {"product_id": 2, "quantity": 2}   (real curl: 201 {"id":1,"product_id":2,"quantity":2,"total_cents":9000})
1    router   create_order(body: OrderIn, db: DbDep)          validation by Pydantic (quantity 1..100)
2    service  place_order(db, 2, 2)
3    service  -> catalog.service.find_product(db, 2)          public surface of another feature
4    repo     SELECT ... FROM products WHERE id = ?            price_cents = 4500
5    service  total = 4500 * 2 = 9000
6    repo     INSERT INTO orders (...) VALUES (?, ?, ?)
7    router   201 + OrderOut (response_model filters the fields)
8    unknown product: service raises UnknownProduct -> router -> 422 {"detail": "Unknown product"}

Real scenario: the course's split of a main.py into routes.py and data.py; a repository replaced by a SQLAlchemy implementation without touching routers (SQLAlchemy 2 & SQLModel); a service reused by a CLI or a background job.

LayerKnows aboutDoes not know aboutTested with
RouterHTTP, status codes, schemas, dependenciesSQLTestClient
ServiceDomain rules, domain errorsHTTP, Request, status codesPlain pytest + a test DB
RepositorySQL, rows, the DB driverBusiness rules, HTTPA real (SQLite/PostgreSQL) DB
SchemasAPI shapesPersistenceThrough router tests
ModelsPersistence shapesAPI shapesThrough repository tests

Fix / how to use it: routers thin, services pure, repositories the only place with SQL; domain exceptions raised by services and mapped to HTTP in one place (per router, or app-wide with an exception handler: Exceptions & Responses).

Package-relative imports, __init__.py and circular imports Important ​

In plain words: Inside a package you can import a sibling module with one dot (from .repository import OrderRepository) and a module of the parent package with two (from ..db import Database). Absolute imports (from shop.core.db import Database) always work from anywhere. A circular import happens when module A imports B while B (directly or through others) imports A, and one of them asks for a name that does not exist yet.

Common misunderstanding: "Relative imports work when I run the file directly." They do not: a file run as a script has no package, so python app/orders/script.py fails with ImportError: attempted relative import with no known parent package (real). The Python tutorial: "relative imports are based on the name of the current module's package. Since the main module does not have a package, modules intended for use as the main module of a Python application must always use absolute imports." Run it as a module (python -m app.orders.script) instead. Going up too far (from ...config import settings inside app/orders/) gives ImportError: attempted relative import beyond top-level package (real).

Definition: PEP 328: "A single leading dot indicates a relative import, starting with the current package. Two or more leading dots give a relative import to the parent(s) of the current package, one level per dot after the first." The real circular-import message from the probe (catalog imports orders, orders imports catalog): ImportError: cannot import name 'count_orders_for' from partially initialized module 'app.orders.service' (most likely due to a circular import). The module object exists in sys.modules as soon as its import starts, but its names are defined only as its body runs; a from X import name during that window finds a half-built module.

     python -c "import app.orders.service"   (real probe, imports-probe/)
1    start app.orders.service            sys.modules["app.orders.service"] = <empty module>
2      line 1: from app.catalog.service import find_product
3        start app.catalog.service
4          line 1: from app.orders.service import count_orders_for
5          app.orders.service is in sys.modules but count_orders_for is not defined yet (we are still at its line 1)
6          ImportError: cannot import name 'count_orders_for' from partially initialized module ...
7    fix: catalog must not import orders; move the shared piece to core/ or invert the call

Real scenario: orders needs product prices and catalog wants "number of orders per product": both import each other and the app fails at startup; type-hint-only imports that create a cycle (fix: if TYPE_CHECKING: plus string annotations); __init__.py files that re-export everything and turn every import into an import of the whole package.

FormExampleUse
Relative, same packagefrom .repository import OrderRepositoryInside a feature
Relative, parentfrom ..dependencies import get_token_header (tutorial)Inside a small app
Absolutefrom shop.catalog.service import find_productAcross features, in tests, in scripts
Module importfrom shop.catalog import router as catalogAvoid name clashes between router variables
if TYPE_CHECKING: importTypes onlyBreak cycles caused by annotations
Re-export in __init__.pyfrom .service import find_productSparingly: one public surface per feature

Fix / how to use it: relative inside a feature, absolute across features, dependency direction one way (features → core; orders → catalog, never back), run code with python -m or through the installed package, and treat an import cycle as a design signal rather than something to hide with a function-level import.

src layout vs flat layout, naming conventions Good to know ​

In plain words: In a flat layout the import package (shop/) sits next to pyproject.toml; in a src layout it sits in src/shop/. The src layout forces you to install the project (or set PYTHONPATH=src) before the code is importable, which guarantees you test what you ship. The snippet uses the flat layout so that pytest's pythonpath = ["."] is enough.

Common misunderstanding: "src layout is required for applications." It is a packaging recommendation that matters most for libraries and for tests that should run against the installed package. The Packaging User Guide: "The src layout requires installation of the project to be able to run its code, and the flat layout does not", and it "helps prevent accidental usage of the in-development copy of the code" because "the Python interpreter includes the current working directory as the first item on the import path". pytest: "especially if you use the default import mode prepend, it is strongly suggested to use a src layout."

Definition: Real probe: in a src-layout project, python -c "import shopx" from the project root fails with ModuleNotFoundError: No module named 'shopx'; with PYTHONPATH=src it imports srcdemo/src/shopx/__init__.py. For a FastAPI service the naming conventions that pay off are: lowercase module names, one router.py per feature, schemas.py for Pydantic API models and models.py for persistence models, service.py/repository.py (singular), deps.py or dependencies.py, config.py for settings, tag names equal to feature names, and function names that read as SDK methods (list_products, get_product, create_order).

     flat (this snippet)                            src
1    pyproject.toml                                 pyproject.toml
2    shop/__init__.py                               src/shop/__init__.py
3    tests/...                                      tests/...
4    pytest: pythonpath = ["."]                     pytest: pythonpath = ["src"] or pip install -e .
5    uvicorn shop.asgi:app (from the root)          uvicorn shop.asgi:app after install, or --app-dir src
6    risk: the CWD copy shadows the installed one   risk: forgetting to reinstall after adding package data

Real scenario: the fastapi-best-practices layout (src/auth/router.py, src/posts/service.py …); a Docker image that installs the project with pip install . and runs from / so no source tree shadows the installed package; a monorepo with several services, each with its own src/<service>/.

NameHoldsAvoid
router.py / routers/APIRouter and path operationsBusiness rules, SQL
schemas.pyPydantic request/response modelsORM classes
models.pyORM/persistence modelsAPI-only shapes
service.pyDomain logic, domain errorsRequest, HTTPException
repository.py (or crud.py)QueriesStatus codes
deps.pyDependencies (get_db, require_admin)Heavy logic
config.pySettings, get_settingsReading env vars elsewhere
main.py / asgi.pyFactory / process entryRoutes

Fix / how to use it: flat layout plus pythonpath = ["."] for a single service, src layout plus an editable install when the package is also published or when you want the installed copy under test; the same file names in every feature.

API versioning with routers: /v1 and /v2 side by side Important ​

In plain words: Put each version's routes under a router with prefix="/v1" or prefix="/v2" and include both. Unchanged endpoints can be included in both versions; changed ones get a new router (and a new response model) in v2. The OpenAPI document then shows both, side by side.

Common misunderstanding: "Copying the whole v1 package into v2 is versioning." It doubles the code for every endpoint that did not change. Version only what changed: in the snippet, v2 contains one route (GET /api/v2/products/{product_id} returns {"price":{"amount":"45.00","currency":"EUR"}}, real) and v1 keeps price_cents. When to version at all, and how long to keep v1, is design work covered in API Versioning & Evolution.

Definition: The tutorial: "You can also use .include_router() multiple times with the same router using different prefixes. This could be useful, for example, to expose the same API under different prefixes, e.g. /api/v1 and /api/latest." With function-name operationIds the same router included twice collides (Duplicate Operation ID status_, real warning); the tag-based ids stay unique when each version's router has its own tag (catalog-v2-get_product).

     build_api_router()
1    v1 = APIRouter(prefix="/v1"): catalog.router, orders.router, admin.router (hidden)
2    v2 = APIRouter(prefix="/v2"): catalog_v2.router (tags=["catalog-v2"])
3    api.include_router(v1); api.include_router(v2); app.include_router(api, prefix="/api")
4    GET /api/v1/products/2 -> {"price_cents": 4500, ...}
5    GET /api/v2/products/2 -> {"price": {"amount": "45.00", "currency": "EUR"}, ...}
6    later: app.include_router(api_v1, deprecated=True) marks v1 in the docs; removal after the sunset date

Real scenario: a mobile app that cannot be force-updated and keeps calling v1 for a year; /api/latest as an alias for the newest version for internal tools; a v2 that changes only the money representation.

TechniqueFastAPI toolTrade-off
URL path versionRouter prefix /v1, /v2Visible, cacheable, easy to route at the gateway
Same router under two prefixesinclude_router(r, prefix=...) twiceWatch operationIds
Header version (Accept-Version)A dependency, or APIRouter.matches() (experimental, 0.137.0+)Invisible in URLs; harder to cache
Separate deployments per versionTwo apps behind a gatewayMost isolation, most cost
Deprecationdeprecated=True on include; Sunset/Deprecation headers in middlewareCommunicate dates

Fix / how to use it: use API versioning routers (/v1, /v2 prefixes), not copied packages; give each version router its own tag; keep shared routers shared; mark the old version deprecated at include time.

Mounting sub-applications and static files: app.mount Important ​

In plain words: app.mount("/legacy", other_app) hands every request under /legacy to a completely separate ASGI app: its own routes, its own /legacy/docs, its own middleware and exception handlers. app.mount("/static", StaticFiles(directory=...)) does the same with Starlette's file server. Use include_router for parts of your API and mount for things that are genuinely another app.

Common misunderstanding: "Mount and include are two ways of doing the same thing." The tutorial: "'Mounting' means adding a completely 'independent' application in a specific path". Mounted apps are absent from the main OpenAPI document, do not get the parent's lifespan, and see a root_path ({"root_path": "/legacy"}, real) that FastAPI uses so the sub-app's docs work: "FastAPI will take care of communicating the mount path for the sub-application using a mechanism from the ASGI specification called a root_path."

Definition: Starlette routing: Mount('/users', routes=[...]) for sub-routes and Mount("/static", app=StaticFiles(directory="static"), name="static") for an app. In the snippet, /static/robots.txt is served (real 200) and /legacy/docs returns 200 text/html; charset=utf-8 (real) while the main /openapi.json has no /legacy paths. The route table lists both as Mount entries after the API routes. In current FastAPI, a built single-page front-end is better served with app.frontend("/", directory="dist") (0.138.0+), which registers "low-priority routes" checked "only if no normal route matched".

     request                         route table (in order)            handled by
1    GET /api/v1/products/2          APIRoute /api/v1/products/{id}     shop app, main lifespan state
2    GET /static/robots.txt          Mount /static                      StaticFiles (no OpenAPI entry)
3    GET /legacy/report              Mount /legacy                      legacy FastAPI app: lifespan_ran false, root_path /legacy
4    GET /legacy/docs                Mount /legacy                      legacy app's own Swagger UI
5    GET /nope                       no match                           404 from the main app (with x-request-id: middleware wraps it)

Real scenario: an old Flask or Django admin wrapped with an ASGI adapter and mounted under /admin-legacy; a metrics exporter app mounted at /metrics; a GraphQL app mounted at /graphql; static assets in development (Nginx or a CDN in production).

NeedUseGets parent's routers/docsGets parent's lifespan
A feature of this APIinclude_routerYesYes
A separate FastAPI/Starlette appapp.mount(path, app)No (own docs)No
Files from a directoryapp.mount("/static", StaticFiles(...))No—
A built SPA (0.138.0+)app.frontend("/", directory="dist")Low-priority routes—
A WSGI appMount via an ASGI adapterNoNo

Fix / how to use it: include your own features; mount only independent apps and files (a StaticFiles mount for assets, app.mount for sub-applications); give mounted apps their own lifespan-free initialisation (or a shared resource passed in by the factory).

Middleware placement relative to routers Important ​

In plain words: Middleware wraps the whole app, not a router: it runs for every request, including 404s and requests to mounted apps' paths, before routing happens. The last middleware added is the outermost. Behaviour that should apply to only one router belongs in a router dependency, not in middleware.

Common misunderstanding: "I can add middleware to an APIRouter." Not in FastAPI 0.128.8 (the router has no add_middleware); the 0.137.0 notes list "Middleware per router" only under "Future Features Enabled". Per-router behaviour today is a router dependency.

Definition: FastAPI docs: "each new middleware wraps the application, forming a stack. The last middleware added is the outermost, and the first is the innermost. On the request path, the outermost middleware runs first." In the snippet the request-id middleware is added first and CORS last, so CORS is outermost: a preflight OPTIONS is answered by CORSMiddleware and never reaches the request-id middleware (test_cors_is_outermost_when_enabled: 200 with access-control-allow-origin and no x-request-id), while a normal 404 carries x-request-id (test_static_mount_and_middleware).

     app.add order: request_id (1st), CORSMiddleware (2nd)   -> stack from outside in:
1    ServerErrorMiddleware (Starlette, always outermost)
2    CORSMiddleware            preflight OPTIONS answered here (no x-request-id)
3    request_id middleware     adds x-request-id, x-process-time-ms (real: x-process-time-ms: 1.28)
4    ExceptionMiddleware       HTTPException -> JSON
5    Router                    /api/v1/..., /healthz, Mount /static, Mount /legacy
6    router dependencies       require_admin for /api/v1/admin/* only

Real scenario: request ids and access logs for every request (middleware); CORS for browsers (middleware, outermost); authentication only for the admin router (router dependency); GZip for large responses (middleware).

Want it forUseBecause
Every request, including 404MiddlewareRuns before routing
One routerRouter dependencyMiddleware cannot be scoped to a router (0.128.8)
One routeDecorator dependencyNarrowest
CORS preflightCORSMiddleware, added lastMust answer before anything else
Mounted app onlyThe mounted app's own middlewareSeparate stack

Fix / how to use it: add middleware in the factory in a deliberate order (CORS last), keep them cheap, and push anything router-specific into dependencies.

Tests mirroring packages: conftest placement Important ​

In plain words: Put the tests for shop/orders/ in tests/shop/orders/, the tests for shop/core/ in tests/shop/core/, and so on. Put each fixture in the conftest.py of the lowest folder that needs it: the settings fixture for everyone in tests/conftest.py, the app and client fixtures for the feature package in tests/shop/conftest.py. Then a test file shows which module it tests by where it is, and moving a feature moves its tests with it.

Common misunderstanding: "Test files in different folders may share a name." With pytest's default prepend import mode and no __init__.py, two test_router.py files collide; the snippet sets --import-mode=importlib, which pytest recommends: "For new projects, we recommend to use importlib import mode". Another one: "conftest fixtures are global." They are scoped by directory: "each directory can have its own conftest.py with its own fixtures, adding on to the ones provided by the conftest.py files in parent directories" (pytest docs), so tests/layered/ never sees the shop client fixture.

Definition: The snippet's test tree and fixture scopes:

1    tests/
2    ├── conftest.py                      autouse: clear SHOP_* env vars, get_settings.cache_clear(); fixture: settings
3    ├── before/test_before.py            the flat app's problems (5 tests)
4    ├── layered/test_layered.py          the layer-based package (2)
5    ├── shop/conftest.py                 app = create_app(settings), client (with TestClient), admin_headers
6    ├── shop/test_app.py                 OpenAPI organisation, hidden routes, mounts, middleware (7)
7    ├── shop/catalog/test_catalog_router.py   (3)     shop/orders/test_orders_router.py (2), test_orders_service.py (2, no HTTP)
8    ├── shop/core/test_settings.py (9, incl. the prod default-token refusal), test_lifespan.py (2)
9    ├── test_router_semantics.py         APIRouter rules on 0.128.8 (12)
10   └── test_layouts_equivalent.py       layered and shop publish the same operations (1)
11   real run: 45 passed, 2 warnings in 0.63s (the warnings are the Before app's on_event)

Real scenario: a feature team that owns shop/payments/ and tests/shop/payments/; a fixture that starts a PostgreSQL test database placed in tests/shop/conftest.py so the pure unit tests in another folder do not pay for it; CI that runs pytest tests/shop/orders for a change to shop/orders/.

FixturePlaced inUsed by
Clear env + settings cache (autouse)tests/conftest.pyEvery test
settingstests/conftest.pyAll packages
app, client, admin_headerstests/shop/conftest.pyShop tests only
Service-level dbtests/shop/orders/test_orders_service.pyThat file
Test database (PostgreSQL)The package conftest that needs itTesting FastAPI

Fix / how to use it: mirror the package, place fixtures at the narrowest folder, use --import-mode=importlib, build a fresh app per test from the factory, and test services without HTTP.

Mechanics ​

What include_router does, step by step (0.128.8 vs 0.137.0+) Important ​

In the pinned version APIRouter.include_router(router, prefix=..., tags=..., dependencies=..., responses=..., ...) is a loop that re-registers each route of the included router on the including one. Read from fastapi/routing.py at tag 0.128.8:

     self.include_router(router, prefix, tags, dependencies, responses, ...)
1    assert self is not router                               "Cannot include the same APIRouter instance into itself."
2    if prefix: assert prefix.startswith("/"), not prefix.endswith("/")
3    else: any route with an empty path -> FastAPIError("Prefix and path cannot be both empty ...")
4    for route in router.routes:                              the routes that exist NOW
5        APIRoute: self.add_api_route(prefix + route.path, route.endpoint,
                     tags = include tags + route tags, dependencies = include deps + route deps,
                     responses = {**include responses, **route.responses},
                     response_class = first of route / router default / include default / self default,
                     include_in_schema = route and self and include, deprecated = route or include or self,
                     generate_unique_id_function = first of route / router / include / self)
6        Starlette Route / WebSocket routes: re-added with the prefix
7    router.on_startup / on_shutdown handlers -> self.add_event_handler(...)
8    self.lifespan_context = _merge_lifespan_context(self.lifespan_context, router.lifespan_context)

The consequence is the "copy" semantics measured in Including routers: the parent ends up with new APIRoute objects, and the included router can be changed afterwards without effect. FastAPI 0.137.0 replaced this: "Before this, router.include_router(other_router) would take each path operation from other_router and 'clone' it … The way it is structured here is that there are a few additional classes to handle intermediate metadata for router and route inclusion", with the breaking change that "router.routes is no longer a plain list of APIRoute objects, it can contain these intermediate objects … forming a tree", and "router.routes should be considered an internal implementation detail". Code that walks app.routes to list endpoints works on 0.128.8 (the probe prints a flat list) and needs app.openapi()["paths"] instead on 0.137.0+.

How a request finds its route and its resources Good to know ​

     GET /api/v1/products/featured   (real run, uvicorn --factory)
1    Uvicorn                  scope built; await app(scope, receive, send)
2    ServerErrorMiddleware -> request_id middleware (CORS absent: no origins configured)
3    Router                   linear scan: docs routes, /api/v1/products (path mismatch), /api/v1/products/featured -> full match
4    route dependencies       include-level: none for catalog; router-level: none; parameter: repo(db=get_db(request))
5    get_db                   request.app.state.db  (set by the lifespan before the first request)
6    list_featured_products   def -> thread pool; ProductRepository.list(featured_only=True) runs the SELECT
7    response_model           list[ProductOut] -> JSON
8    middleware               x-request-id: 2ed3bd41..., x-process-time-ms: 1.28   -> 200 OK

Startup order inside one process Good to know ​

     uvicorn shop.asgi:app --workers 2   (real log, per worker)
1    import shop.asgi -> shop.main -> shop.api -> every feature router module (routes registered on the module routers)
2    create_app(): get_settings() (lru_cache miss -> Settings read once), FastAPI(...), include_router tree, mounts
3    Uvicorn sends lifespan.startup          "Waiting for application startup."
4    app lifespan (outer) -> catalog lifespan (inner, merged)
5    "Application startup complete."          printed twice: one per worker [31044], [31045]
6    SIGTERM to the parent: "Terminated child process" x2, each worker "Waiting for application shutdown." -> "Application shutdown complete."

Exact errors, warnings and log lines Must-know ​

Every line below was printed by the snippet run or a saved probe (FastAPI 0.128.8, Starlette 0.49.3, Pydantic 2.13.5, pydantic-settings 2.11.0, Uvicorn 0.39.0, CPython 3.9.6).

TriggerExact output
APIRouter(prefix="/items/")AssertionError: A path prefix must not end with '/', as the routes will start with '/'
include_router(r, prefix="items")AssertionError: A path prefix must start with '/'
r.include_router(r)AssertionError: Cannot include the same APIRouter instance into itself. Did you mean to include a different router?
@router.get("") included with no prefixFastAPIError: Prefix and path cannot be both empty (path operation: root)
Two routes with operation_id="read", on app.openapi()UserWarning: Duplicate Operation ID read for function read_b at …/p1_routers.py
/users/{user_id} router before /users/me router422 {"type":"int_parsing","loc":["path","user_id"],"msg":"Input should be a valid integer, unable to parse string as an integer","input":"me"}
Route added after include_router404 (0.128.8)
@app.on_event("startup")DeprecationWarning: on_event is deprecated, use lifespan event handlers instead.
Typo SHOP_DATABSE_URL in .env1 validation error for Settings / shop_databse_url / Extra inputs are not permitted [type=extra_forbidden, input_value='sqlite:///typo.db', input_type=str]
SHOP_ENVIRONMENT=prod without SHOP_ADMIN_TOKENValue error, SHOP_ADMIN_TOKEN must be set in prod (the default 'change-me' is public) [type=value_error, ...] (process exits)
SHOP_ENVIRONMENT=productionInput should be 'dev', 'test', 'staging' or 'prod' [type=literal_error, input_value='production', input_type=str]
SHOP_HTTP_TIMEOUT_S=60 (le=30)Input should be less than or equal to 30 [type=less_than_equal, input_value='60', input_type=str]
SHOP_CORS_ORIGINS=https://shop.example (not JSON)SettingsError: error parsing value for field "cors_origins" from source "EnvSettingsSource"
_secrets_dir="/run/secrets-missing"UserWarning: directory "/run/secrets-missing" does not exist
repr(settings)... admin_token=SecretStr('**********') ...
Circular import between two featuresImportError: cannot import name 'count_orders_for' from partially initialized module 'app.orders.service' (most likely due to a circular import)
from ...config import settings in app/orders/ImportError: attempted relative import beyond top-level package
python app/orders/script.py with a relative importImportError: attempted relative import with no known parent package
src layout, not installedModuleNotFoundError: No module named 'shopx'
Hidden admin route without token (curl)403; access log "GET /api/v1/admin/stats HTTP/1.1" 403 Forbidden
openapi_url=NoneGET /docs → 404 (curl, two workers)
Uvicorn, two workersStarted parent process [31039] … Application startup complete. ×2

Solving the classic problems ​

BugSymptomFixCost
Everything in main.py1,500 lines, merge conflictsRouters per feature, factory in main.pyAn afternoon
Prefix and tag on every decoratorTypos create a second docs group (Products)APIRouter(prefix=..., tags=[...])Minutes
Admin routes publicAnyone can call /admin/resetinclude_router(admin, dependencies=[Depends(require_admin)])One line
"Hidden" means "safe"Hidden route still callableHide and guardOne line
Literal route after parameter route (across routers)/users/me → 422Include specific routers firstOrdering
Routes added after include (≤ 0.136)New route 404s, no errorBuild router trees bottom-up in a functionRestructure
Long or colliding operationIdsUgly SDK names; Duplicate Operation ID warningTag + name generate_unique_id_function, one tag per versionOne function
Config read with os.environ.get"false" is truthy; ints as stringsBaseSettings with typesOne class
Settings at importTests cannot change them; import reads .env@lru_cache get_settings() + factorySmall
Connection opened at importTests open real connections; nothing closes themLifespan + app.state10 lines
on_event plus lifespanStartup handlers silently not calledMove everything into the lifespanSmall
Mounted app expects lifespanIts resources never initialisedPass resources in, or include instead of mountDesign
Circular imports between featuresImportError ... partially initialized module at startupOne-way dependencies, public service modulesDesign
Tests share one appOrder-dependent failurescreate_app(settings) per testSmall
Middleware for one routerRuns for everythingRouter dependencySmall

From one file to routers ​

Move each group of routes into <feature>/router.py with router = APIRouter(prefix=..., tags=[...]), remove the prefix and the tag from every decorator, and include the routers in a function called from the factory. Keep the path strings relative ("", /featured, /{product_id}). Run the route-table probe or app.openapi()["paths"] before and after: the set of (method, path) pairs must be identical, which is exactly what test_layouts_equivalent.py does for the two layouts.

Configuration you can trust ​

Replace every os.environ read with a field on one Settings class (types, Literal, Field constraints, SecretStr), give it a prefix, keep extra="forbid", inject it through @lru_cache get_settings(), and let the factory accept a Settings instance. The process now fails at startup with a clear validation error instead of at 3 a.m. on the first request that reads the bad value.

Resources with a lifetime ​

Everything that is expensive to create and safe to share (engine, pool, HTTP client, model) is created before yield in the lifespan and closed after it, stored on app.state and handed to routes through a dependency. Everything that belongs to one request (session, transaction, current user) is a yield dependency instead.

Boundaries that survive growth ​

Pick the layout deliberately (see Choosing), write down the import rules (features → core, orders → catalog.service, never back), make each feature's public module small, and check the rules in CI with an import linter once more than one team works in the codebase.

Choosing ​

SituationChooseWhy
< 10 routes, one personOne main.py (+ config.py)Structure costs more than it saves
A few resources, one teamBy technical layer (routers/, schemas/, ...)Familiar; tutorial and template shape
Many domains, several teamsBy feature (vertical slices) + core/Change stays in one folder; ownership
A router shared across projectsNo prefix/auth in the file; configure at include_routerReuse without edits
Auth for a groupRouter or include-level dependencyCannot be forgotten on a new route
Internal endpointsinclude_in_schema=False and a dependencyNot in SDKs, still protected
A separate app (legacy, GraphQL, metrics)app.mountOwn docs and stack
Front-end buildStaticFiles mount (dev) / app.frontend (0.138.0+) / CDN (prod)Low priority, cacheable
Breaking change for some endpointsv2 router for those endpoints onlyNo copy of the whole API
SettingsBaseSettings + lru_cache dependency + factory parameterTyped, once, overridable
SecretsSecret files (secrets_dir) or the environmentNot in .env on servers
Local defaults.env (ignored) + .env.example (committed)Onboarding without leaks
TestsMirror packages; conftest per folderLocality
Library or published packagesrc layoutTest what you ship
Single deployable serviceFlat layout + pythonpath = ["."]Less ceremony

When to switch from layers to features ​

Switch when two of these are true: a layer folder no longer fits on one screen; most pull requests touch three or more layer folders; two teams edit the same layer files; you are thinking about extracting a part of the system into its own service. The move is mechanical (one folder per feature, five files each, imports rewritten), and the layout-equivalence test is the safety net: the OpenAPI paths must not change.

Monorepo vs single service, and when to split services (link) ​

QuestionOne service, feature foldersSeveral services in one monorepoSeveral repositories
DeployOne unitIndependent units, shared toolingIndependent everything
Cross-feature callPython function (catalog.service.find_product)HTTP/gRPC/eventsHTTP/gRPC/events
Shared codecore/ packageA shared library package in the repoA published package
ConsistencyOne transactionSagas/outboxSagas/outbox
Start here whenAlmost alwaysTeams need independent deploysOrganisational boundaries

When to split services (link): the decision belongs to architecture, not to folder layout; feature folders with enforced boundaries are the precondition that makes a later split cheap. The trade-offs are in Modular Monolith and Clean & Hexagonal Architecture.

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

One FastAPI app built by create_app(), one lifespan opening one database pool and one HTTP client, routers per feature under /api/v1, settings from the environment. This chapter's shop/ is that shape with SQLite; in production the Database stand-in becomes a SQLAlchemy engine and the secrets come from /run/secrets. The route table is the API's map, the OpenAPI document its contract, and tests/ mirrors the packages.

Modular monolith and multiple databases ​

The same process, but the feature folders are treated as modules with enforced boundaries: each owns its tables (catalog owns products, orders owns orders), other modules call its public service.py and never its repository, and an import linter fails CI on a forbidden import. A second datastore (Redis for carts, a search index for the catalog) gets its own client in the lifespan, owned by the module that uses it (a router lifespan is a good home). This is the shape where by-feature layout pays off; Modular Monolith covers the architecture.

Microservices ​

Each extracted feature becomes its own FastAPI app with its own factory, settings prefix, lifespan and OpenAPI document; the cross-feature Python call becomes an HTTP call through an httpx.AsyncClient opened in the lifespan with a timeout from settings (http_timeout_s). The by-feature layout makes the move a folder move: shop/orders/ plus tests/shop/orders/ become orders-service/orders/ plus its tests, and catalog.service.find_product is replaced by a small client module with the same signature. Stable operationIds and tags matter more now, because other teams generate clients from your schema.

Distributed data: replicas, caches, sharded databases, multi-region ​

Everything on app.state is per process: with --workers 2 each worker ran its own lifespan (two "Application startup complete." lines) and would hold its own featured_ids cache. Shared state goes to Redis or PostgreSQL, reached through clients opened in the lifespan. Settings make topology configurable without code changes: a read-replica URL, a cache URL and a region name are fields, so the same image runs in every region with different environment variables. Per-region secrets arrive as files under the secrets directory. Caching and replica lag: Caching.

Scaling path: 1×, 10×, 100× ​

LoadWhat changesStructure practice
1× (one process, one team)Code grows past one fileRouters, factory, settings, lifespan; layers are fine
10× (several workers, several teams)Per-process state diverges; teams collide in layer foldersFeature folders, shared state in Redis/PostgreSQL, tag-based operationIds, import rules, CI-exported OpenAPI
100× (many services, many teams)Contracts between teams, independent deploysExtract features into services along existing folder boundaries; versioned routers; per-service settings prefixes; secrets from files; API Versioning

Lab ​

All commands run from docs/snippets/python/routers-project-structure/. Steps marked "real" were run on CPython 3.9.6 (macOS) with the pinned versions; outputs are copied from the saved transcripts.

1. Install and run the tests (real) ​

python3 -m venv ~/venvs/rps                     # the venv lives outside the repo
~/venvs/rps/bin/pip install '.[test]'           # pins from pyproject.toml (FastAPI 0.128.8, pydantic-settings 2.11.0 ...)
source ~/venvs/rps/bin/activate
export PYTHONDONTWRITEBYTECODE=1                 # no __pycache__ in the snippet tree; pyproject sets -p no:cacheprovider
python -m pytest -v
# tests/before/test_before.py .....                                        [ 11%]
# tests/layered/test_layered.py ..                                         [ 15%]
# tests/shop/catalog/test_catalog_router.py ...                            [ 22%]
# tests/shop/core/test_lifespan.py ..                                      [ 26%]
# tests/shop/core/test_settings.py .........                               [ 46%]
# tests/shop/orders/test_orders_router.py ..                               [ 51%]
# tests/shop/orders/test_orders_service.py ..                              [ 55%]
# tests/shop/test_app.py .......                                           [ 71%]
# tests/test_layouts_equivalent.py .                                       [ 73%]
# tests/test_router_semantics.py ............                              [100%]
# before/main.py:28  DeprecationWarning: on_event is deprecated, use lifespan event handlers instead.
# 45 passed, 2 warnings in 0.63s       <- both warnings are the Before app's on_event, on purpose

2. Run the factory with Uvicorn and call it (real) ​

SHOP_ADMIN_TOKEN=lab-token SHOP_ENVIRONMENT=staging uvicorn --factory shop.main:create_app --port 18931
curl -si http://127.0.0.1:18931/api/v1/products/featured
# HTTP/1.1 200 OK
# server: uvicorn
# content-type: application/json
# x-request-id: 2ed3bd41ef1740c69d83059c8601ed9a
# x-process-time-ms: 1.28
# [{"id":2,"sku":"GM-001","name":"Catan","price_cents":4500},{"id":3,"sku":"MU-001","name":"Kind of Blue (vinyl)","price_cents":2900}]
curl -s http://127.0.0.1:18931/version                 # {"app":"Shop API","environment":"staging"}
curl -s -o /dev/null -w "%{http_code}\n" http://127.0.0.1:18931/api/v1/admin/stats    # 403
curl -s -H "x-admin-token: lab-token" http://127.0.0.1:18931/api/v1/admin/stats
# {"orders":0,"lifespan_events":["startup","catalog:startup"]}
curl -s -X POST http://127.0.0.1:18931/api/v1/orders -H "content-type: application/json" -d '{"product_id":2,"quantity":2}'
# {"id":1,"product_id":2,"quantity":2,"total_cents":9000}
curl -s http://127.0.0.1:18931/api/v2/products/2
# {"id":2,"sku":"GM-001","name":"Catan","price":{"amount":"45.00","currency":"EUR"}}
curl -s http://127.0.0.1:18931/legacy/report           # {"lifespan_ran":false,"root_path":"/legacy"}

3. Read the OpenAPI organisation (real) ​

curl -s http://127.0.0.1:18931/openapi.json | python3 -c "import json,sys; d=json.load(sys.stdin); \
  print([t['name'] for t in d['tags']]); print(sorted(op['operationId'] for p in d['paths'].values() for op in p.values()))"
# ['catalog', 'orders', 'catalog-v2', 'meta']
# ['catalog-create_product', 'catalog-get_product', 'catalog-list_featured_products', 'catalog-list_products',
#  'catalog-v2-get_product', 'meta-version', 'orders-create_order', 'orders-get_order']
# (no /api/v1/admin/*, no /healthz, no /static or /legacy entries)

4. Two workers, production settings (real) ​

SHOP_ENVIRONMENT=prod SHOP_DOCS_ENABLED=false uvicorn shop.asgi:app --port 18933      # no token: refused
# pydantic_core._pydantic_core.ValidationError: 1 validation error for Settings
#   Value error, SHOP_ADMIN_TOKEN must be set in prod (the default 'change-me' is public) [type=value_error, ...]
SHOP_ENVIRONMENT=prod SHOP_DOCS_ENABLED=false SHOP_ADMIN_TOKEN=prod-lab-token uvicorn shop.asgi:app --workers 2 --port 18932
# INFO:     Started parent process [31039]
# INFO:     Started server process [31044]
# INFO:     Started server process [31045]
# INFO:     Application startup complete.          <- twice: one lifespan (and one settings read) per worker
# INFO:     Application startup complete.
curl -s -o /dev/null -w "%{http_code}\n" http://127.0.0.1:18932/docs     # 404 (openapi_url=None)
curl -s http://127.0.0.1:18932/version                                     # {"app":"Shop API","environment":"prod"}
curl -s -o /dev/null -w "%{http_code}\n" -H "x-admin-token: change-me" http://127.0.0.1:18932/api/v1/admin/stats   # 403

5. Break it on purpose (real probes, in a scratch copy) ​

# a) include a router, then add a route to it:   404, app.routes has only the docs routes   (runs/p1-output.txt)
# b) swap the order of two routers sharing /users: GET /users/me -> 422 int_parsing          (test_route_order_across_routers)
# c) make catalog import orders and orders import catalog:
#    ImportError: cannot import name 'count_orders_for' from partially initialized module 'app.orders.service'
# d) add SHOP_DATABSE_URL=... to .env:   ValidationError ... [type=extra_forbidden ...]
# e) set SHOP_ENVIRONMENT=production:   ValidationError ... [type=literal_error ...]

6. Run it on current FastAPI (expected, not run) ​

On Python 3.12 with fastapi>=0.137, at least test_routes_added_after_include_are_missing_on_0_128 and test_nested_router_must_be_complete_before_it_is_included are expected to fail, because routers stay live (the late route answers 200); other assertions pinned to 0.128.8 details (default operationIds, warning texts) may need updating too. fastapi run (from fastapi[standard]) is expected to find the app through [tool.fastapi] entrypoint = "shop.asgi:app". Neither was run here.

For PHP/Laravel developers ​

Laravel answers the same questions with conventions instead of objects. Route files are the routers: "All Laravel routes are defined in your route files, which are located in the routes directory. These files are automatically loaded by Laravel using the configuration specified in your application's bootstrap/app.php file." Laravel routes/api.php (the routes/api.php file) is the closest thing to an api_router with a prefix: "The routes in routes/api.php are stateless and are assigned to the api middleware group. Additionally, the /api URI prefix is automatically applied to these routes", changeable with apiPrefix: in withRouting(...). Route::prefix('admin')->middleware('auth')->group(...) is include_router(admin, prefix="/admin", dependencies=[...]); a new route file is registered in the then: closure of withRouting, the way a new feature router is added to build_api_router(). Controllers are where Laravel puts path operations; a single-action controller (__invoke) is one FastAPI path operation function. Service providers are the lifespan and the factory in one: "Service providers are the central place of all Laravel application bootstrapping", with register for container bindings and boot for everything else, registered in bootstrap/providers.php. The process model differs: under PHP-FPM a provider boots on every request, while a FastAPI lifespan runs once per worker (Laravel Octane brings Laravel close to that). Configuration is the other big parallel: Laravel's .env "can be overridden by external environment variables such as server-level or system-level environment variables" (the same priority as pydantic-settings), values are strings so the docs cast them ('debug' => (bool) env('APP_DEBUG', false)), and after php artisan config:cache "your application's .env file will not be loaded by the framework during requests", which is the lru_cache on get_settings() taken to deployment. Laravel's default app/ tree (Http, Models, Providers) is a by-layer layout; feature folders (app/Domain/Orders/...) are a community convention there too.

php
// bootstrap/app.php (Laravel 13): the factory, the route tree and the API prefix
return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        api: __DIR__.'/../routes/api.php',           // include_router(api_router, prefix="/api")
        apiPrefix: 'api',
        then: function () {                          // another router file, like admin.router at include time
            Route::middleware(['api', 'auth:sanctum', 'can:admin'])   // dependencies=[Depends(require_admin)]
                ->prefix('api/v1/admin')                              // prefix="/admin" under /api/v1
                ->group(base_path('routes/admin.php'));
        },
    )->create();

// routes/api.php: the v1 tree; one controller per feature (shop/catalog/router.py, shop/orders/router.py)
Route::prefix('v1')->group(function () {
    Route::get('/products/featured', [ProductController::class, 'featured']);   // literal before {product}
    Route::get('/products/{product}', [ProductController::class, 'show']);
    Route::post('/orders', StoreOrderController::class);                         // single-action controller (__invoke)
});

// config/shop.php: typed config read once (php artisan config:cache), like get_settings()
return ['timeout' => (float) env('SHOP_HTTP_TIMEOUT_S', 2.0), 'docs' => (bool) env('SHOP_DOCS_ENABLED', true)];
Laravel 13FastAPI
Laravel routes/api.php with the automatic /api prefixapp.include_router(api_router, prefix="/api")
Route::prefix('v1')->group(...)APIRouter(prefix="/v1") + include_router
->middleware('auth') on a groupinclude_router(r, dependencies=[Depends(auth)])
Route file registered in withRouting(then: ...)build_api_router() adds a feature router
Controllers (resource, single-action __invoke)Path operation functions in router.py
Service providers (register, boot), bootstrap/providers.phpcreate_app() + lifespan
Service container bindingsDepends(...) providers, app.state resources
.env + config/*.php + env().env + BaseSettings
php artisan config:cache@lru_cache get_settings()
Environment variables override .envSame in pydantic-settings
Encrypted env files in source controlSecret files under secrets_dir
app/Http, app/Models (by layer)routers/, models/ (by layer)
Domain folders (app/Domain/Orders)shop/orders/ (by feature)
php artisan route:listapp.routes / /openapi.json
tests/Feature, tests/Unittests/shop/<feature>/, service tests without HTTP

The Go angle ​

The Go twin of this chapter is Go Project Layout, Linting & Build. Go's official layout guide gives the server shape that the by-feature package mirrors: "Server projects typically won't have packages for export, since a server is usually a self-contained binary … it's recommended to keep the Go packages implementing the server's logic in the internal directory. Moreover, since the project is likely to have many other directories with non-Go files, it's a good idea to keep all Go commands together in a cmd directory." The Go package layout cmd internal pkg is often quoted as a trio, but the official guide only describes cmd/ and internal/; pkg/ is a community convention for code meant to be imported by other modules. Two differences matter. Boundaries are enforced by the compiler: a package under internal/ "cannot be imported outside this module", and import cycles are a compile error, where Python finds a cycle only at runtime (ImportError ... partially initialized module) and has no internal rule (import-linter fills the gap). The factory and the lifespan are just main(): there is no framework lifespan; cmd/api/main.go reads config into a struct, opens the pool, builds the router (a ServeMux per feature, mounted with http.StripPrefix or a sub-router), serves, and closes resources after srv.Shutdown(ctx).

go
// cmd/api/main.go: config -> resources -> routes -> serve -> shutdown (create_app + lifespan in one function)
func main() {
	cfg := config.MustLoad()              // like Settings(): env vars into a typed struct, fail fast
	db := store.MustOpen(cfg.DatabaseURL) // lifespan, before yield
	defer db.Close()                      // lifespan, after yield

	api := http.NewServeMux()
	catalog.Register(api, catalog.NewService(db))            // internal/catalog: router + service + repository
	orders.Register(api, orders.NewService(db, catalog.API)) // orders depends on catalog's exported API only
	root := http.NewServeMux()
	root.Handle("/api/v1/", http.StripPrefix("/api/v1", api)) // include_router(v1, prefix="/api/v1")
	root.Handle("/static/", http.FileServer(http.Dir("static")))

	srv := &http.Server{Addr: cfg.Addr, Handler: requestID(root)} // middleware wraps everything, like FastAPI
	go func() { _ = srv.ListenAndServe() }()
	stop := make(chan os.Signal, 1)
	signal.Notify(stop, syscall.SIGTERM, os.Interrupt)
	<-stop
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	_ = srv.Shutdown(ctx)
}
ConcernFastAPIGo
Group of routesAPIRouterA ServeMux or a Register(mux) function per package
Prefixprefix= / include_router(prefix=)http.StripPrefix or pattern prefixes
Group authRouter dependencyMiddleware wrapping that sub-mux
App factorycreate_app(settings)run(cfg) error called from main
Lifespanasynccontextmanager + yielddefer and srv.Shutdown(ctx) in main
SettingsBaseSettings, env vars, .env, secret filesStruct + env parsing (stdlib or a library)
Feature foldersshop/orders/internal/orders/
Boundary enforcementConvention + import-linterinternal/ rule + compiler
Import cyclesRuntime ImportErrorCompile error
Entry pointshop/asgi.py, [tool.fastapi] entrypointcmd/api/main.go

Common misconceptions ​

BeliefReality
An APIRouter is a separate appIts routes join the app's single route table and OpenAPI document; mount makes separate apps
Routes added to a router after include_router are servedNot before 0.137.0: routes are copied at include time (404 measured)
Routers are matched by prefix, then insideOne flat, ordered table; the first match wins across routers
Duplicate routes across routers raise an errorThe first wins silently
A prefix may end with /AssertionError: A path prefix must not end with '/'
Router tags replace route tagsThey are concatenated: include tags, then route tags
include_in_schema=False protects a routeIt hides it; protection is a dependency
FastAPI rejects duplicate operationIdsIt warns (UserWarning) when the schema is built
Middleware can be attached to one routerNot in 0.128.8; use a router dependency
on_event and lifespan can be combinedWith lifespan= the event handlers are not called
A mounted app gets the parent's lifespanOnly the top-level app gets lifespan events
TestClient(app) runs the lifespanOnly inside with TestClient(app)
.env overrides environment variablesEnvironment variables win over .env, .env over secret files
A typo in .env is ignoredextra="forbid" (the default) raises extra_forbidden
bool(os.environ["DEBUG"]) works"false" is truthy; parse with a typed Settings field
Settings() in a dependency is fineWithout lru_cache it re-reads .env on every request
Changing an env var at runtime updates settingsNot until get_settings.cache_clear()
By-feature layout has no layersEach feature contains the layers, one file each
Folders enforce module boundariesOnly tools (import-linter) or review do in Python
Relative imports work in scriptsattempted relative import with no known parent package; use python -m
src layout is requiredRecommended for packages and installed-copy testing; flat works for a service
app.state is shared between workersEach worker process has its own state and its own lifespan

Cheat sheet ​

TopicRemember
Routerrouter = APIRouter(prefix="/products", tags=["catalog"], responses={404: ...})
Includeapp.include_router(r, prefix=..., tags=..., dependencies=[...], include_in_schema=...)
NestingBuild bottom-up: v1.include_router(child) before app.include_router(v1) (copy semantics ≤ 0.136)
PrefixStarts with /, never ends with /; @router.get("") serves the prefix itself
OrderFirst match wins across all routers; include specific routers first
Dependenciesapp → include → router → decorator → parameters
Responses{**include_responses, **route.responses}; route wins
operationIdgenerate_unique_id_function=lambda r: f"{r.tags[0]}-{r.name}"; one tag per version
Docsopenapi_tags=[...], include_in_schema=False, openapi_url=None per environment
Factorycreate_app(settings=None) -> FastAPI; asgi.py: app = create_app(); uvicorn --factory
Lifespan@asynccontextmanager + yield; resources on app.state; request.app.state
Router lifespanAPIRouter(lifespan=...) nested inside the app's; mounts get none
SettingsBaseSettings + SettingsConfigDict(env_prefix=, env_file=, extra="forbid")
Priorityinit > env > .env (later file wins) > secrets dir > default
Settings dependency@lru_cache def get_settings(); Annotated[Settings, Depends(get_settings)]
LayoutSmall: by layer. Many domains/teams: by feature + core/
ImportsRelative inside a feature, absolute across; one-way dependencies
Mountapp.mount("/static", StaticFiles(...)), app.mount("/legacy", sub_app)
MiddlewareLast added = outermost; CORS last
Teststests/ mirrors packages; conftest per folder; --import-mode=importlib

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — What is the difference between app.include_router(router) and app.mount("/x", other_app)? Must-know ​

Answer

Answer: include_router adds the router's path operations to the app's own route table: they share the app's middleware, exception handlers, lifespan, dependencies and OpenAPI document ("The APIRouters are not 'mounted', they are not isolated from the rest of the application"). mount attaches a completely independent ASGI app under a path: it has its own routes, its own /x/docs and /x/openapi.json, receives a root_path, and gets no lifespan events. Use include for features of your API, mount for separate apps and StaticFiles. See Mounts and sub-applications.

2 — You include a /users/{user_id} router and then a /users/me router. What happens on GET /users/me, and how do you fix it? Must-know ​

Answer

Answer: After inclusion there is one ordered route table, and the first match wins; /users/{user_id} matches first, so user_id="me" fails int parsing and the client gets 422 int_parsing (measured). Include the router with the literal path first, or keep both in one router with the literal declared first. Duplicate method+path pairs across routers are also silent: the first wins. See Route order across routers.

3 — How do you require an admin token for every route of a router you are not allowed to edit? Must-know ​

Answer

Answer: Pass the dependency at include time: app.include_router(admin.router, prefix="/admin", tags=["admin"], dependencies=[Depends(require_admin)], responses={403: {...}}). It runs before every route of that router in this app only, and the file stays reusable. Hiding it with include_in_schema=False is optional and does not protect anything by itself. The order of execution is app, include, router, decorator, then parameter dependencies. See Router dependencies.

4 — Why use an app factory instead of a module-level app = FastAPI()? Must-know ​

Answer

Answer: A factory builds the app when called, with the settings it is given, so tests get a fresh, independent app per test (create_app(test_settings)), importing the package has no side effects, and different configurations (docs off, CORS on) are one argument away. Servers call it through uvicorn --factory shop.main:create_app or a tiny asgi.py that does app = create_app(). See The app factory.

5 — Where do you open a database engine and an HTTP client, and how does a route reach them? Must-know ​

Answer

Answer: In the lifespan: an @asynccontextmanager function passed as FastAPI(lifespan=...); create them before yield, close them after it (in finally), and store them on app.state. A route reaches them through request.app.state or, better, through a small dependency (get_db(request)). It runs once per worker process, only inside with TestClient(app) in tests, and never for mounted apps; with lifespan= set, on_event handlers are not called. See Lifespan.

6 — SHOP_APP_NAME is set in the environment, in .env and in /run/secrets/shop_app_name. Which value does Settings() use? Important ​

Answer

Answer: The environment variable. pydantic-settings' priority, highest first: initialiser arguments, environment variables, dotenv files (later files override earlier ones), the secrets directory, then field defaults. So .env is a local convenience that real deployment variables override, and secret files are the fallback for secrets. The snippet's test_priority_env_over_dotenv_over_secrets checks each step. See Settings sources.

7 — Why wrap get_settings() in @lru_cache, and what does that mean for tests? Important ​

Answer

Answer: Without it, every request that depends on settings creates a new Settings and re-reads the environment and the .env file. With it, settings are built once per process and behave like a global that can still be replaced: tests use app.dependency_overrides[get_settings] (or pass Settings to the factory) and call get_settings.cache_clear() between tests, because a changed environment variable is invisible to a cached object. See The Settings dependency.

8 — Layer-based or feature-based layout: when do you choose which? Important ​

Answer

Answer: By technical layer (routers/ schemas/ models/ services/ repositories/) for small services with one team: familiar, matches the tutorial and the full-stack template. By feature (catalog/, orders/, each a vertical slice, plus core/) once there are many domains or several teams: a change stays in one folder, ownership is clear, boundaries can be enforced and a feature can later become a service. Switch when layer folders overflow and most changes touch three or more of them. See Choosing.

9 — Your SDK has methods called getProductApiV1ProductsProductIdGet. How do you fix that without breaking uniqueness? Important ​

Answer

Answer: Pass a generate_unique_id_function to FastAPI that builds the id from the first tag and the function name (f"{route.tags[0]}-{route.name}"), tag every route, and give a second version its own tag (catalog-v2) so get_product in v1 and v2 stays unique. FastAPI only warns (UserWarning: Duplicate Operation ID ...) when ids collide, so keep a test that all operationIds are unique. See operationId.

10 — orders/service.py imports catalog/service.py, and catalog/service.py imports orders/service.py. What fails and how do you fix it? Important ​

Answer

Answer: Importing either module fails at startup with ImportError: cannot import name ... from partially initialized module ... (most likely due to a circular import): the first module is registered in sys.modules before its names exist. Fix the design, not the symptom: make dependencies one-way (orders → catalog's public service), move shared code into core/, or invert the call (catalog publishes data, orders consumes it). Use relative imports inside a feature and absolute imports across features. See Imports and circular imports.

11 — You call @router.get("/late") after app.include_router(router). Why does /late return 404 on FastAPI 0.128.8 but 200 on 0.140? Good to know ​

Answer

Answer: Up to 0.136, include_router copied each existing route into the parent (self.add_api_route(prefix + route.path, ...) in a loop), so later additions never reach the app. 0.137.0 (2026-06-14) refactored routing "to preserve APIRouter and APIRoute instances": routers are stored, not copied, so routes added later are visible and router.routes becomes a tree. Code that must work on both builds router trees bottom-up. See Mechanics.

12 — How should the tests of a feature-based package be laid out, and where do the fixtures go? Good to know ​

Answer

Answer: Mirror the package: tests/shop/catalog/, tests/shop/orders/, tests/shop/core/, with --import-mode=importlib so files in different folders may share names. Put each fixture in the conftest.py of the lowest folder that needs it (pytest scopes conftest fixtures by directory): environment cleanup and settings in tests/conftest.py, the app and client in tests/shop/conftest.py. Build a fresh app per test from the factory and test services without HTTP. See Tests mirroring packages.

Glossary ​

TermMeaning
APIRouterFastAPI class grouping path operations with shared prefix, tags, dependencies, responses; a "mini FastAPI"
include_routerMethod that adds a router's routes to an app or router, combining prefixes, tags, dependencies, responses
Nested routersRouters included into routers (api → v1 → catalog)
prefixPath segment prepended to every route of a router or include call
tagsOpenAPI grouping labels; docs sections and SDK service classes
Router dependenciesdependencies=[...] on a router or include call, run before every route
Router responsesresponses={...} documented on every route of a router
default_response_classResponse class used by routes that do not set their own
include_in_schemaFlag that removes a route, router or include from OpenAPI (not from routing)
Route orderThe rule that the first registered matching route handles a request
Path conflictTwo routes for the same method and path; the first wins silently
operationIdUnique OpenAPI identifier of an operation; SDK method names come from it
generate_unique_id_functionCallable APIRoute -> str that builds operationIds
openapi_tags / tags metadataList of tag dicts (name, description, externalDocs) passed to FastAPI
App factoryFunction (create_app) that builds and returns a configured app
Entry pointThe import string a server or CLI uses (shop.asgi:app, [tool.fastapi] entrypoint)
--factoryUvicorn flag: call the named function to get the app
LifespanAsync context manager around the app's life: startup before yield, shutdown after
asynccontextmanagercontextlib decorator turning a one-yield async generator into an async context manager
Startup / shutdownThe two ASGI Lifespan Protocol events
app.stateAttribute bag on the app instance for process-wide resources
request.appThe app that is handling a request; request.app.state reaches its resources
Lifespan stateDict yielded by a lifespan; a shallow copy appears as request.state
Router lifespanAPIRouter(lifespan=...), nested inside the including app's lifespan (0.112.2+)
on_eventDeprecated startup/shutdown hooks; ignored when lifespan= is set
pydantic-settingsPackage providing BaseSettings (separate from Pydantic since v2)
BaseSettingsPydantic model filled from init args, env vars, dotenv files, secret files, defaults
SettingsConfigDictTyped dict for model_config of a settings class
env_prefixPrefix for environment variable names (SHOP_)
env_fileDotenv file(s) to read, relative to the working directory
secrets_dirDirectory with one file per value; file name = variable name
SecretStrPydantic type that hides its value in repr and logs
extra="forbid"Settings default: unknown keys in dotenv files are a validation error
lru_cachefunctools decorator caching results; makes get_settings() run once
Settings dependencyDepends(get_settings), overridable in tests
Per-environment configValues that differ by environment, from env vars or .env.<env> files
Twelve-factor config"Store config in the environment" (factor III)
By technical layerLayout with one folder per layer: routers, schemas, models, services, repositories
By featureLayout with one folder per business capability (vertical slice)
Vertical sliceA feature folder containing all its layers
Module boundaryThe rule about which modules may import which (public surface only)
Router (layer)HTTP adapter: request in, status code out
ServiceBusiness rules and domain errors, no HTTP
RepositoryData access (SQL), no business rules
Schema vs modelPydantic API shape vs persistence (ORM) shape
__init__.pyFile that makes a directory a regular package; executed on import
Namespace packagePackage without __init__.py (PEP 420)
Relative importfrom .x import y / from ..x import y (PEP 328)
Circular importTwo modules importing each other; fails on a partially initialised module
src layoutImport packages under src/; requires installation to import
Flat layoutImport packages next to pyproject.toml
app.mountAttach an independent ASGI app or StaticFiles under a path
Sub-applicationA separate FastAPI app mounted in another; own docs, no lifespan
StaticFilesStarlette ASGI app serving files from a directory
root_pathASGI scope value telling a mounted or proxied app its external path prefix
Middleware orderLast added = outermost; runs for every request before routing
conftest.pypytest file whose fixtures apply to its directory and below
--import-mode=importlibpytest import mode allowing same-named test files in different folders
FastAPI / Starlette / PydanticThe framework, the ASGI toolkit it subclasses, the validation library
Uvicorn / httpx / pytestThe ASGI server, the HTTP client (also behind TestClient), the test runner
SQLAlchemy / SQLModel / AlembicThe ORM, the Pydantic-flavoured ORM layer and the migration tool of later chapters
eval-type-backportPackage letting Pydantic evaluate X | None on Python 3.9

References ​

Built by Morteza Negahi