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.

4 min readUpdated 2026-11-30
In This Lesson
  • 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:

text
POST /enrollments ─▶ Pydantic Schema ─▶ AcademyRepository ─▶ SQLite (students + enrollments)
                                              │
                         Enforces PRAGMA foreign_keys = ON & UNIQUE constraints

Every constraint inside __init__ protects your API even if two requests arrive at the same millisecond:

Table / ConstraintSQL DefinitionWhat It Prevents at Runtime
students.emailTEXT NOT NULL UNIQUEDuplicate student accounts with the same email
enrollments composite keyUNIQUE(student_id, course_slug)Enrolling the same student twice in one course
enrollments.student_idFOREIGN 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:

python
@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:

  1. add_student(self, name: str, email: str) -> int
    • Wrap INSERT INTO students (name, email) VALUES (?, ?) inside with self.conn: so it commits atomically.
    • Return int(cur.lastrowid)—the auto-incremented primary key assigned by SQLite.
  2. enroll(self, student_id: int, course_slug: str) -> None
    • Execute INSERT INTO enrollments (student_id, course_slug) VALUES (?, ?) inside with self.conn:.
    • Rely on SQLite's FOREIGN KEY and UNIQUE(student_id, course_slug) constraints so invalid student IDs or duplicate enrollments raise sqlite3.IntegrityError instead of corrupting data.
  3. counts_by_course(self) -> dict[str, int]
    • Query SELECT course_slug, COUNT(*) AS total FROM enrollments GROUP BY course_slug with .fetchall().
    • Because self.conn.row_factory = sqlite3.Row, map each row cleanly via {row["course_slug"]: row["total"] for row in rows}.
Common Repository Pitfalls to Avoid
  • 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

Python 3Lab 1: Implement AcademyRepository
Output

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 s1 in "python-backend" a second time should raise sqlite3.IntegrityError (which an API endpoint turns into 409 Conflict).
  • Enrolling a nonexistent student 999 should raise sqlite3.IntegrityError (which an API endpoint turns into 404 Not Found or 400 Bad Request).

Lab 1 Completion Checklist

0/3 done