📖 Blog API — Architecture & Flow

A minimal RESTful blogging platform built with FastAPI + SQLAlchemy + JWT. Try it live in the playground.

🧱 Project layout

app/
├── main.py                # FastAPI app + route registration
├── config.py              # env vars (SECRET_KEY, DATABASE_URL, …)
├── database.py            # SQLAlchemy engine + get_db() dependency
├── models/                # ORM tables: User, Post, Comment
├── schemas/               # Pydantic request/response shapes
├── routes/                # Endpoint handlers (auth, users, posts, comments)
├── auth/                  # JWT create/decode + get_current_user dependency
└── core/security.py       # bcrypt password hashing

🔁 Request lifecycle

Client → HTTP  →  Uvicorn  →  FastAPI router
                             ↓
                    Pydantic validates body
                             ↓
                Dependency: get_current_user()   (protected routes)
                             ↓
                     Route function runs
                             ↓
                SQLAlchemy talks to SQLite (blog.db)
                             ↓
                Return ORM object  →  Pydantic serializes  →  JSON

🔐 Auth flow

  1. POST /auth/register → password hashed with bcrypt, user row inserted.
  2. POST /auth/login → verify hash, sign JWT with HS256 & SECRET_KEY.
  3. Client sends Authorization: Bearer <token> on every write.
  4. get_current_user decodes the JWT, loads the user, injects it into the route.
  5. Routes enforce ownership: if obj.author_id != current_user.id → 403.

📚 Endpoint map

MethodPathAuthHandler
POST/auth/registerroutes/auth.register
POST/auth/loginroutes/auth.login
GET/users/meroutes/users.me
GET/PUT/DELETE/users/{id}✅ (self)routes/users
POST/posts/routes/posts.create_post
GET/posts/{id}routes/posts.read_post
PUT/DELETE/posts/{id}✅ (author)routes/posts
POST/comments/routes/comments.create_comment
GET/comments/{id}routes/comments.read_comment
PUT/DELETE/comments/{id}✅ (author)routes/comments

🗄 Data model

User ─┬─◀ Post ─┬─◀ Comment
      │        │
      └────────┴─◀ Comment    (author)

Cascade delete: removing a user removes their posts and comments; deleting a post removes its comments.

🚀 Try it

Head over to the interactive playground — it walks through register → login → create post → comment step by step and prints every request/response.