← Back to courses

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.

Module 1 of 107 lessons

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

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

Beginnerstart here25 min
Lesson 1.1Open →

Setup and Your First App

1.2

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

Beginnersetup25 min
Lesson 1.2Open →

Path Operations and HTTP Methods

1.3

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

Beginnerrouting35 min
Lesson 1.3Open →

Path Parameters

1.4

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

Beginnerparameters30 min
Lesson 1.4Open →

Query Parameters

1.5

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

Beginnerparameters30 min
Lesson 1.5Open →

Request Body with Pydantic

1.6

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

Beginnerpydantic35 min
Lesson 1.6Open →

The Interactive Docs

1.7

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

Beginneropenapi25 min
Lesson 1.7Open →
Module 2 of 105 lessons

Pydantic & Validation

Describe your data once, and let FastAPI check every request and response

Pydantic Models in Depth

2.1

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

Beginnerpydantic35 min
Lesson 2.1Open →

Field Rules

2.2

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

Beginnerpydantic35 min
Lesson 2.2Open →

Custom Validators

2.3

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

Intermediatepydantic35 min
Lesson 2.3Open →

Nested Models and Lists

2.4

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

Intermediatepydantic30 min
Lesson 2.4Open →

Response Models

2.5

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

Intermediatepydantic30 min
Lesson 2.5Open →
Module 3 of 105 lessons

Responses & Errors

Status codes, clear errors, and every kind of response - JSON, files, forms and cookies

Status Codes

3.1

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

Beginnerresponses25 min
Lesson 3.1Open →

Errors and HTTPException

3.2

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

Intermediateresponses35 min
Lesson 3.2Open →

Response Types

3.3

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

Intermediateresponses30 min
Lesson 3.3Open →

Headers and Cookies

3.4

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

Intermediatehttp30 min
Lesson 3.4Open →

Forms and File Uploads

3.5

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

Intermediatemultipart35 min
Lesson 3.5Open →
Module 4 of 104 lessons

Dependencies

Share code between endpoints with Depends - the most important FastAPI idea after models

Module 5 of 106 lessons

Databases

Store data in a real database with SQLModel and SQLAlchemy

Databases and ORMs in 15 Minutes

5.1

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

Beginnerdatabases20 min
Lesson 5.1Open →

SQLModel Setup

5.2

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

Intermediatedatabases30 min
Lesson 5.2Open →

CRUD with Sessions

5.3

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

Intermediatedatabases35 min
Lesson 5.3Open →

Relationships

5.4

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

Intermediatedatabases40 min
Lesson 5.4Open →

Migrations with Alembic

5.5

create_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".

Intermediatedatabases40 min
Lesson 5.5Open →

Async Database Access

5.6

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

Advanceddatabases35 min
Lesson 5.6Open →
Module 6 of 105 lessons

Auth & Security

Passwords, tokens and permissions - who is calling, and what they may do

Authentication vs Authorization

6.1

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

Intermediatesecurity30 min
Lesson 6.1Open →

Password Hashing

6.2

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

Intermediatesecurity35 min
Lesson 6.2Open →

Login with OAuth2 and JWT

6.3

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

Intermediatesecurity40 min
Lesson 6.3Open →

Protecting Routes

6.4

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

Intermediatesecurity40 min
Lesson 6.4Open →

CORS and Security Basics

6.5

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

Intermediatesecurity35 min
Lesson 6.5Open →
Module 7 of 108 lessons2 ready

Async, Background Tasks & Middleware

async and await, work after the response, and code that runs around every request

async def or def?

7.1

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

Intermediateasync35 min
Lesson 7.1Open →

Calling Other APIs

7.2

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

Intermediateasync40 min
Lesson 7.2Open →

Background tasks

7.3

Work that runs after the response is sent

Send a welcome email

Lesson 7.3planned

Middleware

7.4

Code around every request

Timing and request ids

Lifespan: startup and shutdown

7.5

Opening and closing shared resources

Load a model once at startup

Streaming responses

7.6

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

The 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.8

Two-way connections, and when to choose them over SSE

A live chat room

Module 8 of 104 lessonsComing soon

Bigger Apps

Split an app into routers and files, and configure it with settings

APIRouter and project layout

8.1

One file per area, with prefixes and tags

users, todos and admin routers

Settings and environment variables

8.2

pydantic-settings and .env files

Database URL and secret key

Lesson 8.2planned

Logging

8.3

Useful logs for every request

A request id in every log line

Lesson 8.3planned

API versioning

8.4

Changing an API without breaking clients

/v1 and /v2 side by side

Lesson 8.4planned
Module 9 of 104 lessonsComing soon

Testing

Prove your API works - and keeps working - with pytest

Testing with TestClient

9.1

Requests without a server, checked with pytest

Tests for the to-do API

Overriding dependencies

9.2

Fake users and fake databases in tests

Test a protected route

Testing with a database

9.3

A fresh test database for each test

SQLite in memory

Lesson 9.3planned

Async tests

9.4

httpx.AsyncClient and pytest-asyncio

Testing an async endpoint

Lesson 9.4planned
Module 10 of 104 lessonsComing soon

Production & Deployment

Run it for real users: workers, Docker, HTTPS and monitoring

fastapi run and workers

10.1

Production mode, processes and ports

4 workers on one machine

Docker

10.2

A small, safe image for your API

A Dockerfile for the to-do API

Behind a proxy with HTTPS

10.3

Nginx or a cloud load balancer in front

Forwarded headers and root_path

Lesson 10.3planned

Health checks and monitoring

10.4

Knowing your API is up and fast

/health and request timing

Lesson 10.4planned
Classic lessons · 7

The earlier version of this course

Shorter reference-style lessons. Each one stays here until the new course covers its topic.