FastAPI is a Python framework for writing a REST API. From plain type annotations, it generates data validation and interactive OpenAPI documentation. This guide has you build an API from scratch: installation in a virtual environment, first routes, validation with Pydantic, error handling and documentation. Everything was tested on FastAPI 0.165 (Pydantic 2.14, Python 3.12).
This page is the hands-on companion to the concept: if you first want to know what a REST API is, read REST API: definition and best practices (in French).
What you will learn
- Install FastAPI and the Uvicorn server in a virtual environment
- Write GET and POST routes with type annotations
- Validate input data with Pydantic
- Return the right HTTP status codes and handle errors (404)
- Use the OpenAPI documentation that FastAPI generates for you
What is FastAPI?
FastAPI is a Python web framework for building APIs, built on Starlette (the asynchronous web layer) and Pydantic (data validation). Its principle: you type your functions and your data models, and FastAPI deduces the rest.
- The type of a parameter becomes a validation rule: invalid data is rejected with a clear error, without a single extra line of code.
- Pydantic models describe your objects: FastAPI serializes them to JSON and checks every field.
- The OpenAPI documentation (Swagger UI at
/docs) is generated from these types.
Flask is minimalist and leaves you to wire up validation and documentation yourself. FastAPI provides both out of the box, from your type annotations.
Prerequisites
- Python 3.11 or later: FastAPI 0.165 requires Python 3.11. On Python
3.10,
pip install fastapireports nothing and installs an older version (0.162.5 in thepython:3.10-slimimage), whereaspip install fastapi==0.165.0fails withNo matching distribution found. This guide uses Python 3.12. - A way to isolate dependencies: a virtual environment or uv (in French).
Installing FastAPI
To answer HTTP requests, FastAPI needs an ASGI server (ASGI is the standard
interface between a web server and an asynchronous Python application). This
guide uses Uvicorn. The official documentation recommends installing FastAPI
with the standard extra: it brings FastAPI, Uvicorn and the fastapi
command (fastapi dev, fastapi run).
On Ubuntu 24.04, Debian 13 and recent distributions, pip install outside a
virtual environment is refused: the system Python is reserved for its own
packages (PEP 668). The following command therefore fails on these systems:
pip install "fastapi[standard]"error: externally-managed-environment
× This environment is externally managed╰─> To install Python packages system-wide, try apt install python3-xyz, where xyz is the package you are trying to install....hint: See PEP 668 for the detailed specification.The ubuntu:24.04 container image contains neither Python nor pip. First
install the two required packages with apt install python3 python3-venv. The
pip command then answers pip: command not found, because the
python3-pip package is still missing. On an Ubuntu desktop installation, the
message may differ. The virtual environment created below brings its own
pip, which works around both cases.
So create a virtual environment, a .venv folder that holds its own
Python and its own packages, then activate it. Activation changes the current
terminal so that python, pip and installed programs are looked up in
.venv.
mkdir inventaire && cd inventairepython3 -m venv .venvsource .venv/bin/activateOn Ubuntu and Debian, if python3 -m venv answers ensurepip is not available, first install the missing package: sudo apt install python3-venv.
After activation, the terminal prompt starts with (.venv). Without
activation, uvicorn stays unfindable (uvicorn: command not found),
even though the installation succeeded in .venv. You must run
source .venv/bin/activate again in every new terminal.
Now install FastAPI in the activated environment. With uv, you can create the
environment with uv venv instead of python3 -m venv .venv: the .venv
folder and the activation are the same.
pip install "fastapi[standard]"uv pip install "fastapi[standard]"Check that both commands answer:
fastapi --versionuvicorn --versionFastAPI CLI version: 0.0.34FastAPI Cloud CLI version: 0.28.1Running uvicorn 0.54.0 with CPython 3.12.3 on LinuxThe versions installed by pip install "fastapi[standard]": FastAPI
0.165.0, Pydantic 2.14.4, Uvicorn 0.54.0. Yours will probably be
more recent.
Your first API
Create a main.py file. It exposes a small server inventory: a Pydantic
model describes a server, and a few routes handle it. The identifiers
are French (Serveur means server, serveurs the servers, lire_serveur
reads one server) so that the code matches the outputs shown below exactly.
from fastapi import FastAPI, HTTPExceptionfrom pydantic import BaseModel, Field
app = FastAPI(title="API Inventaire serveurs", version="1.0.0")
class Serveur(BaseModel): hostname: str = Field(min_length=1, examples=["web-prod-01"]) ip: str env: str = "prod"
# in-memory "database" for the exampleserveurs: dict[int, Serveur] = { 1: Serveur(hostname="web-prod-01", ip="10.0.1.10", env="prod"),}
@app.get("/serveurs")def lister_serveurs() -> list[Serveur]: return list(serveurs.values())
@app.get("/serveurs/{serveur_id}")def lire_serveur(serveur_id: int) -> Serveur: if serveur_id not in serveurs: raise HTTPException(status_code=404, detail="Serveur introuvable") return serveurs[serveur_id]
@app.post("/serveurs", status_code=201)def creer_serveur(serveur: Serveur) -> Serveur: nouvel_id = max(serveurs) + 1 serveurs[nouvel_id] = serveur return serveurThree things to note: the @app.get(...) decorator binds a route to a
function, the serveur_id: int parameter converts and validates the URL,
and the -> Serveur return type documents the response.
Running the server
From the folder containing main.py, with the virtual environment activated,
the fastapi dev command starts the application in development mode. It
reloads the server on every code change.
fastapi dev main.py Starting FastAPI in development mode
Using import string: main:app
Server started at http://127.0.0.1:8000 Documentation at http://127.0.0.1:8000/docs...INFO: Will watch for changes in these directories: ['/work/inventaire']INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)INFO: Application startup complete.The Server started at line gives the server address, and Documentation at
the address of the interactive documentation, presented below. fastapi dev
starts Uvicorn for you. You can also call Uvicorn directly, which gives the
same server with hot reload:
uvicorn main:app --reloadmain:app means "the app object of the main module". Leave the server
running in this terminal and test the routes with curl from a second
terminal:
curl http://127.0.0.1:8000/serveurs# [{"hostname":"web-prod-01","ip":"10.0.1.10","env":"prod"}]
curl -i -X POST http://127.0.0.1:8000/serveurs \ -H "Content-Type: application/json" \ -d '{"hostname":"db-prod-01","ip":"10.0.1.20","env":"prod"}'# HTTP/1.1 201 Created (headers shortened)# {"hostname":"db-prod-01","ip":"10.0.1.20","env":"prod"}A missing resource returns the right code thanks to HTTPException:
curl -i http://127.0.0.1:8000/serveurs/99# HTTP/1.1 404 Not Found (headers shortened)# {"detail":"Serveur introuvable"}Automatic validation
Validation is declared in the model. The hostname field of Serveur is
declared Field(min_length=1): send an empty hostname to see FastAPI's
response.
curl -X POST http://127.0.0.1:8000/serveurs \ -H "Content-Type: application/json" \ -d '{"hostname":"","ip":"10.0.0.1"}'FastAPI answers 422 with a precise error, without you having written a
single if:
{ "detail": [ { "type": "string_too_short", "loc": ["body", "hostname"], "msg": "String should have at least 1 character", "input": "", "ctx": {"min_length": 1} } ]}The loc field says exactly where the error is. Pydantic does the
work: your types are the contract, and the contract is enforced on its own.
Documentation generated for you
Open http://127.0.0.1:8000/docs: FastAPI displays an interactive
Swagger UI where you can try every route. The raw schema is at
/openapi.json:
curl -s http://127.0.0.1:8000/openapi.json | head# {"openapi":"3.1.0","info":{"title":"API Inventaire serveurs",...}You get an OpenAPI 3.1 specification derived from your types, with no configuration at all. To understand what you are generating here, see the REST API best practices (in French).
Common pitfalls
| Pitfall | Consequence | Solution |
|---|---|---|
| Virtual environment not activated | uvicorn: command not found or fastapi: command not found even though the installation succeeded | source .venv/bin/activate (the prompt shows (.venv)), then run again |
| Installing outside a venv | error: externally-managed-environment (PEP 668) | python3 -m venv .venv, activate, then pip install "fastapi[standard]" |
| Forgetting Uvicorn | uvicorn: command not found | Install fastapi[standard] (or uvicorn[standard]) in the active venv |
Wrong main:app | Error loading ASGI app | Use the file:variable format (without .py) |
| Mixing up Pydantic 1 and 2 | Validator/config errors | Recent FastAPI requires Pydantic 2 |
| No type on the body | Data not validated | Declare a Pydantic model as a parameter |
--reload in production | Instability, overhead | --reload in dev only; in prod, several workers |
Key takeaways
- FastAPI builds REST APIs in Python from type annotations.
- Input validation is automatic through Pydantic (precise
422errors). - The OpenAPI / Swagger documentation (
/docs) is generated on its own. - You need an activated virtual environment: without one,
pip installis refused on recent systems, oruvicornstays unfindable. - In development, you run the application with
fastapi dev main.py(oruvicorn main:app --reload). - With Flask, validation and documentation are wired by hand.
Knowledge check
Six questions on installing in a virtual environment, routes, validation with Pydantic and the OpenAPI documentation.
Knowledge check
Check what you have learned with this interactive quiz
How it works
- The timer starts when you click Start
- Multiple choice, true/false and short answer questions
- You can move between questions
- Detailed results are shown at the end
Starts the quiz and the timer
Review
(0/0)Result saved on this device. It will be sent to your account at the next sync. Sync now
Score by domain
A domain groups several guides and gets several questions, so its score is more reliable than a per-topic score, which often rests on a single question.
Summary
Strengths
No topic passed at 80% on at least two questions yet.
Weak areas
No topic below the pass mark.
Recommended next
Hints before you try again?
A new full quiz with random questions
Work again only on the questions you missed
FAQ: frequently asked questions
fastapi[standard] is installed, run:fastapi dev main.py
This command starts Uvicorn, the ASGI server that runs the application, and reloads the code on every change. FastAPI finds the app object in main.py by itself. The alternative uvicorn main:app --reload gives the same server: main is the file (main.py), app is the FastAPI object. Hot reload is meant for development; in production, use fastapi run or several workers, without reload.pip install "fastapi[standard]" live in the .venv folder. As long as the virtual environment is not activated in the terminal, the shell cannot see them and answers uvicorn: command not found, even though the installation succeeded.source .venv/bin/activate
fastapi --version
After activation, the prompt starts with (.venv). You must run this command again in every new terminal.BaseModel) as a route parameter, and FastAPI automatically rejects an invalid request with a 422 code and a precise error (faulty field in loc, clear message), without any hand-written validation. The type is the contract, and the contract is enforced on its own./docs, an alternative ReDoc at /redoc, and the raw OpenAPI 3.1 schema at /openapi.json. No configuration: the documentation derives from your type annotations.