Walk me through a practical project with FastAPI. Be patient and detailed in your…
- User
Walk me through a practical project with FastAPI. Be patient and detailed in your teachings.
- Assistant
Below is a step-by-step walkthrough of a small but realistic FastAPI project: a “To-Do List” API backed by a SQLite database. We’ll cover:
- Project goals
- Environment setup
- Directory layout
- Database setup with SQLAlchemy + context manager
- Pydantic schemas (request/response models)
- Dependency for database sessions
- CRUD endpoints
- Running & testing
—
1. Project Goals
We want an API that allows clients to:
- Create a to-do item (title, description, “done” flag)
- Read all to-dos or a single to-do by ID
- Update a to-do
- Delete a to-do
We’ll persist data in SQLite via SQLAlchemy, use Pydantic for data validation, and demonstrate best practices (lifecycle management, dependencies, error handling).
—
2. Environment Setup
- Create & activate a virtualenv:
python3 -m venv venv source venv/bin/activate - Install dependencies:
We’ll use SQLAlchemy (v1.4+) with its async support over SQLite.pip install fastapi uvicorn sqlalchemy aiosqlite
—
3. Directory Layout
todo_app/ ├── main.py ├── db.py ├── models.py ├── schemas.py └── crud.py- db.py: engine + session management
- models.py: SQLAlchemy ORM models
- schemas.py: Pydantic request/response models
- crud.py: functions to Create/Read/Update/Delete
- main.py: FastAPI app, routers, dependencies
—
4. Database Setup (db.py)
We’ll create an async engine & sessionmaker, and manage its lifespan via FastAPI’s
lifespancontext manager.# db.py import asyncio from sqlalchemy.ext.asyncio import ( AsyncEngine, create_async_engine, AsyncSession ) from sqlalchemy.orm import sessionmaker from contextlib import asynccontextmanager DATABASE_URL = "sqlite+aiosqlite:///./todo.db" # 1. Create AsyncEngine engine: AsyncEngine = create_async_engine( DATABASE_URL, echo=True, future=True ) # 2. Create session factory AsyncSessionLocal = sessionmaker( bind=engine, class_=AsyncSession, expire_on_commit=False, ) # 3. Lifespan context manager to handle startup/shutdown @asynccontextmanager async def lifespan(app): # Startup: create tables from models import Base async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) print("🗄️ Database tables created.") yield # Shutdown: dispose engine await engine.dispose() print("🗄️ Database connection closed.")Explanation:
- We use
sqlite+aiosqlitefor async SQLite. - On startup, we create tables; on shutdown, we dispose the engine.
—
5. ORM Models (models.py)
Define our
Todotable:# models.py from sqlalchemy import Column, Integer, String, Boolean from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Todo(Base): __tablename__ = "todos" id = Column(Integer, primary_key=True, index=True) title = Column(String, nullable=False) description = Column(String, default="") done = Column(Boolean, default=False)—
6. Pydantic Schemas (schemas.py)
We separate “input” (no ID) from “output” (with ID):
# schemas.py from pydantic import BaseModel from typing import Optional class TodoCreate(BaseModel): title: str description: Optional[str] = "" done: Optional[bool] = False class TodoUpdate(BaseModel): title: Optional[str] description: Optional[str] done: Optional[bool] class TodoRead(BaseModel): id: int title: str description: Optional[str] done: bool class Config: orm_mode = True # allow reading from ORM objects—
7. CRUD Utilities (crud.py)
We implement async functions that take a DB session and perform operations:
# crud.py from sqlalchemy import select, update, delete from sqlalchemy.ext.asyncio import AsyncSession from models import Todo from schemas import TodoCreate, TodoUpdate from typing import List, Optional async def get_todo(db: AsyncSession, todo_id: int) -> Optional[Todo]: result = await db.execute(select(Todo).where(Todo.id == todo_id)) return result.scalars().first() async def get_todos(db: AsyncSession) -> List[Todo]: result = await db.execute(select(Todo)) return result.scalars().all() async def create_todo(db: AsyncSession, todo_in: TodoCreate) -> Todo: todo = Todo(**todo_in.dict()) db.add(todo) await db.commit() await db.refresh(todo) # populate generated fields (e.g., id) return todo async def update_todo( db: AsyncSession, todo_id: int, todo_in: TodoUpdate ) -> Optional[Todo]: stmt = ( update(Todo) .where(Todo.id == todo_id) .values(**{k: v for k, v in todo_in.dict().items() if v is not None}) .execution_options(synchronize_session="fetch") ) await db.execute(stmt) await db.commit() return await get_todo(db, todo_id) async def delete_todo(db: AsyncSession, todo_id: int) -> bool: stmt = delete(Todo).where(Todo.id == todo_id) result = await db.execute(stmt) await db.commit() return result.rowcount > 0—
8. FastAPI App & Dependencies (main.py)
# main.py from fastapi import FastAPI, Depends, HTTPException, status from sqlalchemy.ext.asyncio import AsyncSession from db import lifespan, AsyncSessionLocal from crud import ( get_todo, get_todos, create_todo, update_todo, delete_todo ) from schemas import TodoCreate, TodoRead, TodoUpdate from typing import List app = FastAPI(lifespan=lifespan) # Dependency: provide a DB session per request async def get_db() -> AsyncSession: async with AsyncSessionLocal() as session: yield session @app.post( "/todos/", response_model=TodoRead, status_code=status.HTTP_201_CREATED ) async def api_create_todo( todo_in: TodoCreate, db: AsyncSession = Depends(get_db) ): return await create_todo(db, todo_in) @app.get( "/todos/", response_model=List[TodoRead] ) async def api_read_todos(db: AsyncSession = Depends(get_db)): return await get_todos(db) @app.get("/todos/{todo_id}", response_model=TodoRead) async def api_read_todo( todo_id: int, db: AsyncSession = Depends(get_db) ): todo = await get_todo(db, todo_id) if not todo: raise HTTPException(404, detail="To-do not found") return todo @app.put("/todos/{todo_id}", response_model=TodoRead) async def api_update_todo( todo_id: int, todo_in: TodoUpdate, db: AsyncSession = Depends(get_db) ): todo = await update_todo(db, todo_id, todo_in) if not todo: raise HTTPException(404, detail="To-do not found") return todo @app.delete( "/todos/{todo_id}", status_code=status.HTTP_204_NO_CONTENT ) async def api_delete_todo( todo_id: int, db: AsyncSession = Depends(get_db) ): deleted = await delete_todo(db, todo_id) if not deleted: raise HTTPException(404, detail="To-do not found") # returning None yields a 204 responseWhat’s happening?
- We inject
get_db()into every path, guaranteeing a fresh session and automatic cleanup. - Each path calls our
crud.pyfunctions. - We raise
HTTPExceptionfor 404s.
—
9. Running the App
uvicorn main:app --reload- Browse to http://127.0.0.1:8000/docs to see interactive Swagger UI.
- Try out create/read/update/delete directly in the docs.
—
10. Quick Testing with TestClient
Create
test_main.py:# test_main.py import pytest from httpx import AsyncClient from main import app @pytest.mark.asyncio async def test_crud_flow(): async with AsyncClient(app=app, base_url="http://test") as client: # 1. Create resp = await client.post("/todos/", json={"title": "Test", "description": "Desc"}) assert resp.status_code == 201 todo = resp.json() todo_id = todo["id"] # 2. Read resp = await client.get(f"/todos/{todo_id}") assert resp.status_code == 200 assert resp.json()["title"] == "Test" # 3. Update resp = await client.put(f"/todos/{todo_id}", json={"done": True}) assert resp.json()["done"] is True # 4. Delete resp = await client.delete(f"/todos/{todo_id}") assert resp.status_code == 204 # 5. Verify 404 on read resp = await client.get(f"/todos/{todo_id}") assert resp.status_code == 404Run tests:
pip install pytest httpx pytest—
🎉 Congratulations! You now have a fully working FastAPI “To-Do” backend:- Async database with SQLAlchemy
- Clean startup/shutdown via a lifespan context manager
- Pydantic schemas for validation & docs
- Dependencies for session management
- CRUD endpoints, error handling, and automated tests
From here you can extend this blueprint—add authentication, pagination, filtering, background tasks, or integrate with a real RDBMS.