FastAPI Tutorial
Learn FastAPI step by step: 50 lessons in 12 chapters with examples, quizzes, diagrams and projects.
Start learning →
of lessons completed
Getting started
- What FastAPI is and how to set it up Learn what FastAPI is, how it builds on Starlette and Pydantic, why type hints drive everything, and how to install and run it on this site and at home.
- Your first endpoint and the test client Create a FastAPI app, add path operations with decorators, return JSON, and call the app in-process with httpx to read status, headers and body.
- REST principles with FastAPI Learn the ideas behind REST (resources, HTTP verbs, status codes, idempotency, statelessness) and see each one in a runnable FastAPI example, plus REST versus RPC and GraphQL.
- FastAPI vs Flask vs Django Compare FastAPI, Flask and Django on features, speed, validation, async, docs and learning curve, see the same endpoint written twice, and learn which framework to choose when.
Request parameters
- Path parameters Capture values from the URL with typed FastAPI path parameters. See automatic conversion, 422 errors, Enum choices, file-path converters and route order.
- Query parameters Use FastAPI query parameters for filters and paging: defaults, optional values, bool conversion, lists, Query() validation, aliases and pagination.
- Request bodies Receive JSON in FastAPI with Pydantic models: body validation, nested data, multiple body parameters, Body(), embedding, and reading 422 error details.
- Headers, cookies, forms and uploads Read request headers and cookies, accept HTML form fields, and receive file uploads with UploadFile in FastAPI. Learn what runs live here and what needs python-multipart.
Pydantic models and validation
- Pydantic models for APIs Learn how Pydantic v2 models describe API data in FastAPI: types, defaults, optional fields, model_dump, model_validate, JSON Schema, and coercion vs strict mode.
- Field constraints and validators Add rules to FastAPI models with Field(), constraints, field_validator, model_validator, computed fields, Annotated types and custom error messages.
- Response models and nested data Use response_model in FastAPI to filter output, hide password fields, split Create/Read/Update schemas, nest models, return lists and use exclude_unset.
- PUT, PATCH and partial updates Learn the difference between PUT and PATCH in FastAPI, build partial updates with model_dump(exclude_unset=True), write update helpers and keep PUT idempotent.
Responses, errors and docs
- Status codes and error handling Choose the right HTTP status codes in FastAPI, raise HTTPException, write custom exception handlers, reshape 422 validation errors and return one consistent error format.
- Response classes and OpenAPI docs Return JSON, plain text, HTML and redirects in FastAPI, then document endpoints with tags, summaries and examples and read the generated openapi.json.
- Jinja2 templates and static files Serve HTML pages from FastAPI with Jinja2Templates and TemplateResponse, mount a StaticFiles directory, loop and branch in templates, and build a form-based to-do page.
- jsonable_encoder and serialization control Control how FastAPI turns Python objects into JSON: use jsonable_encoder, aliases, response_model_exclude_unset, serialization options and custom types, with runnable examples.
Dependency injection
- Dependencies Learn FastAPI dependency injection: write functions with Depends, share query parameters, chain sub-dependencies, understand caching and swap them in tests.
- Class and yield dependencies Use classes as FastAPI dependencies, write yield dependencies for setup and teardown, see how errors reach cleanup code, and know how long each resource lives.
- Router-level and global dependencies Apply FastAPI dependencies to a single decorator, a whole APIRouter or the entire app, build auth guards, and shorten signatures with Annotated aliases.
Structuring larger apps
- Routers and project layout Split a growing FastAPI app with APIRouter: prefixes, tags, include_router, and a layered layout of routers, services and schemas, shown in a runnable single file.
- Settings and configuration Configure FastAPI the 12-factor way: typed settings from environment variables with pydantic-settings, a cached settings dependency, secrets and test overrides.
- Middleware and CORS Write FastAPI HTTP middleware for timing and request IDs, configure CORSMiddleware for browser apps, add GZip and trusted hosts, and learn the middleware order.
- Lifespan events and app state Learn the FastAPI lifespan context manager: run code at startup and shutdown, keep shared resources on app.state and run the lifespan in tests.
- Mounting sub-applications and static directories Use app.mount in FastAPI to attach static directories, separate FastAPI sub-apps with their own docs, and WSGI apps, and learn how root_path works behind a proxy.
- API versioning Version a FastAPI API with URL prefixes and routers, a custom version header, or mounted sub-apps, mark old endpoints deprecated, and announce sunset dates to clients.
Async and concurrency
- async def vs def endpoints Understand the event loop, when a FastAPI endpoint should be async def or plain def, how blocking calls freeze everything and how asyncio.gather helps.
- Background tasks Use FastAPI BackgroundTasks to send emails or write logs after the response is sent, test that they ran, and learn when to switch to a task queue.
- Streaming, SSE and WebSockets Stream large or slow responses with StreamingResponse and async generators, send Server-Sent Events, and learn WebSocket endpoints with a connection manager.
Authentication and security
- Password hashing and user accounts Store passwords safely in FastAPI: why you hash, how salts and slow hashes work, a live PBKDF2 stand-in, pwdlib with Argon2, and a registration flow.
- OAuth2 password flow and JWT Build FastAPI login with OAuth2PasswordBearer and signed JWT access tokens: token endpoint, HS256 signing, expiry, a current-user dependency and refresh tokens.
- Roles, scopes and permissions Protect FastAPI endpoints with role checks, OAuth2 scopes via Security(), and ownership rules, and learn when to answer 401, 403 or 404.
- API keys and security practices Protect a FastAPI service with API key headers, rate limiting, strict CORS, request size limits, secure secrets and security headers, with live examples.
- Google and social login (OAuth2 authorization code) Add Sign in with Google (or GitHub) to FastAPI using the OAuth2 authorization code flow: redirect, state check, code exchange, user info, then your own session or JWT.
Databases
- SQLAlchemy with FastAPI Connect FastAPI to a database with SQLAlchemy 2.0: engine, session dependency with yield, ORM models versus Pydantic schemas, and async sessions.
- SQLModel Use SQLModel to define a database table and its Pydantic schema in one class, build Create, Public and table models, and serve them from FastAPI.
- CRUD, filtering and pagination Build a FastAPI data layer: a service layer for CRUD, filtering and sorting, offset and keyset pagination, the N+1 problem, and 409 on unique violations.
- Migrations with Alembic Learn why you need migrations, the Alembic init, revision and upgrade workflow, autogenerate caveats, and how to roll out schema changes safely.
- MongoDB with FastAPI (PyMongo async and Motor) Connect FastAPI to MongoDB with the async PyMongo client (or Motor): create the client in lifespan, handle ObjectId with Pydantic, and build CRUD endpoints you can run here.
Testing and production
- Testing FastAPI apps Learn to test FastAPI apps: call endpoints in-process, assert on status and JSON, override dependencies, isolate databases per test and cover auth and errors.
- Performance and caching Make a FastAPI app faster: measure first, avoid N+1 queries, cap page sizes, cache with a TTL, send ETag and Cache-Control headers and tune pools and JSON.
- Deployment Take a FastAPI app to production: choose uvicorn or gunicorn workers, build a Docker image, put a reverse proxy in front, add health checks and shut down cleanly.
Projects
- Project: To-do API Build a complete to-do REST API with FastAPI: Pydantic schemas, an in-memory store, CRUD endpoints, filters, pagination and a test suite you can run live.
- Project: URL shortener Build a URL shortener with FastAPI and SQLite: generate short codes, accept custom aliases, redirect, count clicks, validate URLs and return 409 on conflicts.
- Project: Blog API with auth Build a blog API with FastAPI: register and log in, signed tokens, posts and comments, ownership permissions (401 vs 403), and paginated public lists.
- Project: Production-ready service Build a small FastAPI service with an app factory, settings, a database, one error shape, request-id middleware, a health endpoint, tests and a Dockerfile.
- Project: A chat app with WebSockets Build a multi-room chat server with FastAPI WebSockets: connection manager, rooms, usernames, join and leave messages, message validation, and a browser client.
Practice, interviews and cheat sheet
- Exercises with solutions Practice FastAPI with 12 graded exercises on parameters, models, dependencies, authentication and databases. Every solution runs live and checks itself.
- Common FastAPI pitfalls Avoid the FastAPI mistakes that bite everyone: blocking calls in async code, shared defaults, leaking fields, route order, missing await and Pydantic v2 traps.
- FastAPI interview questions Prepare for FastAPI interviews with 28 questions and clear answers on ASGI, dependency injection, async, Pydantic, auth, testing and FastAPI vs Flask and Django.
- FastAPI cheat sheet A one-page FastAPI cheat sheet: route decorators, parameter types, status codes, response models, dependency patterns, error handling and test snippets.