FastAPI Tutorials
FastAPI from a first endpoint to something you can put in front of users — routing and validation, project structure, dependency injection, SQLAlchemy and migrations, auth, uploads, background work, middleware, testing, observability and Docker. Every example is taken from a real short-let booking API, and the performance claims are measured on the machine that wrote them rather than repeated.
- FastAPI – Interview QuestionsThe questions a FastAPI role actually asks, answered against the seventeen lessons before this one. Why type hints do the validating, def versus async def and what happens to each, how dependency injection is tested, where a transaction begins and ends, what BackgroundTasks does not promise, and how a request is traced in production. Short answers, with the reasoning behind them.
- FastAPI – Getting It Into ProductionFrom a working image to something serving users. Workers and what they cost in database connections, a reverse proxy in front, configuration and secrets from the environment, running migrations as a step rather than at boot, and rolling out without dropping requests. Plus what to check first when it works locally and not in the cluster.
- FastAPI – Containerising It ProperlyA multi-stage Dockerfile that leaves the compiler behind, a .dockerignore that cuts the build context from hundreds of megabytes and keeps .env out of a layer, and a non-root user. Then the settings that decide whether it works: --host 0.0.0.0, PYTHONUNBUFFERED, how many workers, and a healthcheck. With the resulting image size and build time measured rather than estimated.
- FastAPI – Logging, Health Checks and Request TracingMaking a running API explainable. Structured JSON logs with a correlation id carried by a ContextVar so it survives both async routes and the threadpool, a health check that reports each dependency separately, and what to log per request. Includes two things that bite in a container: uvicorn quietly replacing your log config, and a test that asserted on log content while reading another handler's work.
- FastAPI – Testing the Whole StackTestClient against the real ASGI stack, dependency_overrides to swap the database and the current user, and a fixture that runs every test inside a transaction it rolls back. Which tests belong at the service layer and which can only be written through HTTP — including the class of bug that lives entirely in configuration and is invisible to everything below TestClient.
- FastAPI – Middleware, Ordering and CORSMiddleware for the things every request needs: a correlation id, a timing header, one access log line. Then ordering, which reads backwards — add_middleware inserts at the front, so the last call is the outermost layer. Getting that wrong shipped a real bug here: every 500 reached the browser without CORS headers, so the frontend reported a CORS failure and never saw the error body.
- FastAPI – async def or def, and How to TellThe most consequential one-word decision in the framework. What FastAPI does with a def route versus an async def one, why a blocking call inside async def stalls every other request, and the threadpool that makes plain def safe. Then the same eight queries run serially and concurrently and MEASURED — where async wins by 86%, where it loses by 289%, and roughly where the line between them sits.
- FastAPI – Background Tasks and Their LimitsBackgroundTasks runs work after the response is sent, which is the entire feature. What that buys, what it emphatically is not — no retry, no persistence, no visibility — and when to reach for a real queue instead. Then the trap that makes it dangerous: a yield dependency closes BEFORE the task runs, so passing an ORM object half-works, and the half that fails is the half you add later.
- FastAPI – File Uploads Without the HolesUploadFile, streamed in chunks rather than read into memory, with a size limit enforced during the write because there is no trustworthy length beforehand. Then the three guards an upload endpoint needs: content sniffed from the bytes rather than trusted from a header the client typed, a generated filename because "../../app/main.py" is a valid one, and no partial file left behind on failure.
- FastAPI – Authentication and AuthorizationHashing passwords with bcrypt, issuing a JWT, and verifying it on every request. Then the half everyone skips: authorization as dependencies, so a route signature declares who may call it and the OpenAPI schema documents it for free. Includes why the user is re-read from the database each request, and why a foreign-owned resource returns 404 rather than 403.
- FastAPI – One Error Shape for the Whole APIEvery failure leaving as the same JSON body, so a client needs one error parser. Custom exception classes raised from the service layer, handlers that turn them into responses, and flattening pydantic's nested validation errors into field messages a form can render. Plus the trap that cost this project a real bug: a handler registered for bare Exception does NOT run where the others do.
- FastAPI – Designing the REST APITurning endpoints into an API someone else can use. Resource naming, PATCH versus PUT, response_model and what it hides, and giving a state change its own endpoint instead of making it a writable field. Then pagination done properly — a generic Page[T] envelope, bounded page sizes, and the ORDER BY that stops page two repeating rows from page one.
- FastAPI – SQLAlchemy, Sessions and MigrationsA real data layer. The engine and one session per request, typed SQLAlchemy 2.0 models, the repository pattern, and who owns the transaction. Then Alembic: naming constraints so a downgrade can refer to them, and never editing an applied migration. Includes the N+1 problem, eager loading, and why expire_on_commit=False matters specifically in FastAPI.
- FastAPI – Dependency Injection in PracticeThe feature FastAPI is built on. Depends(), dependencies that yield so setup and teardown live together, sub-dependencies, and collapsing the whole thing into one readable Annotated alias so a route signature states its own security rules. Then dependency_overrides, which is what makes any of it testable — and the reason an override keyed on the wrong function object silently does nothing.
- FastAPI – Project Structure That Survives GrowthThe question the official docs answer least well. How a single main.py becomes routes, services, repositories, schemas and models — what belongs in each layer, and the rules that keep them apart: routes own HTTP, services own the rules, and repositories never commit because only the caller knows where a transaction ends. Plus typed settings read once, so a misspelt variable is a startup error.
- FastAPI – Pydantic Models and ValidationPydantic v2 as FastAPI actually uses it. Field constraints, field and model validators, computed fields for values that change at midnight, and separating the model you store from the model you return. Includes the snake_case-to-camelCase boundary that lets Python and TypeScript each keep their own conventions, and a field named `property` that breaks the `property` builtin twenty lines later.
- FastAPI – Routes, Parameters and Status CodesEverything that turns an HTTP request into typed Python arguments. Path and query parameters, constraints with Query(), why Annotated is the form to learn, header and cookie parameters, choosing a status code, and splitting an API across routers with APIRouter. Including the repeated query parameter that needs no parsing, and the alias that lets a Python snake_case argument read as camelCase on the wire.
- FastAPI – What It Is and Why It ExistsStart here. What FastAPI actually gives you — validation, serialisation and OpenAPI docs derived from ordinary type hints — and what it does not. Installing it, a first endpoint, what /docs is really reading, and how a request travels through the ASGI stack. Then the lesson index in reading order, the versions this track is written against, and the booking API every example is taken from.