N
NexusDigitalLabs
← Back to Academy

Phase 1 — Foundations · Lesson 14 · 40 XP

Project: CRUD API with Postgres

This project wires Lesson 12 (SQL/Postgres) into Lesson 13 (FastAPI): a real Create-Read-Update-Delete API backed by a real database, not an in-memory list that resets on every restart.

Keep the database connection string in an environment variable, read at startup — never hardcoded in source, since that's a credential that would otherwise sit in your git history forever. Return the right status code for each outcome: 201 for a successful create, 200 for a successful read/update, 204 or 200 for delete, 404 when the id doesn't exist.

import os
DATABASE_URL = os.environ["DATABASE_URL"]

@app.get("/todos/{todo_id}")
def get_todo(todo_id: int):
    row = db.fetch_one(todo_id)
    if row is None:
        raise HTTPException(status_code=404, detail="not found")
    return row

Exercise

Build a complete CRUD API for a resource (e.g. todos) backed by your local Postgres: Create, Read (list + single), Update, and Delete endpoints, with Pydantic request/response models and correct status codes throughout.

Check yourself

1. Why keep the database connection string in an environment variable instead of hardcoding it in the source file?

2. What status code should a DELETE on a nonexistent id return, and why?

← Previous lesson

FastAPI basics

Answer the check-yourself questions to unlock this