6. Final Capstone Project

Capstone Project: Authenticated Task & Study Tracker REST API

Bring together REST design, SQLite transactions, Pydantic schemas, salted password hashing, Bearer token auth, FastAPI CRUD, and pytest TestClient into one complete backend project.

6 min readUpdated 2026-11-30
In This Lesson
  • Architect a clean multi-module FastAPI + SQLite backend with auth and CRUD
  • Protect user-owned tasks so users can only view, update, and delete their own records
  • Test registration, login, 401/403 guards, and CRUD flows automatically with pytest TestClient

Congratulations on reaching the final capstone of Python Backend, APIs & Databases! Now let's assemble everything—REST design, parameterized SQLite repositories, Pydantic validation, salted password hashing, HMAC/JWT Bearer tokens, FastAPI Depends(), and pytest TestClient—into a complete Task & Study Tracker REST API.

1. Interactive End-to-End Backend Engine (Live in Browser)

Run the complete SQLite + Auth + Ownership-Protected Task Service right here in Pyodide—it exercises signup, salted password login, token verification, creating tasks, blocking another user from touching your tasks, and deleting cleanly:

Python 3Capstone Engine: Auth + Ownership-Protected SQLite Task API
Output

Click “Run Code” to execute this snippet right in your browser.

2. Full FastAPI Project Layout for Your Machine

Create a clean folder task_api/ locally:

text
task_api/
├── main.py
├── test_main.py
└── requirements.txt

requirements.txt

text
fastapi[standard]
pyjwt
pytest
httpx

main.py

python
from datetime import datetime, timedelta, timezone
import hashlib
import hmac
import os
import secrets
import sqlite3

from fastapi import Depends, FastAPI, Header, HTTPException, status
import jwt
from pydantic import BaseModel, Field

JWT_SECRET = os.environ.get("JWT_SECRET", "dev-only-change-in-production-32chars")
ALGORITHM = "HS256"
DB_PATH = os.environ.get("DB_PATH", "tasks.db")

app = FastAPI(title="Yadav Academy Task Tracker API", version="1.0.0")


def init_db(db_path: str = DB_PATH) -> None:
    conn = sqlite3.connect(db_path)
    with conn:
        conn.execute("""
            CREATE TABLE IF NOT EXISTS users (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                email TEXT NOT NULL UNIQUE,
                password_hash TEXT NOT NULL
            )
        """)
        conn.execute("""
            CREATE TABLE IF NOT EXISTS tasks (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                owner_id INTEGER NOT NULL,
                title TEXT NOT NULL,
                completed INTEGER NOT NULL DEFAULT 0,
                FOREIGN KEY(owner_id) REFERENCES users(id)
            )
        """)
    conn.close()


def get_db():
    conn = sqlite3.connect(DB_PATH, check_same_thread=False)
    conn.row_factory = sqlite3.Row
    try:
        yield conn
    finally:
        conn.close()


class AuthRequest(BaseModel):
    email: str = Field(min_length=5)
    password: str = Field(min_length=8)


class TaskCreate(BaseModel):
    title: str = Field(min_length=1, max_length=120)


class TaskPublic(BaseModel):
    id: int
    title: str
    completed: bool


def hash_password(password: str) -> str:
    salt = secrets.token_hex(16)
    dk = hashlib.pbkdf2_hmac("sha256", password.encode(), salt.encode(), 200_000)
    return f"{salt}${dk.hex()}"


def verify_password(password: str, stored: str) -> bool:
    salt, expected = stored.split("$", 1)
    dk = hashlib.pbkdf2_hmac("sha256", password.encode(), salt.encode(), 200_000)
    return hmac.compare_digest(dk.hex(), expected)


def get_current_user_id(authorization: str | None = Header(default=None)) -> int:
    if not authorization or not authorization.startswith("Bearer "):
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Missing Bearer token")
    token = authorization.removeprefix("Bearer ").strip()
    try:
        payload = jwt.decode(token, JWT_SECRET, algorithms=[ALGORITHM])
        return int(payload["sub"])
    except jwt.PyJWTError:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid or expired token")


@app.on_event("startup")
def on_startup():
    init_db()


