A modern, asynchronous social media platform API for cooking recipe sharing, voting, and community engagement. Built with FastAPI, PostgreSQL, and SQLModel.
- User registration and login
- JWT-based authentication (access & refresh tokens)
- Token blacklisting with Redis
- Password hashing with bcrypt
- Secure token validation
- Create, read, update, and delete posts
- Free-form hashtags (up to 10 per post) with a suggested starter list, trending tags and tag search
- Post metadata tracking (upvotes, downvotes, comment counts)
- Author-based access control
- Chronological public feed (
GET /posts/feed) - Following-only feed with fallback to the public feed (
GET /posts/following-feed) - FYP recommendation engine (
api/posts/algorithm.py) — interaction-weighted, Redis-backed personalized feed logic
- Nested comment replies (unlimited depth)
- Create, edit, and delete comments
- Soft deletion support
- Recursive reply tree structure
- Comment threading
- Upvote and downvote posts
- One vote per user per post (unique constraint)
- Vote type toggling (switch between upvote/downvote)
- Real-time vote count updates
- Vote history tracking
- Follow/unfollow users
- View followers and following lists
- Follow status checking
- Follower/following counts
- Username-based follower queries
- Framework: FastAPI 0.126+
- Database: PostgreSQL (with asyncpg driver)
- ORM: SQLModel 0.0.27+
- Migrations: Alembic (async support)
- Authentication: JWT (PyJWT)
- Password Hashing: bcrypt
- Caching & ranking: Redis (JWT blacklisting, FYP interaction scores, and post rankings)
- Validation: Pydantic 2.12+
- Python: 3.13+
- Python 3.13+
- PostgreSQL database
- Redis server (JWT blacklisting and FYP recommendation data)
uvpackage manager (recommended) orpip
-
Clone the repository
git clone <repository-url> cd chefly
-
Install dependencies
uv sync # or pip install -e .
-
Configure environment variables Create a
.envfile in the root directory:DB_URL=postgresql+asyncpg://user:password@host:port/database?ssl=require JWT_SECRET=your-secret-key-here JWT_ALGORITHM=HS256 JWT_ACCESS_EXPIRY=43200 JWT_REFRESH_EXPIRY=172800 REDIS_HOST=localhost REDIS_PORT=6379 REDIS_DB=0
-
Run database migrations
alembic upgrade head
-
Start the server
uvicorn main:app --reload # or python -m uvicorn main:app --reload
Once the server is running, access the interactive API documentation:
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
POST /auth/signup- Register a new userPOST /auth/login- Login and get access/refresh tokensPOST /auth/refresh- Refresh access tokenPOST /auth/logout- Logout (blacklist token)
POST /posts/create- Create a new post (authenticated). Body:title,content,tags(e.g.["#Meal Prep", "vegan"])GET /posts/all- Get all posts (authenticated)GET /posts/feed- Public chronological feed sorted by recency and upvotesGET /posts/following-feed- Posts from users you follow (authenticated; falls back to/feedif empty)GET /posts/fyp- Personalized For You feed based on interaction history (authenticated)GET /posts/{post_id}- Get a specific post (authenticated)PUT /posts/{post_id}- Update a post (authenticated, author only)DELETE /posts/{post_id}- Delete a post (authenticated, author only)
POST /comments/create- Create a comment or reply (authenticated)GET /comments/post/{post_id}- Get all comments for a post (authenticated)GET /comments/{comment_id}- Get a specific comment with replies (authenticated)PUT /comments/{comment_id}- Edit a comment (authenticated, author only)DELETE /comments/{comment_id}- Delete a comment (authenticated, author only)
POST /votes/create- Create or update a vote (authenticated)GET /votes/{vote_id}- Get a specific vote (authenticated)GET /votes/post/{post_id}- Get all votes for a post (authenticated)GET /votes/user/{user_id}- Get all votes by a user (authenticated)
POST /follows/users/{user_id}/follow- Follow a user (authenticated)DELETE /follows/users/{user_id}/follow- Unfollow a user (authenticated)GET /follows/users/{user_id}/followers- Get user's followers (public)GET /follows/users/{user_id}/following- Get users that a user follows (public)GET /follows/users/{user_id}/follow-status- Check follow status (authenticated)GET /follows/users/{user_id}/followers-count- Get follower count (public)GET /follows/users/{user_id}/following-count- Get following count (public)GET /follows/users/{user_id}/followers-usernames- Get follower usernames (public)GET /follows/users/{user_id}/following-usernames- Get following usernames (public)
All post responses include a tags list. PUT /posts/{post_id} accepts tags to replace a post's tags ([] clears them; omit to leave unchanged).
Tags are normalized: lowercased, # stripped, spaces/underscores become -, other symbols removed ("#Meal Prep" → meal-prep). Max 10 tags per post, 30 characters each.
GET /tags/suggested- Starter tags (recipe, tip, baking, vegan, ...) followed by popular user tags (public)GET /tags/trending- Most used tags on public posts in the lastdays(default 7), falls back to all-time popular (public)GET /tags/trending/posts- Posts from the lastdayscarrying any of the top 10 trending tags, ranked by engagement (upvotes - downvotes + 2 × comments), then recency (authenticated;limit/offset/days)GET /tags/search?q=- Prefix search for autocomplete (public)GET /tags/{name}/posts- Posts with a tag, newest first (authenticated; respects private communities)
Stored in PostgreSQL and pushed live over the WebSocket. You never get notified about your own actions.
| Type | Recipient | Trigger |
|---|---|---|
follow |
Followed user | Someone follows you |
upvote |
Post author | Upvote on your post. Grouped: while unread, further upvotes update one notification ("chi and 3 others upvoted…"). Each user counts once; undoing an upvote (switching to downvote or deleting the vote) removes them, and a group left empty is deleted |
comment |
Post author | Comment or reply on your post |
reply |
Parent comment author | Reply to your comment |
join_request |
Community owner + admins | Someone requests to join a private community |
join_approved |
Requester | Join request approved |
added_to_community |
Added user | An owner/admin adds you directly |
promoted_to_admin |
Promoted user | Owner makes you an admin |
GET /notifications/- List notifications, newest activity first (unread_only,limit,offset). Each includes a ready-to-displaymessage,actor,actor_count, andpost/comment_id/communityreferencesGET /notifications/unread-count- Unread badge countPOST /notifications/{notification_id}/read- Mark one as readPOST /notifications/read-all- Mark all as readDELETE /notifications/{notification_id}- Delete one
Live events: notification (new or updated; grouped upvotes re-send the same id, so upsert by id) and notification.removed ({"id"}, when an upvote group becomes empty).
Notifications are written in their own DB session after the triggering action commits, and are best-effort: a notification failure is logged and never fails the request. They are deleted automatically (FK cascade) when their post, comment, community, or user is deleted.
1-to-1 direct messages. All endpoints are authenticated.
Message requests: when you start a DM with someone who doesn't follow you, it lands in their requests inbox. They can accept it, reply (which accepts it), or decline it (deletes the conversation; the sender isn't told). DMs to people who follow you go straight to their inbox. Conversations with no messages yet are hidden from both inboxes.
POST /chats/- Start or get the DM with a user ({"user_id"})GET /chats/- Inbox, most recent first (?requests=truefor message requests;limit,offset). Each conversation includes the other user, last message preview,unread_count,is_accepted(yours),other_accepted, and read receipts (my_last_read_at,other_last_read_at)GET /chats/unread-count-{"unread_conversations", "requests"}GET /chats/{conversation_id}- One conversationPOST /chats/{conversation_id}/accept- Accept a message requestDELETE /chats/{conversation_id}/request- Decline a message requestPOST /chats/{conversation_id}/read- Mark read up to the latest message (sends a read receipt)GET /chats/{conversation_id}/messages- Messages, newest first (limitup to 100; page back withbefore=<created_at of oldest message you have>)POST /chats/{conversation_id}/messages- Send (contentup to 4000 chars and/orshared_post_id)PUT /chats/{conversation_id}/messages/{message_id}- Edit your message (setsedited_at)DELETE /chats/{conversation_id}/messages/{message_id}- Delete your message (stays in the timeline asis_deletedwith content removed)
Shared posts: messages can carry a post, returned as shared_post (id, title, author, tags). You can only share posts you can see; if the recipient can't see it (e.g. a private community they're not in), they get shared_post_unavailable: true instead of the preview.
Read receipts: your messages with created_at <= other_last_read_at have been seen.
One connection per client carries notifications and chat. Connect with ws://host/ws?token=<access token> (browsers can't set headers on WebSockets) or an Authorization: Bearer header. Invalid tokens are rejected with close code 1008. Events fan out through Redis pub/sub (events:{user_id}), so every open device of a user receives them and it works across multiple server processes.
Every frame is JSON: {"type": "...", "data": {...}}.
| Server → client | data |
|---|---|
ready |
{"user_id", "unread_notifications", "chat": {"unread_conversations", "requests"}}, sent on connect |
notification / notification.removed |
Notification JSON / {"id"} |
chat.message |
{"message": Message, "is_request"}, also sent to the sender's other devices |
chat.message_updated / chat.message_deleted |
Message / {"id", "conversation_id"} |
chat.read |
{"conversation_id", "user_id", "last_read_at"} |
chat.typing |
{"conversation_id", "user_id"} (not stored; show for a few seconds) |
chat.request_accepted / chat.conversation_removed |
{"conversation_id", ...} |
ack |
{"client_id", "message"}, reply to send_message |
error |
{"type", "client_id", "status", "detail"} |
pong |
{} |
| Client → server | Fields |
|---|---|
ping |
- |
typing |
conversation_id (throttle to ~1 per 3s) |
read |
conversation_id |
send_message |
conversation_id, content and/or shared_post_id, optional client_id echoed in the ack/error |
Messages can also be sent with REST; both paths broadcast the same chat.message event. Deduplicate by message id. When the access token expires, the next client frame gets an error (401) and the socket closes, so reconnect with a fresh token.
const ws = new WebSocket(`wss://api.chefly.app/ws?token=${accessToken}`);
ws.onmessage = ({ data }) => {
const { type, data: payload } = JSON.parse(data);
if (type === "notification") upsertNotification(payload);
if (type === "chat.message") addMessage(payload.message);
if (type === "chat.typing") showTyping(payload.conversation_id);
};
ws.send(JSON.stringify({ type: "send_message", conversation_id, content: "Hi!", client_id: crypto.randomUUID() }));GET /bookmarks/- Get your bookmarked posts, newest first (authenticated;limit/offset)POST /bookmarks/posts/{post_id}- Bookmark a post (authenticated; idempotent)DELETE /bookmarks/posts/{post_id}- Remove a bookmark (authenticated)GET /bookmarks/posts/{post_id}/status- Check whether you bookmarked a post (authenticated)
All community endpoints are authenticated. Roles: owner (creator) > admin > member.
POST /communities/- Create a community (name,description,is_private); creator becomes ownerGET /communities/- List/search communities (q,limit,offset), sorted by members countGET /communities/me- Communities you belong to, with your roleGET /communities/{community_id}- Community details (includesmy_role)PUT /communities/{community_id}- Edit name/description/privacy (owner/admin)DELETE /communities/{community_id}- Delete community and its posts (owner)POST /communities/{community_id}/join- Join a public community, or send a join request to a private onePOST /communities/{community_id}/leave- Leave a community (owner cannot leave)GET /communities/{community_id}/members- List members (members only if private)POST /communities/{community_id}/members- Add a user directly byuser_id(owner/admin)DELETE /communities/{community_id}/members/{user_id}- Remove a member (owner/admin; only owner can remove admins)PUT /communities/{community_id}/members/{user_id}/role- Set role toadmin/member(owner)GET /communities/{community_id}/requests- Pending join requests (owner/admin)POST /communities/{community_id}/requests/{request_id}/approve- Approve a join request (owner/admin)POST /communities/{community_id}/requests/{request_id}/reject- Reject a join request (owner/admin)POST /communities/{community_id}/posts- Create a post in the community (members)GET /communities/{community_id}/posts- Community posts, newest first (members only if private)DELETE /communities/{community_id}/posts/{post_id}- Delete a post (author or owner/admin)
Community posts live in the posts table (community_id), so replies use POST /comments/create and voting/bookmarking work as normal. Replying requires membership. Posts in private communities are hidden from /posts/feed and only appear in /posts/all, /posts/following-feed, /posts/fyp, and bookmarks for members.
Personalized “For You” feed logic lives in api/posts/algorithm.py. It uses Redis as an ephemeral scoring layer on top of PostgreSQL for post retrieval.
- Record interactions — Votes, comments, bookmarks, and follows/unfollows automatically call
safe_record_interaction()after a successful DB write. Each event applies a weighted score to the post, its author, and its tags. - Cold start — Users with no interaction history get posts from trending tags first, then popular posts (highest
upvote_count). - Personalized feed — Users with history get, in order:
- Unseen posts from preferred authors (ranked by cumulative interaction weight)
- Unseen posts carrying the user's preferred tags (top 10 positively scored tags)
- Unseen posts from trending tags (helps users discover topics outside their usual tags)
- Backfill from the global post leaderboard (
fyp:ranked_postsin Redis) - Fallback to popular posts if Redis/SQL return nothing
| Interaction type | Weight |
|---|---|
upvotes |
+1 |
downvotes |
-1 |
comments |
+5 |
follows |
+10 |
unfollows |
-10 |
profile_view |
+3 |
bookmarks |
+7 |
unbookmarks |
-7 |
| (unknown) | +0.5 |
| Key | Type | Purpose |
|---|---|---|
user:{user_id}:interactions |
Hash | Per-user post interaction scores (7-day TTL) |
user:{user_id}:preferred_authors |
Sorted set | Authors the user engages with most (7-day TTL) |
user:{user_id}:preferred_tags |
Sorted set | Tags on posts the user engages with, same weights (7-day TTL) |
user:{user_id}:viewed_posts |
Set | Posts already surfaced to the user |
fyp:ranked_posts |
Sorted set | Global post ranking by aggregate interaction score |
from uuid import UUID
from api.db.main import get_session
from api.db.redis import redis_client
from api.posts.algorithm import safe_record_interaction, get_fyp_recommendations
# Manual interaction recording (services use safe_record_interaction automatically)
await safe_record_interaction(
user_id=user_id,
post_id=post_id,
interaction_type="upvotes", # or downvotes, comments, follows, ...
author_id=post.author_id,
)
# Fetch recommendations
async for session in get_session():
posts = await get_fyp_recommendations(
redis=redis_client,
session=session,
user_id=user_id,
limit=20,
offset=0,
)Interaction recording is best-effort: if Redis is unavailable, the API request still succeeds and a warning is logged.
- User authentication and profile information
- Relationships: posts, votes, comments, follows
- Content posts, tagged via
Tag/PostTag(many-to-many;Tag.post_countkept in sync) - Tracks: upvote_count, downvote_count, comment_count
- Author relationship
- Nested comment system with parent_id
- Soft deletion support (is_deleted)
- Relationships: user, post, parent comment, replies
- Upvote/downvote system
- Unique constraint: one vote per user per post
- Relationships: user, post
Community: name (unique), description, is_private, owner, members_countCommunityMember: user membership with role (owner/admin/member); one per user per communityCommunityJoinRequest: pending/approved/rejected requests for private communities- Posts optionally belong to a community via
community_id
- User following relationships
- Unique constraint: one follow per user pair
- Tracks follower_count and following_count on User model
- Signup: User registers with email, username, and password
- Login: User receives access token (short-lived) and refresh token (long-lived)
- API Requests: Include access token in Authorization header:
Bearer <token> - Token Refresh: Use refresh token to get new access token when expired
- Logout: Token is blacklisted in Redis
chefly/
├── api/
│ ├── __init__.py # FastAPI app initialization
│ ├── config.py # Application settings
│ ├── auth/ # Authentication module
│ │ ├── routes.py # Auth endpoints
│ │ ├── service.py # Auth business logic
│ │ ├── schemas.py # Auth Pydantic models
│ │ ├── utils.py # JWT & password utilities
│ │ └── dependencies.py # Token validation
│ ├── posts/ # Posts module
│ │ ├── routes.py # Post & feed endpoints
│ │ ├── service.py # Post business logic
│ │ ├── schemas.py # Post Pydantic models
│ │ └── algorithm.py # FYP recommendation engine (Redis + SQL)
│ ├── comments/ # Comments module
│ ├── votes/ # Voting module
│ ├── follows/ # Follow system module
│ ├── bookmarks/ # Bookmarks module
│ ├── tags/ # Tags: normalization, starter list, trending/search
│ ├── notifications/ # Notifications: storage, grouping
│ ├── chat/ # DMs: message requests, read receipts, shared posts
│ ├── realtime/ # /ws WebSocket + per-user Redis event bus
│ ├── communities/ # Communities, membership, join requests
│ │ └── access.py # Shared visibility/membership rules
│ └── db/
│ ├── main.py # Database session management
│ ├── models.py # SQLModel database models
│ └── redis.py # Shared async Redis client (decode_responses=True)
├── migrations/ # Alembic migrations
├── main.py # Application entry point
└── pyproject.toml # Project dependencies
Create a new migration:
alembic revision --autogenerate -m "description"Apply migrations:
alembic upgrade headRollback:
alembic downgrade -1- Follow PEP 8
- Use type hints
- Async/await for all database operations
- Password hashing with bcrypt (truncated to 72 bytes)
- JWT token validation
- Token blacklisting with Redis
- Ephemeral FYP scores in Redis (TTL-backed; stores user/post UUIDs only)
- Unique constraints on votes and follows
- Author-based access control
- Input validation with Pydantic
The API uses standard HTTP status codes:
200- Success201- Created400- Bad Request401- Unauthorized403- Forbidden404- Not Found500- Internal Server Error
See LICENSE file for details.
Contributions are welcome! Please feel free to submit a Pull Request.
- Recipe ingredient and instruction parsing
- Image upload support
- Search functionality
- Notifications system
- User profiles and bio
- Bookmarks
- Recipe collections
- Rate limiting
- Email verification