Serialize posts with their author

Python · FastAPI · intermediate · greenfield

Adds the feed endpoint: loads the 50 most recent posts and serializes each with its author's name. Uses the ORM relationship for the author.

Postgres via SQLAlchemy 2. Post.author is a lazy relationship (loads on first access). The feed is polled by every open client.

Requirements

Files touched

--- app/routes/feed.py
+from fastapi import APIRouter
+from sqlalchemy import select
+from app.db import Session
+from app.models import Post
+
+router = APIRouter()
+
+
[email protected]("/feed")
+def feed():
+    with Session() as session:
+        posts = session.scalars(
+            select(Post).order_by(Post.created_at.desc()).limit(50)
+        ).all()
+        return [
+            {"id": p.id, "title": p.title, "author": p.author.name}
+            for p in posts
+        ]

Review this PR

Python practice