Learn FastAPI

Fast, type-hint driven Python framework for building HTTP APIs

28 lessons · 6 hours · 4 levels · covers FastAPI 0.143

FastAPI is a modern Python web framework for building APIs, built on Starlette for the web layer and Pydantic for data validation. You declare endpoints as typed functions and get request parsing, validation, JSON serialization and interactive OpenAPI docs from the same code. It is one of the most popular choices for Python back ends, microservices and ML model serving.

Before you start

FastAPI builds on these; the tree links to the exact lessons you need.

How deep do you want to go?

1. EssentialsRead and write simple code, do the everyday basics7 lessons · 1 hour in total
2. PracticalUse it productively at work, with the usual idioms17 lessons · 3 hours in total
3. AdvancedThe less common features, performance and trade-offs24 lessons · 5 hours in total
4. ExpertInternals and the edge cases experts know28 lessons · 6 hours in total

The FastAPI tree

FastAPIWhat FastAPI is and your first appWhat FastAPI is andyour first appPath operations and HTTP methodsPath operations andHTTP methodsInteractive API docs: /docs and /redocInteractive API docs:/docs and /redocPath parametersPath parametersQuery parametersQuery parametersRequest bodies with Pydantic modelsRequest bodies withPydantic modelsResponse models and status codesResponse modelsand status codesValidation with Annotated, Query, Path and FieldValidation withAnnotated, Query,…Errors: HTTPException and exception handlersErrors:HTTPException and…Dependency injection with DependsDependency injectionwith DependsAPIRouter and project structureAPIRouter andproject structureSettings with pydantic-settingsSettings withpydantic-settingsDatabases with SQLModelDatabases withSQLModelAuthentication: OAuth2 password flow and JWTAuthentication:OAuth2 password f…Middleware and CORSMiddleware andCORSBackground tasksBackground tasksTesting with TestClient and pytestTesting withTestClient and pytestVirtual environments and pipVirtual environmentsand pipType hints basicsType hints basicsClasses and instancesClasses andinstancesExceptions in depthExceptions in depthSELECT: reading dataSELECT: reading dataCreating and altering tablesCreating and alteringtablesTesting with pytest and unittestTesting with pytestand unittest
Essentials and Practical shown (17 of 28 lessons); the full list is below. Click a lesson to read it.

All 28 lessons, in order

Getting started

  1. What FastAPI is and your first app · Essentials · 10 min

    Install FastAPI, write a five-line app and serve JSON over HTTP with the fastapi dev command.

  2. Path operations and HTTP methods · Essentials · 8 min

    Map URL paths and HTTP methods to Python functions with @app.get, @app.post and the other method decorators.

  3. Interactive API docs: /docs and /redoc · Essentials · 6 min

    Every app serves an OpenAPI schema plus Swagger UI and ReDoc pages generated from your code.

Request data

  1. Path parameters · Essentials · 8 min

    Capture parts of the URL like /items/{item_id} as typed function arguments that FastAPI converts and validates.

  2. Query parameters · Essentials · 8 min

    Function parameters that aren't in the path become query parameters like ?skip=0&limit=10: typed, optional or required.

  3. Request bodies with Pydantic models · Essentials · 12 min

    Declare a Pydantic BaseModel parameter and FastAPI reads, validates and parses the JSON request body into it.

  4. Validation with Annotated, Query, Path and Field · Practical · 14 min

    Add constraints like max_length, ge/le and regex patterns to parameters and model fields with Annotated metadata.

Responses and errors

  1. Response models and status codes · Essentials · 12 min

    Use return type annotations or response_model to shape, filter and document what an endpoint sends back.

  2. Errors: HTTPException and exception handlers · Practical · 12 min

    Raise HTTPException for expected failures, and register exception handlers that turn your own exceptions into responses.

  3. Uploads, file and streaming responses · Advanced · 14 min

    Accept uploads with UploadFile, send files with FileResponse, and stream generated data with StreamingResponse.

Dependencies and structure

  1. Dependency injection with Depends · Practical · 14 min

    Declare shared logic such as auth, pagination or DB sessions as functions, and let FastAPI call them and inject the results.

  2. APIRouter and project structure · Practical · 12 min

    Split a growing app into one router per feature, and include them with prefixes, tags and shared dependencies.

  3. Settings with pydantic-settings · Practical · 10 min

    Load configuration from environment variables and .env files into a typed, validated Settings class.

  4. Dependencies with yield and scopes · Advanced · 14 min

    Use yield in dependencies for setup and teardown, handle exceptions in them, and control when teardown runs with scope.

Data and security

  1. Databases with SQLModel · Practical · 18 min

    Define tables as SQLModel classes, get a session per request through a dependency, and run CRUD queries.

  2. Authentication: OAuth2 password flow and JWT · Practical · 20 min

    Issue signed JWT access tokens from a /token endpoint and protect routes with an OAuth2PasswordBearer dependency.

  3. Middleware and CORS · Practical · 12 min

    Run code around every request with middleware, and let browser front ends on other origins call your API with CORSMiddleware.

Async and real-time

  1. Background tasks · Practical · 8 min

    Schedule small jobs, like sending an email, to run after the response is sent, using the BackgroundTasks parameter.

  2. async def vs def and the threadpool · Advanced · 16 min

    How FastAPI runs async endpoints on the event loop and sync ones in a threadpool, and how to choose between them.

  3. Lifespan: startup and shutdown · Advanced · 10 min

    Create shared resources such as connection pools, HTTP clients or ML models once per process with a lifespan context manager.

  4. WebSockets · Advanced · 14 min

    Hold long-lived two-way connections with @app.websocket, handle disconnects, and know the limits of in-process broadcasting.

Testing and production

  1. Testing with TestClient and pytest · Practical · 14 min

    Call your app in-process with TestClient, swap dependencies with dependency_overrides, and assert on responses.

  2. Customizing OpenAPI · Advanced · 12 min

    Document extra responses, examples and tags, control operation ids for client generation, and post-process the schema.

  3. Deployment: workers, proxies and containers · Advanced · 16 min

    Run FastAPI in production with fastapi run or Uvicorn, choose worker counts, sit behind a proxy and package it in Docker.

  4. Scaling and observability in production · Expert · 18 min

    Size workers, threads and connection pools together, set timeouts, and instrument logs, metrics and traces per route.

Internals

  1. Under the hood: ASGI and Starlette · Expert · 18 min

    How an ASGI server calls your app with scope, receive and send, and how FastAPI layers its middleware stack and router on Starlette.

  2. How the dependency resolver works · Expert · 16 min

    FastAPI builds a dependency tree per route at startup and solves it per request: sequentially, cached by callable, errors aggregated.

  3. Pydantic v2 core and serialization speed · Expert · 16 min

    How Pydantic v2's Rust core validates and serializes, how FastAPI uses it, and how to keep hot paths fast.