Free course · 35 lessons · Intermediate

FastAPI: From Basics to Production

Build production-ready Python APIs with FastAPI: Pydantic v2, dependency injection, async SQLAlchemy and Alembic, JWT auth, testing, background jobs, observability and deployment.

Start the course

1. FastAPI Basics

Create your first API, handle parameters and bodies, and explore automatic documentation.

  1. Hello FastAPI — Install FastAPI, run the dev server and write your first endpoints.
  2. Path and Query Parameters — Declare, validate and document URL parameters with Annotated.
  3. Request Bodies, Response Models and Status Codes — Accept JSON bodies with Pydantic and control what you return.
  4. Models, Validation and Dependencies: An Overview — How Pydantic models and dependency injection fit together in FastAPI.
  5. Automatic Docs and OpenAPI — Customize the generated OpenAPI schema, tags, examples and client generation.

2. Pydantic v2 in Depth

Validation, serialization, settings and advanced types with Pydantic v2.

  1. Field Constraints and Validators — Validate data with Field constraints, field validators and model validators.
  2. Serialization, Aliases and ORM Mode — Control output with model_dump, aliases, computed fields and from_attributes.
  3. Configuration with pydantic-settings — Load typed settings from environment variables and .env files.
  4. Annotated Types and Discriminated Unions — Reusable constrained types and polymorphic payloads.

3. Dependency Injection in Depth

Yield dependencies, classes, sub-dependencies, global dependencies and overrides.

  1. Dependencies, Sub-dependencies and Classes — Compose reusable request logic with Depends.
  2. Dependencies with yield: Sessions and Resources — Manage per-request resources with setup and teardown.
  3. Lifespan Events and Shared Clients — Create and close app-wide resources like HTTP clients and pools.
  4. Reusable Pagination and Filter Dependencies — Standardize list endpoints with dependency classes.

4. Building Real APIs

Structure larger apps with routers, consistent errors, middleware, background work and file handling.

  1. Routers for Separation — Split an app into feature routers with prefixes, tags and shared dependencies.
  2. Consistent Error Handling — Return predictable error responses with HTTPException and custom handlers.
  3. Middleware, CORS and Request Context — Add cross-cutting behavior: CORS, request IDs, timing and security headers.
  4. Async and Background Work — Use async correctly, avoid blocking the event loop, and offload work.
  5. File Uploads and Streaming Responses — Accept uploads safely and stream large responses.

5. Databases with SQLAlchemy 2.0 and Alembic

Async SQLAlchemy sessions, CRUD, relationships and migrations.

  1. Setting Up Async SQLAlchemy — Engine, session factory, declarative models and per-request sessions.
  2. CRUD with select(), Sessions and Transactions — Query and modify data with SQLAlchemy 2.0 style.
  3. Relationships and Avoiding N+1 Queries — Eager-load related data explicitly in async SQLAlchemy.
  4. Migrations with Alembic — Generate, review and apply schema migrations safely.

6. Authentication and Security

Password hashing, OAuth2 password flow with JWTs, scopes and permissions, API keys and rate limiting.

  1. Password Hashing and the Login Endpoint — Hash passwords with Argon2 and implement OAuth2 password flow login.
  2. JWT Access Tokens and the Current User — Issue and verify short-lived JWTs and resolve the current user.
  3. Permissions, Roles and Object-Level Checks — Authorize actions with role dependencies and ownership checks.
  4. API Keys, Rate Limiting and Security Headers — Protect machine clients and public endpoints.

7. Testing FastAPI Applications

TestClient, async tests, dependency overrides and real-database integration tests.

  1. Testing with TestClient and pytest — Write fast API tests that run in-process.
  2. Async Tests with httpx and pytest — Test async code paths with AsyncClient and ASGITransport.
  3. Dependency Overrides in Tests — Swap auth, settings and external services in tests.
  4. Integration Tests with a Real Database — Run tests against PostgreSQL with migrations and per-test isolation.

8. Deployment, Observability and Performance

Run FastAPI in production with workers, Docker, background jobs, monitoring and tuning.

  1. Running FastAPI in Production — Workers, proxies, timeouts and graceful shutdown.
  2. Docker Images for FastAPI — Build small, cache-friendly, non-root images.
  3. Background Jobs with Task Queues — Move heavy and durable work to Celery, ARQ or Dramatiq workers.
  4. Logging, Metrics and Tracing — Structured logs, Prometheus metrics and OpenTelemetry traces for FastAPI.
  5. Performance Tuning — Find and fix the real bottlenecks in FastAPI services.