A fully functional Social Network REST API built with FastAPI, MySQL, and Graph Data Structures. This project implements intelligent user connection recommendations using graph algorithms like BFS (Breadth-First Search) and provides a complete backend for a modern social media platform.
π Academic Project - Built as part of learning FastAPI, MySQL, and Data Structures & Algorithms
π API Documentation: http://localhost:8000/docs (after running locally)
- β User Authentication - Secure JWT-based authentication system
- β User Profiles - Customizable profiles with bio, stats, and activity tracking
- β Posts & Feed - Create, edit, delete posts with personalized feed
- β Comments System - Multi-level commenting on posts
- β Like System - Like/unlike posts and comments
- β Follow/Unfollow - Build your social network connections
- π Smart Suggestions - Friend recommendations using "friends of friends" algorithm
- π Connection Finder - Find shortest path between any two users (BFS implementation)
- π₯ Mutual Connections - Discover mutual followers and friends
- π Influencer Detection - Identify most popular users using graph metrics
- π Network Analytics - Real-time network statistics and insights
- β Trending Users - See popular users within your network
|
Backend Framework
|
Database
|
|
Security
|
Data Structures
|
This project uses a directed graph to model social relationships efficiently:
- Efficient lookups: O(1) for checking if user A follows user B
- Path finding: BFS algorithm for finding connections
- Scalable: Can handle thousands of users and connections
- Real-world model: Social networks are naturally graphs!
# Adjacency List Representation
graph = {
1: [2, 3, 5], # User 1 follows users 2, 3, 5
2: [1, 4], # User 2 follows users 1, 4
3: [1, 5], # User 3 follows users 1, 5
...
}-
Breadth-First Search (BFS)
- Time Complexity: O(V + E)
- Use: Finding shortest connection path
-
Set Intersection
- Time Complexity: O(min(n, m))
- Use: Finding mutual connections
-
Graph Traversal
- Time Complexity: O(V + E)
- Use: Community size calculation
social_network_app/
β
βββ π main.py # FastAPI app with 40+ endpoints
βββ π models.py # SQLAlchemy database models
βββ π schemas.py # Pydantic validation schemas
βββ π database.py # Database connection config
βββ π auth.py # JWT authentication logic
βββ π graph.py # Graph DS & algorithms (β Core)
β
βββ π§ .env # Environment variables
βββ π§ .gitignore # Git ignore rules
βββ π¦ requirements.txt # Python dependencies
β
βββ π README.md # This file
βββ π TESTING_GUIDE.md # Detailed testing instructions
βββββββββββ βββββββββββ ββββββββββββ
β Users βββββββββ<β Posts βββββββββ<β Comments β
βββββββββββ βββββββββββ ββββββββββββ
β β β
β β β
ββββββββ βββββββ βββββββ
β β β
βββββββΌβββββββΌββββββ βββββββΌβββββββ
β Post Likes β βComment Likesβ
βββββββββββββββββββββ ββββββββββββββ
βββββββββββ
βFollowersβ (Self-referencing many-to-many)
βββββββββββ
| Table | Description |
|---|---|
users |
User accounts and profiles |
posts |
User-generated content |
comments |
Comments on posts |
followers |
Follow relationships (graph edges) |
post_likes |
Post like relationships |
comment_likes |
Comment like relationships |
- β Python 3.8 or higher
- β MySQL 8.0 or higher
- β Git
git clone https://github.com/zain-cs/social-network-api.git
cd social-network-api# Windows
python -m venv venv
venv\Scripts\activate
# Mac/Linux
python3 -m venv venv
source venv/bin/activatepip install -r requirements.txt-- Login to MySQL command line
mysql -u root -p
-- Create database
CREATE DATABASE fastapi;
EXIT;Create a .env file in the project root:
# Database Configuration
DATABASE_URL=mysql+pymysql://root:YOUR_PASSWORD@localhost/fastapi
# Security (Change these in production!)
SECRET_KEY=09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30YOUR_PASSWORD with your MySQL password!
uvicorn main:app --reloadYou should see:
INFO: Uvicorn running on http://127.0.0.1:8000
β
Graph loaded: {'total_users': 0, 'total_connections': 0}
- Swagger UI (Interactive): http://localhost:8000/docs
- ReDoc (Alternative): http://localhost:8000/redoc
POST /register Register new user account
POST /login Login and receive JWT token
GET /users/me Get current user profile with stats
PUT /users/me Update current user profile
GET /users Get all users (paginated)
GET /users/{id} Get specific user by ID
GET /users/search/{username} Search users by username
POST /users/{id}/follow Follow a user
DELETE /users/{id}/unfollow Unfollow a user
GET /users/{id}/followers Get user's followers list
GET /users/{id}/following Get users that user follows
POST /posts Create new post
GET /posts Get all posts (paginated)
GET /posts/{id} Get specific post
PUT /posts/{id} Update own post
DELETE /posts/{id} Delete own post
GET /users/{id}/posts Get all posts by user
GET /feed Get personalized feed
POST /posts/{id}/like Like a post
DELETE /posts/{id}/like Unlike a post
POST /comments Create comment on post
GET /posts/{id}/comments Get all comments on post
PUT /comments/{id} Update own comment
DELETE /comments/{id} Delete own comment
POST /comments/{id}/like Like a comment
DELETE /comments/{id}/like Unlike a comment
GET /graph/suggestions Get friend suggestions (friends of friends)
GET /graph/connection/{id} Find shortest path to user
GET /graph/mutual/{id} Get mutual connections with user
GET /graph/influencers Get most influential users
GET /graph/network-stats Get overall network statistics
GET /graph/popular-in-network Get trending users in your network
-
Start the server (if not running):
uvicorn main:app --reload
-
Open Swagger UI:
- Go to: http://localhost:8000/docs
-
Register a user:
- Find
POST /register - Click "Try it out"
- Enter user details:
{ "username": "john_doe", "email": "john@example.com", "password": "securepass123", "full_name": "John Doe", "bio": "Hello, I'm John!" } - Find
-
Login to get token:
- Find
POST /login - Enter username and password
- Copy the
access_tokenfrom response
- Find
-
Authorize:
- Click the π Authorize button (top right)
- Paste:
Bearer YOUR_ACCESS_TOKEN - Click "Authorize"
-
Test endpoints:
- Now you can test any endpoint!
- Try creating posts, following users, etc.
curl -X POST "http://localhost:8000/register" \
-H "Content-Type: application/json" \
-d '{
"username": "alice",
"email": "alice@example.com",
"password": "alice123",
"full_name": "Alice Smith"
}'curl -X POST "http://localhost:8000/login" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "username=alice&password=alice123"curl -X POST "http://localhost:8000/posts" \
-H "Authorization: Bearer YOUR_TOKEN_HERE" \
-H "Content-Type: application/json" \
-d '{
"title": "My First Post",
"content": "Hello Social Network!",
"published": true
}'For detailed step-by-step testing, check TESTING_GUIDE.md
Request:
GET /graph/connection/5
Authorization: Bearer YOUR_TOKENResponse:
{
"connected": true,
"path": ["alice", "bob", "charlie", "david"],
"degrees_of_separation": 3,
"is_mutual": false
}Request:
GET /graph/suggestions?limit=5Response:
[
{
"id": 7,
"username": "emma_wilson",
"full_name": "Emma Wilson",
"bio": "Coffee lover β"
},
{
"id": 12,
"username": "mike_tech",
"full_name": "Mike Johnson",
"bio": "Tech enthusiast"
}
]Request:
GET /graph/network-statsResponse:
{
"total_users": 150,
"total_connections": 487,
"average_followers": 3.25,
"your_followers": 12,
"your_following": 8,
"your_community_size": 45
}| Feature | Implementation |
|---|---|
| Password Security | Bcrypt hashing with salt |
| Authentication | JWT tokens with expiration |
| Authorization | Token-based access control |
| SQL Injection | Protected via SQLAlchemy ORM |
| Environment Variables | Sensitive data in .env (not in repo) |
| CORS | Configurable cross-origin settings |
- In-Memory Graph: Social graph loaded into memory for O(1) lookups
- Database Indexing: Indexes on user IDs, emails, usernames
- Lazy Loading: Relationships loaded only when needed
- Connection Pooling: Efficient MySQL connection management
- Pagination: All list endpoints support pagination
Building this project taught me:
β
FastAPI Framework - Modern async Python web framework
β
RESTful API Design - Best practices for API architecture
β
JWT Authentication - Secure token-based auth
β
ORM Usage - SQLAlchemy for database operations
β
Graph Algorithms - BFS, path finding, network analysis
β
Database Design - Relational database modeling
β
API Documentation - Automatic docs with Swagger/OpenAPI
β
Git & GitHub - Version control and collaboration
Features I plan to add:
- Real-time notifications using WebSockets
- Direct messaging between users
- Image upload for posts and profiles (AWS S3)
- Hashtag system and trending topics
- Story feature (24-hour posts)
- User verification badges
- Advanced search with filters
- Email notifications
- Password reset via email
- Two-factor authentication (2FA)
- Rate limiting per user
- Caching with Redis
- Docker containerization
- CI/CD pipeline with GitHub Actions
- Deploy to AWS/Heroku
- No frontend interface (backend API only)
- Basic error messages (could be more descriptive)
- No email verification on signup
- No password strength validation
- Limited to text posts (no images yet)
Found a bug? Please open an issue!
Contributions are welcome! Here's how you can help:
- Fork the repository
- Create a feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
This project is licensed under the MIT License - feel free to use it for learning or your own projects!
Zain
- π GitHub: @zain-cs
- π§ Email: Contact me
- πΌ LinkedIn: Connect with me
- Built as an academic project for learning FastAPI and Data Structures
- Thanks to the FastAPI documentation and community
- Inspired by modern social media platforms like Twitter and Instagram
- Special thanks to my instructor for guidance
If you found this project helpful:
- β Give it a star on GitHub
- π΄ Fork it and build your own version
- π’ Share it with others learning FastAPI
- π¬ Open an issue if you have questions