Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Lab · 25 min · revision 2

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

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:

Project 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 lifespan

02. 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.

Python · app/config.py
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: str
Text · .env
READINGLIST_APP_NAME=Reading List
READINGLIST_MAX_PAGE_SIZE=20
READINGLIST_ADMIN_TOKEN=change-me
Terminal · what happens with the variable missing
python -c "from app.config import Settings; Settings(_env_file=None)"
# simulates a fresh machine with no .env and no exported variables
Expected output (traceback trimmed)
pydantic_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/missing

This 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.

Python · app/state.py
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.index
Python · app/main.py
from 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'}
Terminal 1 · run from the project root (any free port works)
uvicorn app.main:app --port 8078
Expected output (your process id differs)
INFO:     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)
Expected output (after pressing Ctrl+C; your process id differs)
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.

Python · app/routers/books.py
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 book
Python · app/main.py (mounting the router)
from 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.

Terminal 2 · with the server running again
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']))"
Expected output
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:

Python · app/main.py (before include_router)
from fastapi.middleware.cors import CORSMiddleware

app.add_middleware(
    CORSMiddleware,
    allow_origins=['http://localhost:5173'],
    allow_methods=['GET', 'POST'],
)
Terminal 2 · same request, two different origins
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)"
Expected output
HTTP/1.1 200 OK
access-control-allow-origin: http://localhost:5173
HTTP/1.1 200 OK

Both 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.

Python · tests/test_app.py
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)
Terminal 1
python -m pytest tests/ -rP
Illustrative output (trimmed, one test PASSES section omitted; the time differs per run)
tests/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

Practice check · 3 questions

Wiring of the finished app

Answer from the app you just assembled.

Q1. A route needs the ReadingIndex that the lifespan created at startup. How does it get it?
Q2. With env_prefix READINGLIST_, which environment variable sets the maximum page size?
Q3. In a test, TestClient(app) is created without with and a request is sent to GET /books. What happens?
Practice only: not graded, not saved, not evidence.

09. Apply it: stretch tasks

Finish the shape of a real service:

  1. Add a members router with its own prefix, tags and two routes, and mount it; check that /docs shows a third group.
  2. Replace the printed seed message with a logging.getLogger(__name__).info(...) call, and find the line in uvicorn’s output.
  3. Make .env optional in a fresh deployment: give max_page_size an environment-specific value in a .env.test file and point SettingsConfigDict at 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.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check