2. Python + SQL Databases
Practice Lab 1: Build a Safe SQLite Enrollment Repository
Combine Module 2 skills in a live in-memory SQLite lab: write parameterized inserts, foreign-key lookups, atomic enrollment counts, and automated assert checks.
- Implement parameterized CRUD methods inside a clean Repository class
- Enforce duplicate-enrollment checks cleanly with transactions and UNIQUE constraints
- Aggregate joined SQL counts directly into Python dictionaries
Put Modules 1 and 2 together by building AcademyRepository, a clean SQLite persistence layer backing a student enrollment API.
1. Architecture & Data Integrity Context
In a production FastAPI backend, routes never execute raw SQL directly. Instead, HTTP endpoints delegate persistence to a dedicated repository:
POST /enrollments ─▶ Pydantic Schema ─▶ AcademyRepository ─▶ SQLite (students + enrollments)
│
Enforces PRAGMA foreign_keys = ON & UNIQUE constraintsEvery constraint inside __init__ protects your API even if two requests arrive at the same millisecond:
| Table / Constraint | SQL Definition | What It Prevents at Runtime |
|---|---|---|
students.email | TEXT NOT NULL UNIQUE | Duplicate student accounts with the same email |
enrollments composite key | UNIQUE(student_id, course_slug) | Enrolling the same student twice in one course |
enrollments.student_id | FOREIGN KEY(student_id) REFERENCES students(id) | Orphaned enrollments for nonexistent student IDs |
2. How FastAPI Routes Use AcademyRepository
Once your repository is built, an API route stays tiny and readable—it simply catches sqlite3.IntegrityError and maps it to HTTP 409 Conflict:
@app.post("/enrollments", status_code=201)
def enroll_student(payload: EnrollRequest, db: sqlite3.Connection = Depends(get_db)):
repo = AcademyRepository(db)
try:
repo.enroll(payload.student_id, payload.course_slug)
except sqlite3.IntegrityError:
raise HTTPException(status_code=409, detail="Already enrolled or invalid student_id")
return {"status": "enrolled"}3. Step-by-Step Method Contracts
Complete the three TODO methods in the live sandbox below:
add_student(self, name: str, email: str) -> int- Wrap
INSERT INTO students (name, email) VALUES (?, ?)insidewith self.conn:so it commits atomically. - Return
int(cur.lastrowid)—the auto-incremented primary key assigned by SQLite.
- Wrap
enroll(self, student_id: int, course_slug: str) -> None- Execute
INSERT INTO enrollments (student_id, course_slug) VALUES (?, ?)insidewith self.conn:. - Rely on SQLite's
FOREIGN KEYandUNIQUE(student_id, course_slug)constraints so invalid student IDs or duplicate enrollments raisesqlite3.IntegrityErrorinstead of corrupting data.
- Execute
counts_by_course(self) -> dict[str, int]- Query
SELECT course_slug, COUNT(*) AS total FROM enrollments GROUP BY course_slugwith.fetchall(). - Because
self.conn.row_factory = sqlite3.Row, map each row cleanly via{row["course_slug"]: row["total"] for row in rows}.
- Query
- Never omit
with self.conn:on writes — without a commit, inserts stay uncommitted and disappear when the connection closes. - Never build SQL with f-strings — always pass
(name, email)and(student_id, course_slug)as parameter tuples to?placeholders. - Remember
PRAGMA foreign_keys = ON— SQLite ignores foreign key constraints by default on every new connection unless explicitly enabled.
4. Interactive Lab Sandbox
Click “Run Code” to execute this snippet right in your browser.
5. Stretch Verification: Test Your Constraints
Once the starter assertions pass, test that your database constraints protect against bad API inputs by adding two quick try/except sqlite3.IntegrityError checks in the playground:
- Enrolling
s1in"python-backend"a second time should raisesqlite3.IntegrityError(which an API endpoint turns into409 Conflict). - Enrolling a nonexistent student
999should raisesqlite3.IntegrityError(which an API endpoint turns into404 Not Foundor400 Bad Request).