Skip to content

An-Array/SM-Backend

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

10 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

SM-Backend 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.

πŸ“‹ Table of Contents

πŸš€ Overview

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.

✨ Features

  • 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

πŸ›  Tech Stack

Component Technology
Framework FastAPI
Database PostgreSQL
ORM SQLAlchemy
Authentication JWT/OAuth2
Password Hashing Bcrypt
Validation Pydantic
Configuration pydantic-settings
Python Version 3.7+

πŸ“ Project Structure

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

πŸ“‹ Prerequisites

Before running this application, ensure you have:

  • Python 3.7 or higher
  • PostgreSQL database
  • pip (Python package manager)

πŸ“¦ Installation

  1. Clone the repository

    git clone https://github.com/An-Array/SM-Backend.git
    cd SM-Backend
  2. Create a virtual environment

    python -m venv venv
    
    # On Windows
    venv\Scripts\activate
    
    # On macOS/Linux
    source venv/bin/activate
  3. Install dependencies

    pip install -r requirements.txt
  4. Set up environment variables

    cp .env.example .env
  5. Configure your environment variables (see Configuration)

  6. Start the development server

    uvicorn app.main:app --reload

The API will be available at http://localhost:8000

βš™οΈ Configuration

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

Configuration Details

  • 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

πŸ“š API Documentation

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

Main Endpoints

Authentication

Method Endpoint Description
POST /login Get access token

Request Body:

{
  "username": "[email protected]",
  "password": "yourpassword"
}

Users

Method Endpoint Description
POST /users/ Create new user
GET /users/{id} Get user by ID

Create User Request:

{
  "email": "[email protected]",
  "password": "yourpassword"
}

Posts

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
}

πŸ—ƒ Database Models

User Model

class User(Base):
    id: int (Primary Key)
    email: str (Unique, Required)
    password: str (Hashed, Required)
    created_at: datetime (Auto-generated)

Post Model

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)

πŸ” Authentication

This API uses JWT (JSON Web Tokens) for authentication following the OAuth2 password bearer flow.

Authentication Flow

  1. User logs in with credentials at /login
  2. Server returns JWT access token
  3. Client includes token in Authorization header:
    Authorization: Bearer <token>
    
  4. Protected endpoints verify token validity
  5. Token expires after 30 minutes (configurable)

Token Details

  • Type: Bearer Token
  • Expiration: Configurable via ACCESS_TOKEN_EXPIRE_MINUTES
  • Algorithm: HS256 (configurable)

πŸ’» Usage Examples

Register a New User

curl -X POST "http://localhost:8000/register" \
     -H "Content-Type: application/json" \
     -d '{
       "email": "[email protected]",
       "password": "securepassword123"
     }'

Login

curl -X POST "http://localhost:8000/login" \
     -H "Content-Type: application/x-www-form-urlencoded" \
     -d "[email protected]&password=securepassword123"

Create a Post (Authenticated)

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
     }'

Get All Posts

curl -X GET "http://localhost:8000/posts"

πŸ”§ Development

Running in Development Mode

uvicorn app.main:app --reload --host 0.0.0.0 --port 8000

Database Operations

The application automatically creates tables on startup using SQLAlchemy's create_all() method.

Adding New Features

  1. Define database models in models.py
  2. Create Pydantic schemas in schemas.py
  3. Implement route logic in appropriate router files
  4. Register routers in main.py

πŸ§ͺ Testing

Manual Testing

Use the interactive documentation at /docs to test endpoints directly from your browser.

Example Test Scenarios

  1. Register a new user
  2. Login with user credentials
  3. Create posts with authentication
  4. Try accessing protected endpoints without tokens
  5. Test data validation with invalid inputs

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Make your changes
  4. Test your changes thoroughly
  5. Commit your changes (git commit -m 'Add amazing feature')
  6. Push to the branch (git push origin feature/amazing-feature)
  7. Open a Pull Request

Development Guidelines

  • Follow PEP 8 style guidelines
  • Add appropriate error handling
  • Include docstrings for functions
  • Test new features before submitting

πŸ“„ Dependencies

Main Dependencies

  • fastapi - Web framework
  • uvicorn - ASGI server
  • sqlalchemy - Database ORM
  • psycopg2-binary - PostgreSQL adapter
  • pydantic[email] - Data validation
  • python-jose[cryptography] - JWT handling
  • passlib[bcrypt] - Password hashing
  • python-multipart - Form data support

πŸ“ž Support

If you encounter any issues or have questions:

  1. Check the API documentation when running locally
  2. Review the configuration settings in your .env file
  3. Open an issue on GitHub with detailed information
  4. Check existing issues for similar problems

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.


Built with ❀️ using FastAPI and modern Python tools

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published