A modern social media backend API built with FastAPI, PostgreSQL, and SQLAlchemy. This project provides a robust foundation for social media applications with user authentication, post management, and secure API endpoints.
- Overview
- Features
- Tech Stack
- Project Structure
- Prerequisites
- Installation
- Configuration
- API Documentation
- Database Models
- Authentication
- Usage Examples
- Development
- Contributing
- License
SM-Backend is a RESTful API service designed for social media applications. Built with FastAPI for high performance and automatic API documentation, it provides essential features like user management, post creation, and JWT-based authentication.
-
User Management
- User registration and authentication
- Secure password hashing with bcrypt
- Email validation
- User profile management
-
Post Management
- Create, read, update, and delete posts
- Post ownership and permissions
- Published/unpublished post states
- Automatic timestamps
-
Authentication & Security
- JWT token-based authentication
- OAuth2 password bearer flow
- Secure password hashing
- Token expiration management
-
API Features
- Automatic API documentation with Swagger UI
- Pydantic data validation
- SQLAlchemy ORM with PostgreSQL
- Environment-based configuration
Component | Technology |
---|---|
Framework | FastAPI |
Database | PostgreSQL |
ORM | SQLAlchemy |
Authentication | JWT/OAuth2 |
Password Hashing | Bcrypt |
Validation | Pydantic |
Configuration | pydantic-settings |
Python Version | 3.7+ |
SM-Backend/
βββ app/
β βββ __init__.py # Package initialization
β βββ main.py # FastAPI application entry point
β βββ config.py # Configuration settings
β βββ database.py # Database connection and session
β βββ models.py # SQLAlchemy database models
β βββ schemas.py # Pydantic schemas for request/response
β βββ oauth2.py # JWT authentication logic
β βββ utils.py # Utility functions (password hashing)
β βββ routers/ # API route modules
β βββ auth.py # Authentication routes
β βββ post.py # Post management routes
β βββ user.py # User management routes
βββ .env # Environment variables
βββ requirements.txt # Python dependencies
βββ README.md # Project documentation
Before running this application, ensure you have:
- Python 3.7 or higher
- PostgreSQL database
- pip (Python package manager)
-
Clone the repository
git clone https://github.com/An-Array/SM-Backend.git cd SM-Backend
-
Create a virtual environment
python -m venv venv # On Windows venv\Scripts\activate # On macOS/Linux source venv/bin/activate
-
Install dependencies
pip install -r requirements.txt
-
Set up environment variables
cp .env.example .env
-
Configure your environment variables (see Configuration)
-
Start the development server
uvicorn app.main:app --reload
The API will be available at http://localhost:8000
Create a .env
file in the root directory with the following variables:
# Database Configuration
DATABASE_HOSTNAME=your_db_host
DATABASE_PORT=your_db_port
DATABASE_PASSWORD=your_db_password
DATABASE_NAME=your_db_name
DATABASE_USERNAME=your_db_user
# JWT Configuration
SECRET_KEY=your_secret_key
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30
- Database Settings: PostgreSQL connection parameters
- JWT Settings:
SECRET_KEY
: Used for signing JWT tokens (keep this secure!)ALGORITHM
: Hashing algorithm for JWT (HS256 recommended)ACCESS_TOKEN_EXPIRE_MINUTES
: Token expiration time in minutes
Once the server is running, you can access:
- Interactive API Documentation (Swagger UI):
http://localhost:8000/docs
- Alternative API Documentation (ReDoc):
http://localhost:8000/redoc
Method | Endpoint | Description |
---|---|---|
POST |
/login |
Get access token |
Request Body:
{
"username": "[email protected]",
"password": "yourpassword"
}
Method | Endpoint | Description |
---|---|---|
POST |
/users/ |
Create new user |
GET |
/users/{id} |
Get user by ID |
Create User Request:
{
"email": "[email protected]",
"password": "yourpassword"
}
Method | Endpoint | Description | Auth Required |
---|---|---|---|
GET |
/posts/ |
Get all posts | Yes |
POST |
/posts/ |
Create new post | Yes |
GET |
/posts/{id} |
Get post by ID | Yes |
PUT |
/posts/{id} |
Update post | Yes |
DELETE |
/posts/{id} |
Delete post | Yes |
Post Request Body:
{
"title": "Post Title",
"content": "Post content here...",
"published": true
}
class User(Base):
id: int (Primary Key)
email: str (Unique, Required)
password: str (Hashed, Required)
created_at: datetime (Auto-generated)
class Post(Base):
id: int (Primary Key)
title: str (Required)
content: str (Required)
published: bool (Default: True)
created_at: datetime (Auto-generated)
user_id: int (Foreign Key to User)
created_by: User (Relationship)
This API uses JWT (JSON Web Tokens) for authentication following the OAuth2 password bearer flow.
- User logs in with credentials at
/login
- Server returns JWT access token
- Client includes token in Authorization header:
Authorization: Bearer <token>
- Protected endpoints verify token validity
- Token expires after 30 minutes (configurable)
- Type: Bearer Token
- Expiration: Configurable via
ACCESS_TOKEN_EXPIRE_MINUTES
- Algorithm: HS256 (configurable)
curl -X POST "http://localhost:8000/register" \
-H "Content-Type: application/json" \
-d '{
"email": "[email protected]",
"password": "securepassword123"
}'
curl -X POST "http://localhost:8000/login" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "[email protected]&password=securepassword123"
curl -X POST "http://localhost:8000/posts" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <your_jwt_token>" \
-d '{
"title": "My First Post",
"content": "This is the content of my first post!",
"published": true
}'
curl -X GET "http://localhost:8000/posts"
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
The application automatically creates tables on startup using SQLAlchemy's create_all()
method.
- Define database models in
models.py
- Create Pydantic schemas in
schemas.py
- Implement route logic in appropriate router files
- Register routers in
main.py
Use the interactive documentation at /docs
to test endpoints directly from your browser.
- Register a new user
- Login with user credentials
- Create posts with authentication
- Try accessing protected endpoints without tokens
- Test data validation with invalid inputs
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature
) - Make your changes
- Test your changes thoroughly
- Commit your changes (
git commit -m 'Add amazing feature'
) - Push to the branch (
git push origin feature/amazing-feature
) - Open a Pull Request
- Follow PEP 8 style guidelines
- Add appropriate error handling
- Include docstrings for functions
- Test new features before submitting
fastapi
- Web frameworkuvicorn
- ASGI serversqlalchemy
- Database ORMpsycopg2-binary
- PostgreSQL adapterpydantic[email]
- Data validationpython-jose[cryptography]
- JWT handlingpasslib[bcrypt]
- Password hashingpython-multipart
- Form data support
If you encounter any issues or have questions:
- Check the API documentation when running locally
- Review the configuration settings in your
.env
file - Open an issue on GitHub with detailed information
- Check existing issues for similar problems
This project is licensed under the MIT License - see the LICENSE file for details.
Built with β€οΈ using FastAPI and modern Python tools