@app.get("/health")
def health():
    return {"status": "ok"}


@app.post("/auth/register", status_code=status.HTTP_201_CREATED)
def register(body: AuthRequest, db: sqlite3.Connection = Depends(get_db)):
    try:
        with db:
            cur = db.execute(
                "INSERT INTO users (email, password_hash) VALUES (?, ?)",
                (body.email.lower().strip(), hash_password(body.password)),
            )
    except sqlite3.IntegrityError:
        raise HTTPException(status_code=409, detail="Email already registered")
    return {"id": cur.lastrowid, "email": body.email.lower().strip()}


@app.post("/auth/login")
def login(body: AuthRequest, db: sqlite3.Connection = Depends(get_db)):
    row = db.execute(
        "SELECT id, password_hash FROM users WHERE email = ?",
        (body.email.lower().strip(),),
    ).fetchone()
    if not row or not verify_password(body.password, row["password_hash"]):
        raise HTTPException(status_code=401, detail="Invalid email or password")

    exp = datetime.now(timezone.utc) + timedelta(hours=2)
    token = jwt.encode({"sub": str(row["id"]), "exp": exp}, JWT_SECRET, algorithm=ALGORITHM)
    return {"access_token": token, "token_type": "bearer"}


@app.post("/tasks", response_model=TaskPublic, status_code=status.HTTP_201_CREATED)
def create_task(
    body: TaskCreate,
    user_id: int = Depends(get_current_user_id),
    db: sqlite3.Connection = Depends(get_db),
):
    with db:
        cur = db.execute(
            "INSERT INTO tasks (owner_id, title) VALUES (?, ?)",
            (user_id, body.title.strip()),
        )
    return TaskPublic(id=cur.lastrowid, title=body.title.strip(), completed=False)


@app.get("/tasks", response_model=list[TaskPublic])
def list_tasks(
    user_id: int = Depends(get_current_user_id),
    db: sqlite3.Connection = Depends(get_db),
):
    rows = db.execute(
        "SELECT id, title, completed FROM tasks WHERE owner_id = ? ORDER BY id DESC",
        (user_id,),
    ).fetchall()
    return [TaskPublic(id=r["id"], title=r["title"], completed=bool(r["completed"])) for r in rows]


@app.delete("/tasks/{task_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_task(
    task_id: int,
    user_id: int = Depends(get_current_user_id),
    db: sqlite3.Connection = Depends(get_db),
):
    with db:
        cur = db.execute("DELETE FROM tasks WHERE id = ? AND owner_id = ?", (task_id, user_id))
    if cur.rowcount == 0:
        raise HTTPException(status_code=404, detail="Task not found")

Automated pytest Suite (test_main.py)

python
import sqlite3
import pytest
from fastapi.testclient import TestClient
from main import app, get_db, init_db


@pytest.fixture
def client(tmp_path):
    db_file = str(tmp_path / "test.db")
    init_db(db_file)

    def override_db():
        conn = sqlite3.connect(db_file, check_same_thread=False)
        conn.row_factory = sqlite3.Row
        try:
            yield conn
        finally:
            conn.close()

    app.dependency_overrides[get_db] = override_db
    with TestClient(app) as c:
        yield c
    app.dependency_overrides.clear()


def test_full_auth_and_task_ownership(client):
    assert client.get("/tasks").status_code == 401

    client.post("/auth/register", json={"email": "maya@example.com", "password": "password123"})
    token = client.post("/auth/login", json={"email": "maya@example.com", "password": "password123"}).json()["access_token"]
    headers = {"Authorization": f"Bearer {token}"}

    created = client.post("/tasks", json={"title": "Ship FastAPI app"}, headers=headers)
    assert created.status_code == 201
    task_id = created.json()["id"]

    assert len(client.get("/tasks", headers=headers).json()) == 1
    assert client.delete(f"/tasks/{task_id}", headers=headers).status_code == 204

Run tests and start the API server locally:

bash
pytest -v
uvicorn main:app --reload

Capstone Checklist & Next Steps

Python Backend Capstone Checklist

0/4 done

Take the Final Assessment next to test your backend mastery and earn your certificate!