3. Building Web APIs with FastAPI & Pydantic
Full CRUD Endpoints, HTTPException & Dependency Injection
Connect FastAPI routes cleanly to SQLite repositories using Depends(), raise explicit 404/409 responses with HTTPException, and implement complete POST/GET/PATCH/DELETE CRUD.
- Manage per-request database connections cleanly with FastAPI Depends() and yield
- Return clean 404 and 409 error responses using HTTPException
- Implement full Create, Read, Partial Update (PATCH), and Delete endpoints
Now let's connect Module 2's SQLite Repository with Module 3's FastAPI + Pydantic schemas using FastAPI's cleanest architectural feature: Depends() Dependency Injection.
1. Architecture: Full CRUD Request Lifecycle with Depends()
Watch how a single PATCH /tasks/42 request flows through FastAPI's dependency system:
PATCH /tasks/42 {"completed": true}
│
├─▶ 1. Pydantic parses path (42) & TaskUpdate body
├─▶ 2. Depends(get_db) runs up to `yield conn` (opens SQLite + PRAGMA foreign_keys)
├─▶ 3. Route handler calls Repository / SQL UPDATE ... WHERE id = ?
├─▶ 4. Response serialized (200 JSON) or HTTPException raised (404 / 409)
└─▶ 5. `finally: conn.close()` ALWAYS runs after response is sent!2. Per-Request Database Cleanup with Depends() + yield
Instead of opening/closing SQLite connections inside every single route, write one generator dependency that yields a connection and guarantees cleanup in finally:—even if the route raises an HTTPException or crashes:
import sqlite3
from fastapi import Depends, FastAPI
app = FastAPI()
def get_db():
conn = sqlite3.connect("app.db", check_same_thread=False)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA foreign_keys = ON")
try:
yield conn
finally:
conn.close()Two huge advantages of Depends(get_db):
- Per-request caching: If two dependencies in the same request both ask for
Depends(get_db), FastAPI reuses the sameconnfor that request by default. - Zero-effort testing: In
pytest, you swapget_dbwith an isolated test database in one line viaapp.dependency_overrides[get_db] = override_get_db!
3. Explicit Errors with HTTPException (404 vs 409)
When a record isn't found (None) or violates a uniqueness rule (like a duplicate email or slug), raise HTTPException instead of returning 200 with an error dict:
from fastapi import HTTPException, status
@app.get("/tasks/{task_id}")
def get_task(task_id: int, db: sqlite3.Connection = Depends(get_db)):
row = db.execute("SELECT * FROM tasks WHERE id = ?", (task_id,)).fetchone()
if row is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Task {task_id} not found",
)
return dict(row)When handling POST uniqueness errors (sqlite3.IntegrityError), catch it explicitly and return 409 Conflict—never let an unhandled IntegrityError leak as a 500 Internal Server Error.
4. Partial Updates (PATCH) with model_dump(exclude_unset=True)
Recall PUT vs PATCH:
PUT /tasks/42replaces the entire task (all required fields must be sent).PATCH /tasks/42updates only the fields the user included (e.g.,{"completed": true}without repeating"title").
In Pydantic v2, payload.model_dump(exclude_unset=True) returns a dictionary containing only the fields actually present in the JSON request—skipping defaults that the client omitted!
class TaskUpdate(BaseModel):
title: str | None = Field(default=None, min_length=1, max_length=120)
completed: bool | None = None
@app.patch("/tasks/{task_id}")
def update_task(task_id: int, payload: TaskUpdate, db: sqlite3.Connection = Depends(get_db)):
updates = payload.model_dump(exclude_unset=True)
if not updates:
raise HTTPException(status_code=400, detail="No fields provided to update")
# Apply only keys present in `updates`, then check rowcount / return 404 if missing
...- Never construct
SET {col} = ?directly from untrusted keys without validating against an allowlist of model fields (e.g.{"title", "completed"}) and always includeWHERE id = ?. - On
DELETE /tasks/{task_id}decorated withstatus_code=status.HTTP_204_NO_CONTENT, checkif cur.rowcount == 0: raise HTTPException(404, ...)and returnNone(an HTTP204response must have an empty body!).
Decorate delete endpoints with @app.delete("/tasks/{task_id}", status_code=status.HTTP_204_NO_CONTENT) and return None after deleting the row (or raise 404 if cur.rowcount == 0).
Try It Yourself in the Playground
Test a complete SQLite-backed CRUD service (create, get, patch, delete) simulating exclude_unset and 404 errors right here:
Click “Run Code” to execute this snippet right in your browser.
Mini-Challenge: Why is payload.model_dump(exclude_unset=True) critical for PATCH endpoints?
Quick Checkpoints
In a FastAPI dependency like def get_db(): try: yield conn finally: conn.close(), when does conn.close() execute?
What should a GET /items/{id} endpoint do when no item exists with that id?