FastAPI is a modern Python web framework for building REST APIs quickly and reliably. It provides automatic OpenAPI documentation, request validation via Pydantic models, and async support out of the box. Here is a complete quickstart to get a validated, documented API running in 15 minutes.
Install and Scaffold
Create a virtual environment and install FastAPI with uvicorn:
python -m venv venv
source venv/bin/activate
pip install fastapi uvicorn[standard] sqlmodel
Your First Endpoint
Create `main.py` with a basic CRUD structure:
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
description: str | None = None
price: float
in_stock: bool = True
items: list[Item] = []
@app.get("/")
def root():
return {"message": "API is running"}
@app.get("/items")
def list_items():
return items
@app.post("/items", status_code=201)
def create_item(item: Item):
items.append(item)
return item
Run it with `uvicorn main:app --reload` and visit `http://localhost:8000/docs`. You will see auto-generated Swagger documentation for every endpoint, including request and response schemas derived from your Pydantic models.
Adding a Database With SQLModel
SQLModel (by the same creator as FastAPI) bridges SQLAlchemy and Pydantic, letting you define database models that also serve as API schemas:
from sqlmodel import SQLModel, Field, Session, create_engine, select
class Item(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str
price: float
in_stock: bool = True
engine = create_engine("sqlite:///database.db")
SQLModel.metadata.create_all(engine)
@app.post("/items", status_code=201)
def create_item(item: Item):
with Session(engine) as session:
session.add(item)
session.commit()
session.refresh(item)
return item
In 15 minutes you have a validated, documented, database-backed REST API. FastAPI handles serialization, validation, error responses, and documentation automatically. For quick prototypes or microservices, it is hard to beat.
Key Takeaways
- FastAPI provides automatic OpenAPI documentation from your Python type hints - Pydantic models handle request validation and serialization with zero extra code - SQLModel bridges SQLAlchemy and Pydantic for clean database integration - The uvicorn server supports hot-reloading for fast development iteration - FastAPI supports async endpoints for high-concurrency workloads - Auto-generated Swagger UI lets you test endpoints directly in the browser - The framework is one of the fastest Python web frameworks available