Routers, dependencies, settings and lifespan
Wire settings, a shared HTTP client and a database pool through dependencies and the lifespan handler.
By Invicly Tech, , in FastAPI with Python for AI Backends. About 11 minutes to read.
In short
As an app grows you split routes into APIRouter modules and give them what they need through dependencies declared with Depends. Settings come from the environment through a typed settings class, and expensive shared objects such as an HTTP client or database pool are created once in the lifespan handler and closed on shutdown. Because everything arrives through dependencies, tests can swap in fakes without touching route code.
Think of it like this: Dependencies are like a hotel's room service: the route asks for a towel or a coffee by name, and the hotel decides where it comes from, so a test hotel can hand over a fake one.
Explained simply
A small FastAPI app can live in one file. A real service quickly grows: document routes, question routes, health checks, admin tools. APIRouter lets you put each group in its own file and plug it into the main app with a shared prefix like /v1/documents.
Most routes need things: settings, a database session, an HTTP client, the current user. Instead of creating them inside each route, you declare them as dependencies with Depends. FastAPI calls the dependency function and passes the result in. This is called dependency injection.
Settings, such as a database URL or an API key, come from environment variables. A settings class from pydantic-settings reads them once, checks their types and refuses to start if something required is missing. That is much safer than finding out at 2 a.m. when the first request fails.
Some things are expensive to create, like a pool of database connections. You make them once when the app starts and close them when it stops. FastAPI's lifespan function is the place for that. And because routes only ask for dependencies, tests can swap in fakes easily.
Press Play on a diagram to walk through it one step at a time.
- 1main.py
Creates FastAPI(lifespan=...) and includes routers
- 2Routers
APIRouter per area: documents, questions, health
- 3Dependencies
get_settings, get_http_client, get_session, get_current_user
- 4Services
Plain classes with business logic, no FastAPI imports
- 5Shared resources
HTTP client and DB pool opened in lifespan
- get_current_user
- reads Authorization header
- get_settings for issuer and audience
- get_session
- session from the pool on app.state
- closed after the response
- get_model_provider
- get_http_client from app.state
- get_settings for model name and timeout
- get_settings
- built once with lru_cache
- shared by every branch in this request
In depth
Splitting routes with APIRouter
Create one router per area in its own module: router = APIRouter(prefix="/v1/documents", tags=["documents"]). Add routes to it exactly as you would to the app, then mount it in main.py with app.include_router(documents.router). The prefix keeps paths consistent, tags group routes in /docs, and router-level dependencies run for every route in that router, which is ideal for authentication on a whole area.
You can also pass a prefix and dependencies to include_router, which helps when one router is mounted twice, for example under /v1 and /v2 during a migration. Keep routers thin: they parse input, call a service, and shape the output. Business logic lives in plain service classes that do not import FastAPI, so you can reuse and test them anywhere.
- APIRouter(prefix=..., tags=[...], dependencies=[...])
- app.include_router(router)
- Router-level dependencies guard a whole area
- Keep routers thin, services plain
Depends in practice
A dependency is any callable: a function, an async function or a class. FastAPI inspects its parameters too, so a dependency can take query parameters, headers or other dependencies. Within one request each dependency runs once and its result is reused, so get_settings asked for by three dependencies is called a single time.
A dependency that uses yield can clean up after the request: open a database session, yield it, and close it after the response work is done. Write the type once with Annotated and reuse it: SessionDep = Annotated[AsyncSession, Depends(get_session)] lets every route write session: SessionDep. Dependencies are also how you express policy, for example a require_role("admin") factory that returns a dependency checking the current user.
- Function, async function or class
- Results cached once per request
- yield for setup and cleanup
- Annotated aliases keep signatures short
Loading settings from the environment
Install pydantic-settings and define class Settings(BaseSettings) with typed fields: database_url: str, model_timeout_s: float = 30.0, provider_api_key: SecretStr. Set model_config = SettingsConfigDict(env_prefix="APP_", env_file=".env") and the class reads APP_DATABASE_URL and friends from the environment, falling back to a local .env file during development.
Wrap creation in a function decorated with @lru_cache so it is built once, and expose it as a dependency. If a required variable is missing or has the wrong type, a validation error is raised the first time settings load; call get_settings() in lifespan so that happens at startup. SecretStr hides the value in logs and reprs; call get_secret_value() only where the key is used. Never commit .env files; in production inject variables from a secret manager.
Startup and shutdown with lifespan
The lifespan function is an async context manager passed to FastAPI(lifespan=lifespan). Code before yield runs once per worker process, before the first request: load settings, create the HTTP client, create the database engine, warm caches. Code after yield runs on shutdown: close clients, dispose of the engine, flush telemetry.
Store the shared objects on app.state, or yield a dict of state that Starlette exposes on request.state, and read them through small dependencies. On shutdown Uvicorn first stops accepting new connections and lets in-flight requests finish, bounded by --timeout-graceful-shutdown if you set it, and then the lifespan exit code runs. Each Uvicorn worker is its own process, so each one runs lifespan and gets its own pool; size pools with that in mind.
- Uvicorn to Lifespan: Startup: enter lifespan1Startup: enter lifespan
- Lifespan to Shared resources: Load settings, open HTTP client and DB pool2Load settings, open HTTP client and DB pool
- Lifespan to Uvicorn: yield: ready for traffic3yield: ready for traffic
- Routes to Shared resources: Requests borrow client and sessions via dependencies4Requests borrow client and sessions via dependencies
- Uvicorn to Lifespan: Shutdown: in-flight requests done, exit lifespan5Shutdown: in-flight requests done, exit lifespan
- Lifespan to Shared resources: aclose client, dispose engine6aclose client, dispose engine
Swapping dependencies in tests
Because routes never build their own clients, a test can replace any dependency: app.dependency_overrides[get_model_provider] = lambda: FakeProvider(). Every route that depends on get_model_provider, directly or through another dependency, now gets the fake. Clear the overrides after each test, for example with app.dependency_overrides.clear() in a fixture, so tests do not leak into each other.
Use TestClient as a context manager, with TestClient(app) as client, to run the lifespan, so startup and shutdown code is tested too. When lifespan opens real connections you do not want in unit tests, have it read settings that point at local services, or keep lifespan small and override the dependencies that hand out those resources.
Learn it in 5 short steps
About 35m each. Track them with a timer in your plan.
- 1Split routes with APIRouter~35m
- 2Inject services with Depends~35m
- 3Load settings from the environment~35m
- 4Open shared clients at startup~35m
- 5Close them cleanly on shutdown~35m
Key points
- APIRouter groups related routes with a shared prefix, tags and dependencies; app.include_router mounts them.
- Depends lets FastAPI build an argument for you, and dependencies can depend on other dependencies.
- A pydantic-settings class reads and validates environment variables once, so bad config fails at startup.
- Open shared clients and pools in the lifespan function before yield and close them after it.
- app.dependency_overrides replaces any dependency in tests with a fake.
Key terms
Tap a card to flip it. 0/5 known
Examples
from contextlib import asynccontextmanager
import httpx
from fastapi import Depends, FastAPI, Request
@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.http = httpx.AsyncClient(timeout=10.0)
yield
await app.state.http.aclose()
app = FastAPI(lifespan=lifespan)
def get_http(request: Request) -> httpx.AsyncClient:
return request.app.state.http
@app.get("/v1/upstream")
async def upstream(http: httpx.AsyncClient = Depends(get_http)) -> dict: ...One client for the whole process, handed to routes through a dependency.
Typed settings with a cached dependency
Settings reads APP_DATABASE_URL, APP_PROVIDER_API_KEY and an optional APP_MODEL_TIMEOUT_S. Start the app without APP_DATABASE_URL and it stops with a validation error naming the missing field, which is the evidence you want: bad config fails fast. Routes receive settings through the SettingsDep alias, and a test can override get_settings with different values.
from functools import lru_cache
from typing import Annotated
from fastapi import Depends
from pydantic import SecretStr
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_prefix="APP_", env_file=".env")
database_url: str
provider_api_key: SecretStr
model_timeout_s: float = 30.0
@lru_cache
def get_settings() -> Settings:
return Settings()
SettingsDep = Annotated[Settings, Depends(get_settings)]A database pool opened at startup, one session per request
The engine owns the connection pool and is created once in lifespan, then disposed on shutdown. get_session is a yield dependency: each request gets its own session from the pool, and the async with block closes it afterwards even if the route raised. pool_size and max_overflow bound how many connections one worker can open. The persistence module builds on this.
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
@asynccontextmanager
async def lifespan(app: FastAPI):
engine = create_async_engine(get_settings().database_url, pool_size=5, max_overflow=5)
app.state.sessions = async_sessionmaker(engine, expire_on_commit=False)
yield
await engine.dispose()
async def get_session(request: Request):
async with request.app.state.sessions() as session:
yield sessionQuick reference
- router = APIRouter(prefix="/v1/documents", tags=["documents"]); app.include_router(router).
- def route(x: Annotated[T, Depends(get_x)]) or x: T = Depends(get_x).
- Dependencies run once per request; yield dependencies clean up afterwards.
- pydantic-settings: BaseSettings + SettingsConfigDict(env_prefix="APP_", env_file=".env").
- @lru_cache on get_settings builds settings once; SecretStr hides keys in logs.
- FastAPI(lifespan=lifespan): open before yield, close after yield.
- One pool per worker process: total connections = workers x (pool_size + max_overflow).
- app.dependency_overrides[dep] = fake; clear it after each test.
Common mistakes
- Creating a new HTTP client or database engine inside every request, which wastes connections.
- Reading os.environ all over the code instead of one validated settings object.
- Using the old on_event startup and shutdown hooks; lifespan replaces them, and on_event handlers are ignored once lifespan is set.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Move a GET /v1/documents route from main.py into app/routes/documents.py using an APIRouter with prefix /v1/documents and tag documents, and include it in the app.
- Exercise 2medium
Write a dependency require_api_key that reads the X-API-Key header, compares it with a key from settings, and raises 401 if it does not match. Apply it to a whole router.
- Exercise 3hard
Write a pytest test that runs the app's lifespan, overrides get_model_provider with a fake that always answers stub, calls POST /v1/questions and checks the answer. Make sure the override is removed afterwards.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Is @app.on_event("startup") still OK?
- It is deprecated. Use the lifespan parameter instead; once you set lifespan, on_event startup and shutdown handlers are not called.
- Should I put the database session on app.state?
- No. Put the engine or session factory on app.state, and create one session per request in a yield dependency. Sessions are not safe to share between concurrent requests.
- Do I need a dependency injection library?
- Usually not. FastAPI's Depends covers per-request wiring, and lifespan covers process-wide resources. Plain constructor arguments handle the rest inside services.
- Should .env files be used in production?
- Avoid it. Use .env for local development only, keep it out of Git, and inject real values as environment variables from your platform's secret manager.