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
- Return the 50 most recent posts, each with its author's name.
- `Post.author` is a lazy-loaded relationship to `User`.
- The endpoint backs a public feed; it must issue a bounded number of queries regardless of page size.
Files touched
- app/routes/feed.py
--- 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
+ ]