Data Layer

View saved

Goal

This snapshot advances Rivermouth Dispatch by teaching you to persist authors and posts with SQLAlchemy and PostgreSQL.

Every numbered folder is a complete app. Run this stage independently, then compare it with the previous folder.

Prerequisites

Use Python 3.11+, a terminal, and Docker for Postgres stages. You should recognize functions, modules, and HTTP verbs.

Port 8001 must be free. Copy .env.example before starting database stages.

  • Python 3 and pip/venv
  • A code editor and terminal
  • Docker from part 4 onward

Concepts

SQLAlchemy 2 mapped classes define tables. Each snapshot uses its own rivermouth database so stages stay independent.

Keep request handling thin: routes accept input, services/models enforce rules, and Jinja templates escape output by default.

Walkthrough

Connect with DATABASE_URL, create User and Post models, seed Ada and Grace, and list posts on the home page.

Read the example, then open the matching snapshot. The repository includes the surrounding setup and error handling.

engine = create_engine(DATABASE_URL)
Base.metadata.create_all(engine)
posts = db.scalars(select(Post).order_by(Post.created_at.desc())).all()

Run and verify

Enter 04-Data-Layer, create a virtualenv, install requirements, copy .env.example when present, and start Uvicorn on port 8001.

Open http://127.0.0.1:8001. Watch the terminal for validation and database errors.

docker compose up -d
git clone https://github.com/michaeldunga1/fcc-fastapi-blog.git
cd fcc-fastapi-blog/04-Data-Layer
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
cp .env.example .env
uvicorn main:app --reload --port 8001

Troubleshooting

Connection refused usually means Docker Postgres is stopped or the port is not 5435.

Import errors usually mean the virtualenv is inactive or you installed packages in another snapshot. For Postgres failures, confirm Docker and the rivermouth_NN database name.

  • Read the first error first
  • Restart after environment changes
  • Never commit .env or .venv

Try this

Add a minimum title length check before insert.

Test a happy path and one invalid or unauthorized request.

  • Make one small change
  • Test it in the browser
  • Compare with the next snapshot only after it works

Next: Feed and Detail

Comments

One comment per signed-in account. Comments are saved with this page’s URL.