Build a REST API with FastAPI and SQLite
From zero to a documented, validated CRUD API in one file. FastAPI is the fastest way to ship a Python back end.
In this guide
FastAPI gives you automatic request validation, serialisation and interactive docs — for free, from type hints alone. Paired with SQLite you have a real, deployable API in one file.
Install and model your data
pip install "fastapi[standard]" sqlmodelfrom typing import Optional
from sqlmodel import SQLModel, Field, create_engine, Session, select
from fastapi import FastAPI, HTTPException
class Item(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
price: float
in_stock: bool = True
engine = create_engine("sqlite:///inventory.db")
SQLModel.metadata.create_all(engine)
app = FastAPI(title="Inventory API")Read (with validation for free)
@app.get("/items")
def list_items():
with Session(engine) as s:
return s.exec(select(Item)).all()
@app.get("/items/{item_id}")
def get_item(item_id: int):
with Session(engine) as s:
item = s.get(Item, item_id)
if not item:
raise HTTPException(404, "item not found")
return itemCreate and update
@app.post("/items", status_code=201)
def create_item(item: Item):
with Session(engine) as s:
s.add(item)
s.commit()
s.refresh(item)
return item
@app.patch("/items/{item_id}")
def update_item(item_id: int, patch: Item):
with Session(engine) as s:
item = s.get(Item, item_id)
if not item:
raise HTTPException(404, "item not found")
for k, v in patch.model_dump(exclude_unset=True).items():
setattr(item, k, v)
s.add(item); s.commit(); s.refresh(item)
return itemRun it and see the docs
uvicorn main:app --reload
# open http://localhost:8000/docs → interactive Swagger UIThose docs aren't just for show — every endpoint is callable right from the browser. It's the fastest feedback loop in web development.
Swap SQLite for Postgres by changing one connection string when you grow. That's the whole migration story — FastAPI is that clean.
More from the lab
Docker for Beginners: Containers Explained
What a container actually is, how a Dockerfile works, and how to ship an app that runs everywhere.
DevOpsA Clean Git Branching Strategy for Teams
Keep main green and releases boring with a lightweight trunk-based Git workflow.
AI & MLBuild a Local Chatbot with Ollama, Python & React
Run an LLM on your own machine with Ollama and put a chat UI in front of it — no cloud, no keys.
Want us to build this for you?
We turn tutorials like these into production systems every day. Tell us what you need.
Start a project →