Python FastAPI

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

The reference material consulted while preparing these pages is listed in the section bibliography.

This section is written against FastAPI 0.142.2 (released 2026-09-30), Pydantic 2.13 and Starlette 1.7, checked on 2026-10-02. FastAPI supports Python 3.10 through 3.14. FastAPI is still a 0.x project, so every page notes the version in which a feature appeared and the guide recommends pinning the version you deploy.

What FastAPI is

FastAPI is a Python web framework for building HTTP APIs. It is deliberately thin: Starlette provides the ASGI toolkit (routing, middleware, requests and responses, WebSockets, background tasks, the test client), Pydantic provides validation, serialization and JSON Schema, and FastAPI adds what ties them together: parameters declared with ordinary Python type hints, a dependency injection system, and automatic generation of an OpenAPI 3.1 description with interactive documentation (Swagger UI and ReDoc).

The practical result is that one declaration does several jobs at once. A function signature such as def read_book(book_id: int) converts the path value to an integer, rejects bad input with a structured 422 error, documents the parameter in /docs, and gives your editor full autocompletion.

This section is for developers who:

  • know Python (or are coming from Flask, Django, Spring Boot, ASP.NET Core or Express) and want to build and run production-grade JSON APIs

  • want one coherent path from a first endpoint to testing, security, data access, deployment and observability

  • need the current idioms (Annotated, Pydantic v2, lifespan, the fastapi CLI, PyJWT and pwdlib) rather than the patterns found in older tutorials

The Bookshelf API scenario

Every example builds one small original service, the Bookshelf API, so the pages fit together instead of being isolated snippets:

  • books, authors and reviews resources with full CRUD

  • users with OAuth2 password login, JWT access tokens and scopes

  • cover-image uploads

  • a live "new review" feed over Server-Sent Events

  • a WebSocket chat per book

  • a Jinja and single-page-application front end

  • PostgreSQL through SQLModel in production and SQLite in tests

Diagram of the Bookshelf API. Clients reach a reverse proxy and an ASGI server running Uvicorn workers. Behind them the FastAPI application contains middleware, routers for books, authors, reviews, authentication, covers, a review stream and a WebSocket chat, and a layer of dependencies and models. The application reads and writes PostgreSQL through SQLModel sessions and stores uploaded covers in cover storage. The same application also serves the interactive docs, openapi.json, Jinja pages and the single-page front end.
Figure 1. The Bookshelf API: clients, ASGI server, application layers and data stores

The final project layout (app/main.py, app/routers/, app/models/, app/services/, app/db.py, app/settings.py and tests/) is assembled on Project Structure & Layered Architecture.

Reading path

The pages are ordered so that each one builds on the previous ones. Read them in this order the first time, then use them as a reference:

  1. Foundations: what FastAPI is made of, a first running app, the Python typing and async concepts it relies on.

  2. Request data: path and query parameters, bodies and Pydantic models, headers, cookies, forms and uploads.

  3. Responses and errors: response models, status codes, error handling, custom and streamed responses.

  4. Dependencies: dependency injection and dependencies with yield.

  5. Security: authentication fundamentals, OAuth2 with JWT, scopes, CORS and proxy headers.

  6. Data and application structure: SQL with SQLModel, other data stores, layered project layout, settings and lifespan.

  7. OpenAPI: the generated contract and how to shape it.

  8. Real-time and web: WebSockets, static files, templates, front ends, sub-applications.

  9. Testing: TestClient, dependency overrides, property-based and load testing.

  10. Production: servers and workers, containers, performance and observability.

  11. Beyond the basics: serving data-science and AI workloads, and what changed between versions.

The cheat sheet at FastAPI Cheat Sheet condenses the whole section onto one page for quick lookup.

mindmap root((Python FastAPI)) Foundations Introduction and architecture Getting started Types and Annotated Async and concurrency Request data Path and query parameters Body and Pydantic models Headers and cookies Forms and uploads Responses and errors Response models Status codes and errors Custom responses Streaming and SSE Dependencies Dependency injection Dependencies with yield Security Security fundamentals OAuth2 and JWT Scopes CORS and proxies Data and structure SQLModel NoSQL stores Layered architecture Settings and lifespan OpenAPI Interactive docs Real-time and web WebSockets Static files and templates Sub-applications Testing TestClient Property-based and load tests Production Deployment Docker and Kubernetes Performance and observability Beyond the basics Data science and AI Changes and migration
Figure 2. The section at a glance

The FastAPI pages link to existing material instead of repeating it, and cover only what FastAPI adds.

Topic Where it lives How the FastAPI section relates

The Python language, typing, asyncio, virtual environments, pytest

Python Reference, including Type Hints, Concurrency & Async, Virtual Environments & Packaging and Testing

FastAPI pages link here for general Python and cover only what FastAPI adds.

GraphQL with Python

Python: Getting Started, Strawberry with FastAPI and Ariadne: Schema-First GraphQL

The sub-applications page links here and does not repeat GraphQL.

OAuth 2.0, OpenID Connect, JWT theory

OAuth Reference

The security pages cover only FastAPI’s utilities (OAuth2PasswordBearer, Security, scopes, JWT handling).

Docker and containers

Docker

The Docker page shows only the FastAPI-specific Dockerfile and Compose files.

Cloud deployment

Azure, AWS (Amazon Web Services) and Google Cloud

The deployment page points to the managed container services described there.

Database engines

SQL Reference, MongoDB Reference, Redis Reference, Elasticsearch Reference and Vector Databases & RAG

The data pages cover only how to use each from FastAPI (sessions and clients as dependencies, lifespan-managed clients).

Architecture

Architecture, Architectural Patterns and Starting a New Project: Which Path and Which Technologies

The project-structure page links the patterns (hexagonal, repository, domain-driven design).

REST APIs in other stacks

REST APIs with Spring MVC and WebFlux, Quarkus Reference and Minimal APIs

The introduction’s framework comparison presents these as the same idea in other stacks.

Messaging

Messaging Reference

The background-tasks page points here for work that outgrows BackgroundTasks.

Kubernetes

Kubernetes Reference

The Docker & Kubernetes page shows only the FastAPI-specific Deployment, probes and graceful shutdown.

AI frameworks and models

LangChain and Hugging Face

The data-science and AI serving page stays introductory and points here for depth.

Related topics that are planned but not yet part of this site (a programming-languages comparison and API gateways) are mentioned in prose only, where relevant.

Bibliography

Every source used to prepare this section is listed here, each linked to its official site. Individual pages list the subset they derive from under their own == References heading.

Book

Third-party tools used by the pages

The book is a consulted reference for the narrative and structure of some topics; it is not reproduced here. The official documentation linked above is authoritative, and where the two differ, the documentation of the version you run prevails.