FastAPI Basics
This chapter derives a modern HTTP API from typed route signatures, Pydantic v2 schemas, dependency graphs, lifespan-managed resources, and correctly scoped background work.
- Explain Path operations & routing by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Pydantic models by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Dependency injection by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Background tasks by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain HTTP & OpenAPI contract by naming its input, guarantee, internal lifecycle, important failure, and proof.
How to use this chapter
For FastAPI Basics, read the explanations first and predict every example before running it. Keep a learning repository containing code, tests, command output, and the short written submission. The roadmap checklist at the end audits coverage; the chapter itself follows the framework learning arc appropriate to this subject.
The problem this chapter solves
This chapter derives a modern HTTP API from typed route signatures, Pydantic v2 schemas, dependency graphs, lifespan-managed resources, and correctly scoped background work.
It minimizes translation between type declarations, runtime validation, documentation, and handler code while remaining close to the ASGI protocol.
Learning outcomes
- Explain Path operations & routing by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Pydantic models by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Dependency injection by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Background tasks by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain HTTP & OpenAPI contract by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Trace the chapter's complete execution path and identify where memory, I/O, concurrency, persistence, or rendering cost accumulates.
- Build the worked example, make one failure visible, and defend the design in a review.
Chapter progression
The order below is intentional: later sections depend on guarantees established earlier.
Runtime or system overview
At startup FastAPI constructs route and dependency metadata. For a request, Starlette matches the route, FastAPI extracts values, resolves dependencies recursively, validates input with Pydantic Core, invokes the endpoint, serializes the response, and returns ASGI messages. Async endpoints run on the event loop; synchronous endpoints are delegated to a thread pool. In FastAPI Basics, use that execution model to decide where the chapter's validation, state ownership, cleanup, and evidence belong.
Execution trace
- At startup Starlette registers routes and FastAPI compiles dependency, validation, response-model, and OpenAPI metadata from Python signatures.
- For the request, Starlette matches method and path; FastAPI extracts path, query, header, cookie, and body values and Pydantic validates them.
- Dependencies resolve in graph order, yielding request-scoped resources; the async endpoint runs on the event loop and awaits non-blocking database or network I/O.
- The response model filters and serializes output; exceptions follow registered handlers; yielded dependencies unwind and close or roll back resources.
- Tests verify the HTTP or WebSocket contract plus durable state, authorization, cleanup, cancellation, and bounded latency under concurrent work.
Memory and performance lens
Each in-flight coroutine retains its frame and referenced data but does not require an operating-system thread. Large request bodies, response models, unbounded queues, or per-request clients defeat this advantage. Pools for database and HTTP connections must be bounded and shared through lifespan state. For FastAPI Basics, connect those costs to the concrete operations in the topic sections rather than assuming the friendly surface syntax is cheap.
When tuning FastAPI Basics, measure request p50/p95/p99, validation failures, database query count, pool saturation, response size, and error rate by contract rather than optimizing from source-code appearance.
1. Path operations & routing
The Path operations & routing unit begins with @app.get/post/put/delete/patch decorators: A FastAPI path operation binds one HTTP method and path template to a typed handler, with parameters classified as path, query, header, cookie, body, or dependencies. Group routes with APIRouter, order static paths before conflicting dynamic paths, and declare response models and status codes explicitly. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The framework contract: Path operations & routing
| Concept | Meaning | Engineering decision |
|---|---|---|
| @app.get/post/put/delete/patch decorators | A FastAPI path operation binds one HTTP method and path template to a typed handler, with parameters classified as path, query, header, cookie, body, or dependencies. | Group routes with APIRouter, order static paths before conflicting dynamic paths, and declare response models and status codes explicitly. |
| path params + type validation | A FastAPI path operation binds one HTTP method and path template to a typed handler, with parameters classified as path, query, header, cookie, body, or dependencies. | Group routes with APIRouter, order static paths before conflicting dynamic paths, and declare response models and status codes explicitly. |
| query params (optional/required/aliases) | A FastAPI path operation binds one HTTP method and path template to a typed handler, with parameters classified as path, query, header, cookie, body, or dependencies. | Group routes with APIRouter, order static paths before conflicting dynamic paths, and declare response models and status codes explicitly. |
| APIRouter for modular routing | A FastAPI path operation binds one HTTP method and path template to a typed handler, with parameters classified as path, query, header, cookie, body, or dependencies. | Group routes with APIRouter, order static paths before conflicting dynamic paths, and declare response models and status codes explicitly. |
Follow the request through the framework: Path operations & routing
@app.get/post/put/delete/patch decorators. At startup FastAPI inspects the signature and builds validation/OpenAPI metadata. At request time Starlette resolves the route, Pydantic converts parameters, dependencies execute, and the response model filters/serializes output.
path params + type validation. At startup FastAPI inspects the signature and builds validation/OpenAPI metadata. At request time Starlette resolves the route, Pydantic converts parameters, dependencies execute, and the response model filters/serializes output.
query params (optional/required/aliases). At startup FastAPI inspects the signature and builds validation/OpenAPI metadata. At request time Starlette resolves the route, Pydantic converts parameters, dependencies execute, and the response model filters/serializes output.
APIRouter for modular routing. At startup FastAPI inspects the signature and builds validation/OpenAPI metadata. At request time Starlette resolves the route, Pydantic converts parameters, dependencies execute, and the response model filters/serializes output.
Read these as one system: @app.get/post/put/delete/patch decorators establishes the starting contract, path params + type validation changes how that contract is executed or represented, and APIRouter for modular routing exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
A focused implementation slice: Path operations & routing
1@router.get("/{item_id}", response_model=ItemRead)2async def read_item(item_id: UUID, service: Service = Depends(get_service)): ...This Path operations & routing slice makes @app.get/post/put/delete/patch decorators observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward APIRouter for modular routing, predict its behavior for empty, invalid, repeated, and large input.
Where production applications break: Path operations & routing
| Risk | Why it matters |
|---|---|
| @app.get/post/put/delete/patch decorators | A decorator registers the function; defining two identical method/path combinations silently creates an ambiguous or unreachable contract. |
| path params + type validation | A decorator registers the function; defining two identical method/path combinations silently creates an ambiguous or unreachable contract. |
| query params (optional/required/aliases) | A decorator registers the function; defining two identical method/path combinations silently creates an ambiguous or unreachable contract. |
| APIRouter for modular routing | A decorator registers the function; defining two identical method/path combinations silently creates an ambiguous or unreachable contract. |
Framework lab: Path operations & routing
- Foundation: implement or demonstrate @app.get/post/put/delete/patch decorators with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine @app.get/post/put/delete/patch decorators with path params + type validation. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for APIRouter for modular routing. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
2. Pydantic models
The Pydantic models unit begins with BaseModel + Field() (min_length/max_length/ge/le/regex): Pydantic models parse untrusted input into typed values and serialize explicit output contracts. Separate create, update, internal, and public schemas. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The framework contract: Pydantic models
| Concept | Meaning | Engineering decision |
|---|---|---|
| BaseModel + Field() (min_length/max_length/ge/le/regex) | Pydantic models parse untrusted input into typed values and serialize explicit output contracts. | Separate create, update, internal, and public schemas. |
| @field_validator (Pydantic v2) | Pydantic models parse untrusted input into typed values and serialize explicit output contracts. | Separate create, update, internal, and public schemas. |
| model inheritance | Python objects combine identity, state, and behavior; inheritance and protocols define substitution relationships. | Prefer composition or small protocols; use inheritance for a genuine substitutable abstraction. |
| from_attributes (orm_mode) | Pydantic models parse untrusted input into typed values and serialize explicit output contracts. | Separate create, update, internal, and public schemas. |
| nested models | Pydantic models parse untrusted input into typed values and serialize explicit output contracts. | Separate create, update, internal, and public schemas. |
Follow the request through the framework: Pydantic models
BaseModel + Field() (min_length/max_length/ge/le/regex). Pydantic v2 compiles a Core Schema evaluated by pydantic-core. Field validation precedes model-level invariants; from_attributes reads object attributes.
@field_validator (Pydantic v2). Pydantic v2 compiles a Core Schema evaluated by pydantic-core. Field validation precedes model-level invariants; from_attributes reads object attributes.
model inheritance. Attribute lookup walks the instance, its class, and the class MRO. super() follows that computed MRO, enabling cooperative multiple inheritance when signatures agree.
from_attributes (orm_mode). Pydantic v2 compiles a Core Schema evaluated by pydantic-core. Field validation precedes model-level invariants; from_attributes reads object attributes.
nested models. Pydantic v2 compiles a Core Schema evaluated by pydantic-core. Field validation precedes model-level invariants; from_attributes reads object attributes.
Read these as one system: BaseModel + Field() (min_length/max_length/ge/le/regex) establishes the starting contract, @field_validator (Pydantic v2) changes how that contract is executed or represented, and nested models exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
A focused implementation slice: Pydantic models
1class ItemCreate(BaseModel):2 name: str = Field(min_length=1, max_length=120)This Pydantic models slice makes BaseModel + Field() (min_length/max_length/ge/le/regex) observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward nested models, predict its behavior for empty, invalid, repeated, and large input.
Where production applications break: Pydantic models
| Risk | Why it matters |
|---|---|
| BaseModel + Field() (min_length/max_length/ge/le/regex) | Validation can coerce values unless strictness is configured; never expose secrets through a broad response model. |
| @field_validator (Pydantic v2) | Validation can coerce values unless strictness is configured; never expose secrets through a broad response model. |
| model inheritance | Direct parent calls break cooperative MRO and deep hierarchies create fragile coupling. |
| from_attributes (orm_mode) | Validation can coerce values unless strictness is configured; never expose secrets through a broad response model. |
| nested models | Validation can coerce values unless strictness is configured; never expose secrets through a broad response model. |
Framework lab: Pydantic models
- Foundation: implement or demonstrate BaseModel + Field() (min_length/max_length/ge/le/regex) with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine BaseModel + Field() (min_length/max_length/ge/le/regex) with @field_validator (Pydantic v2). Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for nested models. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
3. Dependency injection
The Dependency injection unit begins with Depends() + sub-dependencies: FastAPI dependency injection declares request-scoped prerequisites and resource lifecycles as a graph rather than hiding them inside handlers. Use dependencies for authentication, validated policy, units of work, and request resources; use lifespan state for process-wide clients and pools. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The framework contract: Dependency injection
| Concept | Meaning | Engineering decision |
|---|---|---|
| Depends() + sub-dependencies | FastAPI dependency injection declares request-scoped prerequisites and resource lifecycles as a graph rather than hiding them inside handlers. | Use dependencies for authentication, validated policy, units of work, and request resources; use lifespan state for process-wide clients and pools. |
| class-based dependencies | FastAPI dependency injection declares request-scoped prerequisites and resource lifecycles as a graph rather than hiding them inside handlers. | Use dependencies for authentication, validated policy, units of work, and request resources; use lifespan state for process-wide clients and pools. |
| DB session yield pattern | FastAPI dependency injection declares request-scoped prerequisites and resource lifecycles as a graph rather than hiding them inside handlers. | Use dependencies for authentication, validated policy, units of work, and request resources; use lifespan state for process-wide clients and pools. |
| current user dep with JWT | FastAPI dependency injection declares request-scoped prerequisites and resource lifecycles as a graph rather than hiding them inside handlers. | Use dependencies for authentication, validated policy, units of work, and request resources; use lifespan state for process-wide clients and pools. |
| Lifespan events | FastAPI dependency injection declares request-scoped prerequisites and resource lifecycles as a graph rather than hiding them inside handlers. | Use dependencies for authentication, validated policy, units of work, and request resources; use lifespan state for process-wide clients and pools. |
Follow the request through the framework: Dependency injection
Depends() + sub-dependencies. FastAPI resolves each dependency and its sub-dependencies in topological order, caches results per request by default, and unwinds yield dependencies for deterministic cleanup after response handling.
class-based dependencies. FastAPI resolves each dependency and its sub-dependencies in topological order, caches results per request by default, and unwinds yield dependencies for deterministic cleanup after response handling.
DB session yield pattern. FastAPI resolves each dependency and its sub-dependencies in topological order, caches results per request by default, and unwinds yield dependencies for deterministic cleanup after response handling.
current user dep with JWT. FastAPI resolves each dependency and its sub-dependencies in topological order, caches results per request by default, and unwinds yield dependencies for deterministic cleanup after response handling.
Lifespan events. FastAPI resolves each dependency and its sub-dependencies in topological order, caches results per request by default, and unwinds yield dependencies for deterministic cleanup after response handling.
Read these as one system: Depends() + sub-dependencies establishes the starting contract, class-based dependencies changes how that contract is executed or represented, and Lifespan events exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
A focused implementation slice: Dependency injection
1async def get_session():2 async with session_factory() as session:3 yield sessionThis Dependency injection slice makes Depends() + sub-dependencies observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward Lifespan events, predict its behavior for empty, invalid, repeated, and large input.
Where production applications break: Dependency injection
| Risk | Why it matters |
|---|---|
| Depends() + sub-dependencies | A generator dependency is a lifecycle boundary, not an ordinary lazy iterator; sharing sessions across requests or concurrent tasks corrupts transaction ownership. |
| class-based dependencies | A generator dependency is a lifecycle boundary, not an ordinary lazy iterator; sharing sessions across requests or concurrent tasks corrupts transaction ownership. |
| DB session yield pattern | A generator dependency is a lifecycle boundary, not an ordinary lazy iterator; sharing sessions across requests or concurrent tasks corrupts transaction ownership. |
| current user dep with JWT | A generator dependency is a lifecycle boundary, not an ordinary lazy iterator; sharing sessions across requests or concurrent tasks corrupts transaction ownership. |
| Lifespan events | A generator dependency is a lifecycle boundary, not an ordinary lazy iterator; sharing sessions across requests or concurrent tasks corrupts transaction ownership. |
Framework lab: Dependency injection
- Foundation: implement or demonstrate Depends() + sub-dependencies with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine Depends() + sub-dependencies with class-based dependencies. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for Lifespan events. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
4. Background tasks
The Background tasks unit begins with BackgroundTasks.add_task(): BackgroundTasks schedules small in-process work after the response; Celery provides externally queued, retryable, independently scalable work. Use BackgroundTasks for best-effort, short work and a durable queue for business-critical jobs. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The framework contract: Background tasks
| Concept | Meaning | Engineering decision |
|---|---|---|
| BackgroundTasks.add_task() | BackgroundTasks schedules small in-process work after the response; Celery provides externally queued, retryable, independently scalable work. | Use BackgroundTasks for best-effort, short work and a durable queue for business-critical jobs. |
| async vs sync background tasks | FastAPI background tasks run after the response has been prepared in the same application process; synchronous callables use a worker thread and asynchronous callables run on the event loop. | Use them for short, best-effort work such as a small audit write; use a durable queue for important, slow, retryable, or independently scalable jobs. |
| when to use Celery instead | BackgroundTasks schedules small in-process work after the response; Celery provides externally queued, retryable, independently scalable work. | Use BackgroundTasks for best-effort, short work and a durable queue for business-critical jobs. |
Follow the request through the framework: Background tasks
BackgroundTasks.add_task(). Background tasks share the server process and are lost if it terminates. Celery serializes work to a broker with worker acknowledgments.
async vs sync background tasks. Starlette stores background callables on the response and executes them after sending the body. They are not brokered, do not survive process loss, and still consume the server's resources.
when to use Celery instead. Background tasks share the server process and are lost if it terminates. Celery serializes work to a broker with worker acknowledgments.
Read these as one system: BackgroundTasks.add_task() establishes the starting contract, async vs sync background tasks changes how that contract is executed or represented, and when to use Celery instead exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
A focused implementation slice: Background tasks
1@router.post("/backgroundtasks_add_task", status_code=202)2async def backgroundtasks_add_task(payload: InputModel, service: Service = Depends(get_service)) -> OutputModel:3 result = await service.execute(payload)4 return OutputModel.model_validate(result)This Background tasks slice makes BackgroundTasks.add_task() observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward when to use Celery instead, predict its behavior for empty, invalid, repeated, and large input.
Where production applications break: Background tasks
| Risk | Why it matters |
|---|---|
| BackgroundTasks.add_task() | Returning a response does not guarantee an in-process background task completed. |
| async vs sync background tasks | Putting CPU-heavy or durable business work in an async background function can block the loop or disappear during deployment. |
| when to use Celery instead | Returning a response does not guarantee an in-process background task completed. |
Framework lab: Background tasks
- Foundation: implement or demonstrate BackgroundTasks.add_task() with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine BackgroundTasks.add_task() with async vs sync background tasks. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for when to use Celery instead. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
5. HTTP & OpenAPI contract
The HTTP & OpenAPI contract unit begins with status codes and response_model: A FastAPI route's status code states the HTTP outcome, while response_model validates, filters, serializes, and documents the public response shape. Declare precise success statuses and response schemas, including created/accepted/no-content behavior, and document typed error responses separately. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The framework contract: HTTP & OpenAPI contract
| Concept | Meaning | Engineering decision |
|---|---|---|
| status codes and response_model | A FastAPI route's status code states the HTTP outcome, while response_model validates, filters, serializes, and documents the public response shape. | Declare precise success statuses and response schemas, including created/accepted/no-content behavior, and document typed error responses separately. |
| OpenAPI schema generation and docs | FastAPI derives an OpenAPI document from route metadata, parameter locations, security dependencies, and Pydantic request/response schemas. | Treat the generated document as a versioned contract: set operation IDs/tags/descriptions, review diffs in CI, and test client generation for important changes. |
| request body vs path/query/header/cookie parameters | FastAPI separates values by HTTP location: path identifies the routed resource, query selects or paginates, headers carry metadata, cookies carry scoped browser state, and the body contains the representation or command payload. | Choose locations from HTTP semantics, give aliases and bounds explicitly, and avoid putting secrets or large structured data in URLs. |
| exception handlers and error schemas | Exception handlers translate typed application or infrastructure failures into stable HTTP statuses, machine-readable codes, safe messages, and correlation metadata. | Define a small error envelope, map expected domain failures centrally, preserve causes in logs, and never expose stack traces or secrets to clients. |
Follow the request through the framework: HTTP & OpenAPI contract
status codes and response_model. FastAPI passes the returned value through the declared response type and Pydantic serialization, excluding undeclared fields and raising a server-side validation error if the implementation violates its own contract.
OpenAPI schema generation and docs. At application startup or first schema access, FastAPI walks registered routes and component models, assigns schema references, and serves the result to Swagger UI or ReDoc.
request body vs path/query/header/cookie parameters. The dependency solver extracts each declared location, converts values through type adapters/Pydantic, aggregates validation errors, and invokes the endpoint only after required inputs succeed.
exception handlers and error schemas. Starlette searches the exception-handler registry as an error unwinds. The handler builds a response; middleware still applies according to placement, while unhandled failures reach the server's 500 path and telemetry.
Read these as one system: status codes and response_model establishes the starting contract, OpenAPI schema generation and docs changes how that contract is executed or represented, and exception handlers and error schemas exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
A focused implementation slice: HTTP & OpenAPI contract
1@router.post("/status_codes_and_response_model", status_code=202)2async def status_codes_and_response_model(payload: InputModel, service: Service = Depends(get_service)) -> OutputModel:3 result = await service.execute(payload)4 return OutputModel.model_validate(result)This HTTP & OpenAPI contract slice makes status codes and response_model observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward exception handlers and error schemas, predict its behavior for empty, invalid, repeated, and large input.
Where production applications break: HTTP & OpenAPI contract
| Risk | Why it matters |
|---|---|
| status codes and response_model | Returning ORM or dictionary data without an explicit response contract can leak internal fields and let implementation drift reach clients. |
| OpenAPI schema generation and docs | A generated schema can still be wrong when handlers return undocumented errors, mutate responses manually, or hide behavior in dependencies. |
| request body vs path/query/header/cookie parameters | Moving the same value between body and query is a breaking contract change, and sensitive query values can leak through logs, history, and referrers. |
| exception handlers and error schemas | Catching every exception and returning 200 or 400 erases retry semantics and hides defects from monitoring. |
Framework lab: HTTP & OpenAPI contract
- Foundation: implement or demonstrate status codes and response_model with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine status codes and response_model with OpenAPI schema generation and docs. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for exception handlers and error schemas. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
Complete worked example
This example integrates the chapter rather than demonstrating an isolated method.
1from contextlib import asynccontextmanager2from fastapi import APIRouter, Depends, FastAPI, status3from pydantic import BaseModel, Field, HttpUrl4
5class LinkCreate(BaseModel):6 url: HttpUrl7 alias: str | None = Field(default=None, pattern=r"^[a-z0-9-]{4,32}$")8
9class LinkRead(BaseModel):10 code: str11 url: HttpUrl12
13router = APIRouter(prefix="/links", tags=["links"])14
15@router.post("", response_model=LinkRead, status_code=status.HTTP_201_CREATED)16async def create_link(body: LinkCreate, service=Depends(get_link_service)):17 return await service.create(body)18
19@asynccontextmanager20async def lifespan(app: FastAPI):21 app.state.http = build_http_client()22 yield23 await app.state.http.aclose()Expected result
1POST /links validates the URL and alias, resolves the service dependency, and returns 201.Line-by-line reading
| Line | Code | Explanation | |
|---|---|---|---|
| 1 | from contextlib import asynccontextmanager | Imports the named dependency; import executes the module once per interpreter cache and binds selected names here. | |
| 2 | from fastapi import APIRouter, Depends, FastAPI, status | Imports the named dependency; import executes the module once per interpreter cache and binds selected names here. | |
| 3 | from pydantic import BaseModel, Field, HttpUrl | Imports the named dependency; import executes the module once per interpreter cache and binds selected names here. | |
| 5 | class LinkCreate(BaseModel): | Creates a class namespace and binds the resulting class object to this name. | |
| 6 | url: HttpUrl | Implements the next python statement in the example's data flow. | |
| 7 | `alias: str \ | None = Field(default=None, pattern=r"^[a-z0-9-]{4,32}$")` | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 9 | class LinkRead(BaseModel): | Creates a class namespace and binds the resulting class object to this name. | |
| 10 | code: str | Implements the next python statement in the example's data flow. | |
| 11 | url: HttpUrl | Implements the next python statement in the example's data flow. | |
| 13 | router = APIRouter(prefix="/links", tags=["links"]) | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. | |
| 15 | @router.post("", response_model=LinkRead, status_code=status.HTTP_201_CREATED) | Applies a decorator or framework annotation before the following definition is bound. | |
| 16 | async def create_link(body: LinkCreate, service=Depends(get_link_service)): | Defines a coroutine function; calling it creates a coroutine object and await drives its execution. | |
| 17 | return await service.create(body) | Starts or resumes asynchronous I/O and yields control until the awaited operation completes. | |
| 19 | @asynccontextmanager | Applies a decorator or framework annotation before the following definition is bound. | |
| 20 | async def lifespan(app: FastAPI): | Defines a coroutine function; calling it creates a coroutine object and await drives its execution. | |
| 21 | app.state.http = build_http_client() | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. | |
| 22 | yield | Emits one lazy value and suspends the generator frame for a later resume. | |
| 23 | await app.state.http.aclose() | Starts or resumes asynchronous I/O and yields control until the awaited operation completes. |
Step-by-step execution
- At startup Starlette registers routes and FastAPI compiles dependency, validation, response-model, and OpenAPI metadata from Python signatures.
- For the request, Starlette matches method and path; FastAPI extracts path, query, header, cookie, and body values and Pydantic validates them.
- Dependencies resolve in graph order, yielding request-scoped resources; the async endpoint runs on the event loop and awaits non-blocking database or network I/O.
- The response model filters and serializes output; exceptions follow registered handlers; yielded dependencies unwind and close or roll back resources.
- Tests verify the HTTP or WebSocket contract plus durable state, authorization, cleanup, cancellation, and bounded latency under concurrent work.
Common mistakes and professional corrections
| Area | Common failure | Better engineering choice |
|---|---|---|
| Path operations & routing | A decorator registers the function; defining two identical method/path combinations silently creates an ambiguous or unreachable contract. | Group routes with APIRouter, order static paths before conflicting dynamic paths, and declare response models and status codes explicitly. |
| Pydantic models | Validation can coerce values unless strictness is configured; never expose secrets through a broad response model. | Separate create, update, internal, and public schemas. |
| Dependency injection | A generator dependency is a lifecycle boundary, not an ordinary lazy iterator; sharing sessions across requests or concurrent tasks corrupts transaction ownership. | Use dependencies for authentication, validated policy, units of work, and request resources; use lifespan state for process-wide clients and pools. |
| Background tasks | Returning a response does not guarantee an in-process background task completed. | Use BackgroundTasks for best-effort, short work and a durable queue for business-critical jobs. |
| HTTP & OpenAPI contract | Returning ORM or dictionary data without an explicit response contract can leak internal fields and let implementation drift reach clients. | Declare precise success statuses and response schemas, including created/accepted/no-content behavior, and document typed error responses separately. |
Interview and review notes
- Define the central abstraction without naming a library function.
- Trace one request, call, query, message, render, or state transition from input to observable result.
- Compare two alternatives from this chapter by guarantee, cost, and failure behavior.
- Explain the most likely production bug and the test or metric that reveals it.
- State what remains authoritative after process loss, retry, reconnect, or deployment.
Practice set
Easy
- Define every bold term in the concept tables in one precise sentence.
- Reproduce the focused examples and annotate the value or state after each important line.
- Explain the chapter progression diagram aloud in two minutes.
Medium
- Replace one convenient default with an explicit policy for validation, timeout, ordering, pagination, cleanup, or error handling.
- Write a negative test for each topic group.
- Compare the measured behavior before and after one justified change.
Hard
- Combine all topic groups into one thin vertical slice.
- Inject a realistic failure at the most important external boundary and prove recovery.
- Write a one-page design note covering ownership, trade-offs, security, observability, and rollback.
Chapter submission
Submit:
- source code or reproducible commands;
- automated tests plus one deliberately failing-before-fix test;
- captured output, query plan, trace, screenshot, or metric;
- a 300–500 word explanation of the execution flow and one rejected alternative;
- a short README with setup, versions, limitations, and cleanup steps.
- Continue with the URL Shortener API project workshop.
Self-review rubric
| Dimension | Beginning | Competent | Professional |
|---|---|---|---|
| Explanation | Names APIs | Explains behavior | Connects guarantees, internals, and trade-offs |
| Implementation | Happy path only | Validated and tested | Clear ownership, failure recovery, and cleanup |
| Evidence | Manual claim | Repeatable output | Tests plus meaningful measurement or inspection |
| Communication | Steps missing | Reproducible README | Decisions, limits, and alternatives are explicit |
Roadmap coverage checklist
- To do: Path operations & routing: @app.get/post/put/delete/patch decorators
- To do: Path operations & routing: path params + type validation
- To do: Path operations & routing: query params (optional/required/aliases)
- To do: Path operations & routing: APIRouter for modular routing
- To do: Pydantic models: BaseModel + Field() (min_length/max_length/ge/le/regex)
- To do: Pydantic models: @field_validator (Pydantic v2)
- To do: Pydantic models: model inheritance
- To do: Pydantic models: from_attributes (orm_mode)
- To do: Pydantic models: nested models
- To do: Dependency injection: Depends() + sub-dependencies
- To do: Dependency injection: class-based dependencies
- To do: Dependency injection: DB session yield pattern
- To do: Dependency injection: current user dep with JWT
- To do: Dependency injection: Lifespan events
- To do: Background tasks: BackgroundTasks.add_task()
- To do: Background tasks: async vs sync background tasks
- To do: Background tasks: when to use Celery instead
- To do: HTTP & OpenAPI contract: status codes and response_model
- To do: HTTP & OpenAPI contract: OpenAPI schema generation and docs
- To do: HTTP & OpenAPI contract: request body vs path/query/header/cookie parameters
- To do: HTTP & OpenAPI contract: exception handlers and error schemas
Quick revision
- Path operations & routing: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Pydantic models: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Dependency injection: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Background tasks: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- HTTP & OpenAPI contract: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Re-read the worked-example execution trace instead of memorizing isolated syntax.
- If you cannot name the owner of state and cleanup, the design is not yet complete.
Mastery check
How well can you recall this?
Finished this lesson?