Skip to content
Français
Sync not enabled: your progress stays in this browser My learning
Select theme
Français

FastAPI: build a REST API in Python

11 min read
Improve this page

Logo Python

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 fastapi reports nothing and installs an older version (0.162.5 in the python:3.10-slim image), whereas pip install fastapi==0.165.0 fails with No 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:

Terminal window
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.

Terminal window
mkdir inventaire && cd inventaire
python3 -m venv .venv
source .venv/bin/activate

On 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.

Terminal window
pip install "fastapi[standard]"

Check that both commands answer:

Terminal window
fastapi --version
uvicorn --version
FastAPI CLI version: 0.0.34
FastAPI Cloud CLI version: 0.28.1
Running uvicorn 0.54.0 with CPython 3.12.3 on Linux

The 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.

main.py
from fastapi import FastAPI, HTTPException
from 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 example
serveurs: 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 serveur

Three 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.

Terminal window
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:

Terminal window
uvicorn main:app --reload

main: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:

Terminal window
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:

Terminal window
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.

Terminal window
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:

Terminal window
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

PitfallConsequenceSolution
Virtual environment not activateduvicorn: command not found or fastapi: command not found even though the installation succeededsource .venv/bin/activate (the prompt shows (.venv)), then run again
Installing outside a venverror: externally-managed-environment (PEP 668)python3 -m venv .venv, activate, then pip install "fastapi[standard]"
Forgetting Uvicornuvicorn: command not foundInstall fastapi[standard] (or uvicorn[standard]) in the active venv
Wrong main:appError loading ASGI appUse the file:variable format (without .py)
Mixing up Pydantic 1 and 2Validator/config errorsRecent FastAPI requires Pydantic 2
No type on the bodyData not validatedDeclare a Pydantic model as a parameter
--reload in productionInstability, 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 422 errors).
  • The OpenAPI / Swagger documentation (/docs) is generated on its own.
  • You need an activated virtual environment: without one, pip install is refused on recent systems, or uvicorn stays unfindable.
  • In development, you run the application with fastapi dev main.py (or uvicorn 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

6 questions
6 min
70% to pass

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

FAQ: frequently asked questions