Reading Mode
CH 14·Lesson 3
Phase 3 — FastAPI — Checkpoint Answer Guide
This is a grading guide, not a script to memorize. Equivalent designs earn credit when their assumptions and evidence are correct.
advanced7 min read
Learning Objectives
- FastAPI Basics
- Async FastAPI
- FastAPI Production
- Professional standard
This is a grading guide, not a script to memorize. Equivalent designs earn credit when their assumptions and evidence are correct.
FastAPI Basics
- Path operations & 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. A strong answer also explains that 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. The main warning is: A decorator registers the function; defining two identical method/path combinations silently creates an ambiguous or unreachable contract.
- Pydantic models: Pydantic models parse untrusted input into typed values and serialize explicit output contracts. A strong answer also explains that pydantic v2 compiles a Core Schema evaluated by pydantic-core. Field validation precedes model-level invariants; from_attributes reads object attributes. The main warning is: Validation can coerce values unless strictness is configured; never expose secrets through a broad response model.
- Dependency injection: FastAPI dependency injection declares request-scoped prerequisites and resource lifecycles as a graph rather than hiding them inside handlers. A strong answer also explains that fastAPI resolves each dependency and its sub-dependencies in topological order, caches results per request by default, and unwinds
yielddependencies for deterministic cleanup after response handling. The main warning is: A generator dependency is a lifecycle boundary, not an ordinary lazy iterator; sharing sessions across requests or concurrent tasks corrupts transaction ownership. - Background tasks: BackgroundTasks schedules small in-process work after the response; Celery provides externally queued, retryable, independently scalable work. A strong answer also explains that background tasks share the server process and are lost if it terminates. Celery serializes work to a broker with worker acknowledgments. The main warning is: Returning a response does not guarantee an in-process background task completed.
- HTTP & OpenAPI contract: A FastAPI route's status code states the HTTP outcome, while
response_modelvalidates, filters, serializes, and documents the public response shape. A strong answer also explains that 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. The main warning is: Returning ORM or dictionary data without an explicit response contract can leak internal fields and let implementation drift reach clients.
Async FastAPI
- async/await patterns: Cooperative concurrency lets one task yield while it waits so another ready task can use the same thread. A strong answer also explains that calling an async function creates a coroutine.
awaitsuspends only at an awaitable; the event loop schedules callbacks and resumes ready tasks.gatherpreserves input order but failure policy must be chosen. The main warning is: A blocking library call freezes the loop; move unavoidable sync work to a bounded executor. - asyncio deep dive: Cooperative concurrency lets one task yield while it waits so another ready task can use the same thread. A strong answer also explains that calling an async function creates a coroutine.
awaitsuspends only at an awaitable; the event loop schedules callbacks and resumes ready tasks.gatherpreserves input order but failure policy must be chosen. The main warning is: A blocking library call freezes the loop; move unavoidable sync work to a bounded executor. - Async SQLAlchemy: Async SQLAlchemy exposes non-blocking database I/O while preserving unit-of-work and identity-map semantics. A strong answer also explains that an AsyncSession wraps a transaction and identity map; it is mutable and must not be shared across concurrent tasks. Alembic tracks schema revisions separately from runtime sessions. The main warning is: Lazy relationship access can attempt I/O in an invalid context; bound pools and avoid concurrent session use.
- Lifespan, diagnosis & load: FastAPI dependencies form a directed graph of reusable request requirements and resources. A strong answer also explains that fastAPI caches a dependency result per request by default. Yield dependencies execute cleanup after the endpoint; lifespan creates process-scoped resources once. The main warning is: Do not create connection pools or SDK clients on every request.
FastAPI Production
- OAuth2 & JWT: Token authentication proves possession of a signed credential; authorization separately decides whether that identity may perform an action. A strong answer also explains that a server validates signature, issuer, audience, expiry, and claims. Short-lived access tokens limit exposure; rotating refresh tokens require server-side reuse detection or revocation state. The main warning is: Decoding is not validation, and a valid token does not grant every resource.
- WebSockets: A decorator receives a callable or class and returns a replacement, usually adding cross-cutting behavior. A strong answer also explains that decoration runs when the definition is executed, not at each call; the returned wrapper is what the name references.
wrapspreserves metadata and the wrapped chain. The main warning is: Keep retries bounded and restricted to transient, idempotent operations. - Middleware & CORS: Middleware wraps every request and response to apply cross-cutting policy at a controlled boundary. A strong answer also explains that request processing follows configured order inward; response and exception handling unwind outward. ASGI middleware passes scope and send/receive callables. The main warning is: Order matters; broad exception swallowing and body buffering can break streaming.
- Testing: FastAPI's synchronous
TestClientdrives the ASGI app through a compatibility portal, while HTTPXAsyncClientwith an ASGI transport keeps the test inside an async event loop. A strong answer also explains that both send real ASGI scopes/messages without a network socket. Async tests are required when the test itself awaits repositories, fixtures, WebSockets, or other event-loop resources. The main warning is: Mixing event loops or creating async database objects in a different loop causes misleading runtime failures and incomplete cleanup. - API keys & file uploads: API-key authentication identifies a calling application through a high-entropy secret carried in a dedicated header; scopes or a stored policy limit what that key may do. A strong answer also explains that the server hashes stored keys, compares in constant-time where practical, checks status/expiry/scope, and records a non-secret key ID. API keys do not identify an end user unless a separate identity layer does so. The main warning is: Never place keys in URLs, source code, browser bundles, or logs.
- Production WebSocket tests: Production WebSocket tests verify handshake authentication, message schemas, room authorization, cross-worker fan-out, backpressure, disconnect cleanup, and reconnect behavior. A strong answer also explains that a test client performs the HTTP upgrade and exchanges frames; integration tests add Redis or another shared channel so several application processes can be exercised as one logical room. The main warning is: A passing single-process echo test does not prove authorization, distributed broadcast, or memory safety under slow clients.
Professional standard
A complete response identifies the boundary, guarantee, state owner, lifecycle, failure, and proof. Award less credit to answers that name tools without explaining why their guarantees fit the requirement.
Mastery check
How well can you recall this?
Finished this lesson?