Routers, Settings and Application Lifespan
Grow the reading list into a proper application: routes grouped into an APIRouter, typed settings from environment variables, shared resources created and released in a lifespan function, and CORS for the browser.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: typed settings that fail at startup
- Step 2: shared resources in a lifespan
- Step 3: books move into a router
- Step 4: let the browser in with CORS
- Step 5: tests that run the real lifespan
- Troubleshooting
- Check your understanding
- Apply it: stretch tasks
- Review prompt
Lessons of FastAPI Fundamentals
- From Function to Endpoint: Path Operations Concept · 15 min
- Lab: A CRUD Resource Held in Memory Lab · 30 min
- Validating Input and Shaping Output with Pydantic Worked example · 25 min
- Dependencies: Sharing Resources Without Globals Worked example · 20 min
- Routers, Settings and Application Lifespan Lab · 25 min
- Check: Trace a Request Through the App Knowledge check · 8 questions
What you will learn
- Organize an application into routers, with typed settings loaded from environment variables and startup and shutdown handled in a lifespan function.
Prerequisites: HTTP & APIs
01. Goal and setup
Everything so far has lived in one file, with values such as the maximum page size written into the code. This lab gives the reading list the shape a real service grows into: routes for one resource grouped in their own module behind an APIRouter; configuration read from environment variables into a typed settings object; and one shared store created when the application starts and released when it stops, inside a lifespan function. A CORS middleware finishes the picture, so a browser front end may call the API.
You need: the environment from the CRUD lab, plus one package: uv pip install pydantic-settings==2.16.3. Everything below was verified with Python 3.12, FastAPI 0.163.1, Pydantic 2.14.3 and pydantic-settings 2.16.3.
The project grows a package layout:
readinglist-app/
├── .env local settings, never committed
├── app/
│ ├── main.py lifespan, CORS, include_router
│ ├── config.py Settings (pydantic-settings)
│ ├── state.py ReadingIndex + state dependencies
│ └── routers/
│ └── books.py every /books route, one prefix
└── tests/
└── test_app.py tests that run the real lifespan02. Step 1: typed settings that fail at startup
Configuration differs per environment — the page cap, an admin token for later admin routes — so it belongs outside the code. A BaseSettings class reads environment variables into typed, validated fields. An env_prefix keeps them namespaced, and env_file lets a local .env carry the development values. Save the .env with the values below and add it to .gitignore: it holds a secret stand-in.
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(
env_prefix='READINGLIST_',
env_file='.env',
env_file_encoding='utf-8',
)
app_name: str = 'Reading List'
max_page_size: int = 50
admin_token: strREADINGLIST_APP_NAME=Reading List
READINGLIST_MAX_PAGE_SIZE=20
READINGLIST_ADMIN_TOKEN=change-mepython -c "from app.config import Settings; Settings(_env_file=None)"
# simulates a fresh machine with no .env and no exported variablespydantic_core._pydantic_core.ValidationError: 1 validation error for Settings
admin_token
Field required [type=missing, input_value={}, input_type=dict]
For further information visit https://errors.pydantic.dev/2.14/v/missingThis is the payoff of typed settings: a missing or malformed value stops the application at startup, with the field named, instead of failing at 3 a.m. inside the one route that reads it. A deployment misconfiguration becomes a boot failure you see immediately. The class validates types too — set READINGLIST_MAX_PAGE_SIZE=lots and the app refuses to start rather than paging with a string.
03. Step 2: shared resources in a lifespan
The store so far was a dictionary at module level. The lifespan gives it a proper home: a function decorated with @asynccontextmanager, where everything before yield runs once at startup and everything after runs once at shutdown. Objects created here are hung on app.state, and small dependency functions hand them to routes. This is also where pooled clients that must not be rebuilt per request belong — an HTTP client for calling other services, later a database engine.
from fastapi import Request
from app.config import Settings
class ReadingIndex:
def __init__(self, settings: Settings) -> None:
self.settings = settings
self._books: dict[int, dict] = {}
self._next_id = 1
def add(self, book: dict) -> dict:
record = {'id': self._next_id, **book}
self._books[self._next_id] = record
self._next_id += 1
return record
def search(self, q: str, limit: int) -> dict:
hits = [b for b in self._books.values()
if q.lower() in b['title'].lower()]
return {'count': len(hits), 'items': hits[:limit]}
def get(self, book_id: int) -> dict | None:
return self._books.get(book_id)
def close(self) -> int:
saved = len(self._books)
self._books.clear()
return saved
def get_settings(request: Request) -> Settings:
return request.app.state.settings
def get_index(request: Request) -> ReadingIndex:
return request.app.state.indexfrom collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from fastapi import FastAPI
from app.config import Settings
from app.state import ReadingIndex
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
settings = Settings()
app.state.settings = settings
app.state.index = ReadingIndex(settings)
app.state.index.add({'title': 'Refactoring', 'author': 'Fowler'})
print(f'startup: {settings.app_name} ready')
yield
saved = app.state.index.close()
print(f'shutdown: {saved} books released')
app = FastAPI(title='Reading List API', lifespan=lifespan)
@app.get('/healthz', tags=['ops'])
def healthz():
return {'status': 'ok'}uvicorn app.main:app --port 8078INFO: Started server process [1916982]
INFO: Waiting for application startup.
startup: Reading List ready
INFO: Application startup complete.
INFO: Uvicorn running on http://127.0.0.1:8078 (Press CTRL+C to quit)INFO: Shutting down
INFO: Waiting for application shutdown.
shutdown: 1 books released
INFO: Application shutdown complete.
INFO: Finished server process [1916982]Both prints come from the lifespan, and they bracket every request the app will ever serve. On shutdown the store reports one book — the one seeded at startup. If the process is killed without a chance to shut down, the after-yield code may not run, which is why production services keep durable data in a database rather than process memory; the lifespan closes connections politely, it does not guarantee a delivery.
04. Step 3: books move into a router
With resources on app.state, the routes themselves become a folder of modules. APIRouter is a miniature route table with its own prefix, tags and dependencies; include_router mounts it into the application. Each route below is the same path operation you have written all along — only router replaces app, and the /books prefix is declared once.
from typing import Annotated
from fastapi import APIRouter, Depends, HTTPException, Query
from pydantic import BaseModel, Field
from app.config import Settings
from app.state import ReadingIndex, get_index, get_settings
router = APIRouter(prefix='/books', tags=['books'])
class BookIn(BaseModel):
title: str = Field(min_length=1, max_length=200)
author: str = Field(min_length=1, max_length=100)
def page_limit(
settings: Annotated[Settings, Depends(get_settings)],
limit: Annotated[int, Query(ge=1)] = 10,
) -> int:
return min(limit, settings.max_page_size)
@router.post('', status_code=201)
def create_book(book: BookIn,
index: Annotated[ReadingIndex, Depends(get_index)]):
return index.add(book.model_dump())
@router.get('')
def list_books(limit: Annotated[int, Depends(page_limit)],
index: Annotated[ReadingIndex, Depends(get_index)],
q: str = ""):
result = index.search(q, limit)
return {**result, 'applied_limit': limit}
@router.get('/{book_id}')
def get_book(book_id: int,
index: Annotated[ReadingIndex, Depends(get_index)]):
book = index.get(book_id)
if book is None:
raise HTTPException(status_code=404, detail='book not found')
return bookfrom app.routers.books import router as books_router
app.include_router(books_router)Note how the settings flow: get_settings reads the object placed on app.state at startup, page_limit mixes the query string with max_page_size, and no route knows where the number came from. Returning applied_limit in the body makes the cap visible to clients — and to you, in the next step.
for u in 'q=refac' 'limit=50'; do
curl -s "http://127.0.0.1:8078/books?$u" | python -c \
'import json,sys; d=json.load(sys.stdin); print(d["count"], d["applied_limit"])'
done
curl -s http://127.0.0.1:8078/openapi.json | python -c \
"import json, sys; s = json.load(sys.stdin); \
ops = [o for p in s['paths'].values() for o in p.values()]; \
tags = sorted({t for o in ops for t in o.get('tags', [])}); \
print('tags:', tags); print('paths:', sorted(s['paths']))"1 10
1 20
tags: ['books', 'ops']
paths: ['/books', '/books/{book_id}', '/healthz']The first request used the default page size of 10; the second asked for 50 and received applied_limit: 20 — the value from .env, applied inside a dependency, invisible to the handler. The generated document confirms the structure: the book routes grouped under the books tag and the /books prefix, the health check under ops. Open /docs and the same grouping greets you as collapsible sections.
05. Step 4: let the browser in with CORS
A page served from http://localhost:5173 (a typical front-end dev server) may not, by default, read responses from your API: the browser’s same-origin policy blocks the response even though the server happily sent it. The CORSMiddleware answers the browser’s preflight checks and marks allowed origins. Middleware wraps the whole application — every router, every route — and this one takes a list of allowed origins:
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=['http://localhost:5173'],
allow_methods=['GET', 'POST'],
)curl -s -i -H "Origin: http://localhost:5173" \
http://127.0.0.1:8078/healthz | grep -iE "^(HTTP|access-control)"
curl -s -i -H "Origin: http://evil.example" \
http://127.0.0.1:8078/healthz | grep -iE "^(HTTP|access-control)"HTTP/1.1 200 OK
access-control-allow-origin: http://localhost:5173
HTTP/1.1 200 OKBoth requests reached the server and both returned 200 — CORS is enforced by the browser, not the server. The difference is the response header: for the allowed origin the middleware echoes it, telling the browser the page may read the body; for the unknown origin no CORS header is sent, so a browser page from there still cannot read the response. Note that allow_origins=["*"] would allow any origin and should never be combined with credentials; listing exact origins, as here, is the disciplined default.
06. Step 5: tests that run the real lifespan
The tests use the same TestClient as before, with one addition that now matters: entering it with with runs the lifespan, so app.state is populated exactly as in production. The fixture also sets environment variables for the test process, keeping tests independent of any real .env. pytest captures anything the tests print; running it with -rP replays that captured output for passed tests, which is how you will see the lifespan prints.
import pytest
from fastapi.testclient import TestClient
from app.config import Settings
from app.main import app
@pytest.fixture()
def client(monkeypatch):
monkeypatch.setenv('READINGLIST_ADMIN_TOKEN', 'test-token')
monkeypatch.setenv('READINGLIST_MAX_PAGE_SIZE', '2')
with TestClient(app) as test_client:
yield test_client
def test_lifespan_loaded_a_book(client):
listed = client.get('/books', params={'q': 'refactoring'})
assert listed.status_code == 200
assert listed.json()['count'] == 1
def test_settings_cap_applies(client):
for n in range(5):
client.post('/books', json={'title': f'Book {n}', 'author': 'Anon'})
listed = client.get('/books', params={'limit': 50})
assert len(listed.json()['items']) == 2
def test_missing_setting_fails_fast():
with pytest.raises(Exception) as excinfo:
Settings(_env_file=None)
assert 'admin_token' in str(excinfo.value)python -m pytest tests/ -rPtests/test_app.py ... [100%]
==================================== PASSES ====================================
_________________________ test_settings_cap_applies ____________________________
---------------------------- Captured stdout setup -----------------------------
startup: Reading List ready
--------------------------- Captured stdout teardown ---------------------------
shutdown: 6 books released
============================== 3 passed in 0.68s ==============================The captured prints prove the lifespan ran: startup before the requests, shutdown after. The second test created five books and asked for 50, and got 2 items — the environment variable set in the fixture, not the 20 from .env, decided the cap. Each test enters and leaves the client’s context manager, so each gets a fresh store; six books were released at its shutdown (one seeded plus five created).
07. Troubleshooting
08. Check your understanding
09. Apply it: stretch tasks
Finish the shape of a real service:
- Add a
membersrouter with its own prefix, tags and two routes, and mount it; check that/docsshows a third group. - Replace the printed seed message with a
logging.getLogger(__name__).info(...)call, and find the line in uvicorn’s output. - Make
.envoptional in a fresh deployment: givemax_page_sizean environment-specific value in a.env.testfile and pointSettingsConfigDictat it from the test fixture. Then read API design before the next skill shapes how these URLs should look to clients.
10. Review prompt
Without looking back: what runs before the yield of a lifespan function, what runs after, and how often does each happen? Why do routes receive resources through request.app.state rather than imports? Which file and naming rule turns a setting into an environment variable, and when does a bad value surface? Finally, explain who enforces CORS and what the middleware actually changes in a response.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.