Course
FastAPI
52 lessons across 10 modules · 7 classic
Build web APIs with Python, from your first endpoint to production. Each lesson explains one idea in simple steps, with code you can run and the real output. The course is being rewritten module by module; the earlier lessons stay below as “classic” until their new version is ready.
Getting Started
What an API is, why FastAPI, and your first endpoints - running on your own machine
What is an API, and Why FastAPI?
1.1Learn what an API is, how a request and a response look, and why FastAPI is a good way to build one in Python. We build the same small API twice - by hand and with FastAPI - and send both the same requests.
Setup and Your First App
1.2Install FastAPI in a virtual environment, write a five-line app, run it with fastapi dev, and open the automatic docs. Then see auto-reload work - and the four errors almost every beginner meets on day one.
Path Operations and HTTP Methods
1.3Build a small to-do API with all five common HTTP methods - GET, POST, PUT, PATCH and DELETE - and the right status codes. Then test the mistakes: a wrong method, a trailing slash, routes in the wrong order, and a route defined twice.
Path Parameters
1.4Read values from the URL itself - /books/2, /shirts/large, /files/docs/report.pdf - with types, limits and fixed choices. Tested with 26 real requests, including the surprising ones: "007", "+2" and "1_000" all become numbers, and "../" passes straight through.
Query Parameters
1.5Use the part of the URL after the ? - /books?skip=2&limit=2, /search?q=web&genre=web - for options, filters and paging. Make them optional or required, add limits, accept lists, and see what FastAPI silently ignores.
Request Body with Pydantic
1.6Receive JSON from the client and get a checked Python object back: describe the shape once with a Pydantic model, and FastAPI does the rest. Tested with 20 requests - including a typo that silently set a price to 0.0, and the one-line fix.
The Interactive Docs
1.7Turn the automatic docs into clear docs: a title and description, groups (tags), summaries, docstrings, field examples, documented errors and deprecated endpoints. Then use "Try it out" in a real browser - and learn the safe way to hide the docs.
Pydantic & Validation
Describe your data once, and let FastAPI check every request and response
Pydantic Models in Depth
2.1Use Pydantic on its own, outside FastAPI: field types (dates, enums, literals, lists), required vs optional, turning dicts and JSON into models and back, and the error object. Then two surprises: changing a field after creation is not checked - and the two settings that fix it.
Field Rules
2.2Add rules to fields: number limits, text length and patterns, exact money with Decimal, list sizes, cleaned-up text, emails and URLs, defaults made at creation time, and JSON names that differ from Python names. Plus a real bug: a default that broke its own rule and caused a 500 error.
Custom Validators
2.3When Field rules are not enough, write your own checks: clean and check one field with @field_validator, compare fields with @model_validator, and add values computed from other fields. Tested in FastAPI - including a validator that forgot "return" and silently turned a username into None.
Nested Models and Lists
2.4Real data has structure: an order has an address, many order lines and one of several payment types. Build it from models inside models, lists and dicts, read errors that point deep inside ("lines.1.qty"), and let one field choose the right model with a discriminated union.
Response Models
2.5Control what leaves your API: a response model filters out everything else - like the password hash our "leaky" endpoint sent. Use a return type or response_model=, separate In and Out models, drop empty fields, and see what happens when you return data that does not fit.
Responses & Errors
Status codes, clear errors, and every kind of response - JSON, files, forms and cookies
Status Codes
3.1Every response starts with a three-digit number that tells the client what happened. Learn the few codes you need every day - 200, 201, 204, 400, 404, 409, 422 - set them with status_code= or the Response object, and see which ones FastAPI already sends for you.
Errors and HTTPException
3.2Stop a request with HTTPException - from an endpoint or any helper - add headers or a dict detail, raise your own business errors, and write exception handlers so every error in the API has one format. Tested before and after the handlers, including a real bug that gives 500.
Response Types
3.3JSON is only the default. Send HTML, plain text, redirects, a CSV download, a file from disk and a stream - and learn the traps: a Response you return yourself skips the response model, dates break JSONResponse, and a file path from the URL can escape your folder.
Headers and Cookies
3.4Read request headers with Header() and cookies with Cookie(), send your own headers, and set and delete cookies with the right options. Built around a "remember my language" cookie, tested with TestClient, curl and a real browser - including a cookie that silently disappeared.
Forms and File Uploads
3.5Receive HTML form fields with Form() and files with UploadFile. Build a profile-photo upload that checks the size and the real file type, saves under its own name, and works from a real browser and curl. Tested with a text file pretending to be a PNG, a 2 MB file and a filename that tries to escape the folder.
Dependencies
Share code between endpoints with Depends - the most important FastAPI idea after models
What is Dependency Injection?
4.1Stop copying the same parameters and checks into every endpoint. Write them once as a dependency, ask for it with Depends, and FastAPI runs it before your endpoint. We start with three copy-pasted endpoints - one with a real bug - and fix all three with one function.
Depends in Practice
4.2Real apps chain dependencies: a token header gives the current user, the user gives the admin check, and a database session is shared by all of them. Build that chain, use a class as a dependency, give a dependency a setting, and see that a dependency runs only once per request.
Dependencies with yield
4.3Open something before the endpoint and close it afterwards - with one yield. Build a SQLite session that commits on success and rolls back on errors, then test the edges: cleanup order, streaming, an exception that is swallowed, and a commit that fails after the client was already told "saved" - and the scope="function" fix.
Router and App Dependencies
4.4Run a dependency for many routes at once: on one route with dependencies=[...], on every route of an APIRouter, or on the whole app. Protect all /admin routes with one API-key check, see the order in which the levels run, and what the app level does NOT cover.
Databases
Store data in a real database with SQLModel and SQLAlchemy
Databases and ORMs in 15 Minutes
5.1Before SQLModel, see what a database really does. Create a to-do table, add, read, change and delete rows with plain SQL in Python’s built-in sqlite3 - then see the two classic mistakes (no commit, SQL built with an f-string) and what an ORM writes for you.
SQLModel Setup
5.2Describe a table once with SQLModel - a class that is both a SQLAlchemy table and a Pydantic model. Create the engine and the table, save and read rows with a Session, and split the model into Base, table, Create and Public models. Tested with the traps: table models do not validate, objects expire after commit, and create_all never changes an existing table.
CRUD with Sessions
5.3Connect SQLModel to FastAPI: one session per request through a yield dependency, tables made at startup with lifespan, and the five to-do endpoints - create, list with paging, read, PATCH and delete - saved to a file that survives a restart. Includes a real 500 bug from PATCH {"title": null}, its fix, and tests on an in-memory database.
Relationships
5.4Connect tables: users and their to-dos (one-to-many with a foreign key) and to-dos and tags (many-to-many with a link table). Move between them in Python, then meet the real traps: SQLite does not check foreign keys by default, deleting a user fails without cascade_delete, and a list of users with their to-dos sent 23 queries instead of 2.
Migrations with Alembic
5.5create_all cannot change a table - Alembic can. Set it up for SQLModel, generate migrations from your models, add a column without losing data, and go back with downgrade. Tested with the traps that stop beginners: the missing import sqlmodel, a NOT NULL column on a table that has rows, and a rename that autogenerate turns into "drop the column".
Async Database Access
5.6Use an async engine and AsyncSession with async def endpoints - and learn when it really helps. A timing test with a slow query shows the one combination that hurts (a normal session inside async def: 5 requests took 2.03 s instead of 0.5 s), and three async traps: MissingGreenlet on relationships and after commit, and a forgotten await.
Auth & Security
Passwords, tokens and permissions - who is calling, and what they may do
Authentication vs Authorization
6.1Two different questions: WHO is calling (authentication, 401) and WHAT may they do (authorization, 403 or 404). Build them as separate dependencies with FastAPI’s HTTPBearer, test a guest, a user, an admin and a bad token against every endpoint, and use the Authorize button in /docs from a real browser.
Password Hashing
6.2Never store passwords - store hashes. Use pwdlib with Argon2: hash at signup, verify at login, and upgrade old hashes on the fly. Measured: Argon2 takes about 43 ms per guess, SHA-256 makes 2 million guesses a second. And two real leaks we found and fixed: login timing told attackers which usernames exist, and the 422 error echoed the password back.
Login with OAuth2 and JWT
6.3Log in once with a username and password, get a signed token, and send it with every request. Take a JWT apart, attack it five ways, build POST /token with OAuth2’s password form, and add a refresh token so access tokens can be short. Plus two real leaks: a bad token that crashed the server with 500, and a 7-day refresh token that worked as an access token.
Protecting Routes
6.4Turn a login token into a real user on every request, then guard routes three ways: a whole router at once, by role, and by owner - with the owner check inside the SQL query. Plus two real leaks we found and fixed: a disabled user whose old token still worked, and a user who made himself admin through PATCH /me. And a ten-line test that lists every route left open by mistake.
CORS and Security Basics
6.5Let a React app on another port call your API. See why the browser blocks it, what a preflight request is, and how CORSMiddleware answers it - tested in a real browser. Then three real traps: an origin that never matches, "*" with credentials that lets ANY site in, and a 500 error that the browser reports as a CORS error. Plus three security headers for every response.
Async, Background Tasks & Middleware
async and await, work after the response, and code that runs around every request
async def or def?
7.1FastAPI runs async def routes on one event loop and def routes in a pool of threads. We measured what that means: one blocking call inside async def made 10 requests take 10.06 s and froze /health for almost 10 s; plain def has a hidden limit of 40 threads (100 requests: 3.24 s); and CPU work is not helped by either - only other processes help.
Calling Other APIs
7.2Call another API from your API with httpx - safely. Our first weather endpoint opened 100 connections for 100 calls, turned 36 upstream errors into "200 OK", and crashed with 500 when the service hung. The fixed one shares one client (3 times faster), sets timeouts, maps errors to 404/502/503/504, and retries only what is safe to retry - retrying timeouts made users wait 6.32 s instead of 2.01 s.
Background tasks
7.3Work that runs after the response is sent
Send a welcome email
Lifespan: startup and shutdown
7.5Opening and closing shared resources
Load a model once at startup
Streaming responses
7.6Async generators, JSON lines (NDJSON), and noticing when the client disconnects
Stream a long report row by row, and stop when the client leaves
Server-Sent Events (SSE)
7.7The text/event-stream format, EventSource in the browser, reconnects and keep-alive pings
Stream an AI chat reply word by word, the way chat apps do
WebSockets
7.8Two-way connections, and when to choose them over SSE
A live chat room
Bigger Apps
Split an app into routers and files, and configure it with settings
APIRouter and project layout
8.1One file per area, with prefixes and tags
users, todos and admin routers
Settings and environment variables
8.2pydantic-settings and .env files
Database URL and secret key
Logging
8.3Useful logs for every request
A request id in every log line
API versioning
8.4Changing an API without breaking clients
/v1 and /v2 side by side
Testing
Prove your API works - and keeps working - with pytest
Testing with TestClient
9.1Requests without a server, checked with pytest
Tests for the to-do API
Overriding dependencies
9.2Fake users and fake databases in tests
Test a protected route
Testing with a database
9.3A fresh test database for each test
SQLite in memory
Async tests
9.4httpx.AsyncClient and pytest-asyncio
Testing an async endpoint
Production & Deployment
Run it for real users: workers, Docker, HTTPS and monitoring
fastapi run and workers
10.1Production mode, processes and ports
4 workers on one machine
Docker
10.2A small, safe image for your API
A Dockerfile for the to-do API
Behind a proxy with HTTPS
10.3Nginx or a cloud load balancer in front
Forwarded headers and root_path
Health checks and monitoring
10.4Knowing your API is up and fast
/health and request timing
The earlier version of this course
Shorter reference-style lessons. Each one stays here until the new course covers its topic.
Middleware
CORS so a browser app can call you, your own logging and timing wrappers, and the security ones that ship with FastAPI.
Classic · ArchitectureLifecycle
Open shared resources at startup and close them at shutdown.
Classic · ArchitectureAsync patterns
When to write async def and when plain def, work done after the reply, task queues, WebSockets, and server-sent events.
Classic · AdvancedRouters
Split your routes into separate APIRouter files and keep old versions working.
Classic · AdvancedTesting
TestClient for quick tests, httpx for async ones, and swapping a dependency for a fake.
Classic · AdvancedProduction
Settings read from the environment, limits on how often someone can call you, and health check endpoints.
Classic · AdvancedCheatsheet
Commands to install and run, the route decorators, and the parameter types.
Classic · Reference