Skip to content

ak0586/gaeinova-magic

Repository files navigation

🪔 Gaeinova Magic - E-Commerce Backend API

FastAPI Python SQLAlchemy JWT

A modern, secure, and scalable e-commerce backend API for handcrafted candles and festive gifts, built with FastAPI.


📋 Table of Contents


🎯 Overview

Gaeinova Magic is a production-ready RESTful API backend for an e-commerce platform specializing in handcrafted candles. The project demonstrates modern web development practices, secure authentication, and scalable architecture.

Key Highlights

  • Fast & Modern: Built with FastAPI for high performance
  • Secure: JWT authentication with Argon2 password hashing
  • Well-Architected: MVC pattern with clean separation of concerns
  • Type-Safe: Pydantic schemas for data validation
  • Auto-Documented: Swagger UI and ReDoc included
  • Production-Ready: Proper error handling, logging, and security

✨ Features

👤 User Features

  • 🔐 User Authentication

    • Register with email validation
    • Login with JWT token generation
    • Secure password hashing (Argon2)
    • Token-based session management
  • 🛍️ Product Browsing

    • Browse products with pagination
    • Filter by category, price range
    • Search products by name
    • View featured products
    • Product detail pages
  • 🛒 Shopping Cart

    • Add/remove items from cart
    • Update quantities
    • Real-time stock validation
    • Persistent cart per user
  • 📦 Order Management

    • Checkout with address & payment method
    • Order history tracking
    • Order status updates
    • Automatic stock management
  • 📧 Communication

    • Newsletter subscription
    • Contact form submissions

🔧 Admin Features

  • 📊 Product Management

    • Create products with image upload
    • Update product details
    • Delete products
    • Manage stock levels
    • Set featured products
  • 🏷️ Category Management

    • Add/delete categories
    • Prevent deletion of categories in use
  • 📋 Order Management

    • View all orders
    • Update order status
    • Track payment status
  • 💬 Customer Support

    • View contact messages
    • Delete resolved messages

🛠️ Tech Stack

Backend Framework

  • FastAPI 0.104.1 - Modern, fast web framework
    • Automatic API documentation (Swagger/ReDoc)
    • Built-in data validation
    • Async support
    • Type hints for better IDE support

Database

  • SQLite - Lightweight database (development)
  • SQLAlchemy 2.0.23 - SQL toolkit and ORM
    • Database-agnostic design
    • Easy migration to PostgreSQL/MySQL

Authentication & Security

  • Python-JOSE - JWT token implementation
  • Passlib - Password hashing library
    • Argon2 - Primary hashing algorithm (memory-hard)
    • SHA256 - Fallback for compatibility

Data Validation

  • Pydantic 2.5.0 - Data validation using Python type hints
  • Email-Validator - Email format validation

File Handling

  • Python-Multipart - Multipart form data (file uploads)
  • UUID - Unique filename generation

Template Engine

  • Jinja2 3.1.2 - HTML template rendering

Server

  • Uvicorn 0.24.0 - Lightning-fast ASGI server

📁 Project Structure

Backend/
├── main.py                 # Application entry point & configuration
├── database.py             # Database connection & session management
├── models.py               # SQLAlchemy database models
├── schemas.py              # Pydantic schemas for validation
├── requirements.txt        # Python dependencies
├── .env                    # Environment variables (not in git)
├── .gitignore             # Git ignore rules
│
├── routes/                 # API route handlers (Controllers)
│   ├── __init__.py
│   ├── users.py           # User authentication & profile
│   ├── products.py        # Product CRUD operations
│   ├── cart.py            # Shopping cart management
│   └── orders.py          # Order processing
│
├── frontend/               # HTML templates (Views)
│   ├── index.html
│   ├── product.html
│   ├── cart.html
│   ├── admin.html
│   └── ...
│
├── static/                 # Static files
│   ├── css/
│   ├── js/
│   └── uploads/           # Product images
│
└── PROJECT_DOCUMENTATION.md  # Detailed interview prep guide

🚀 Installation

Prerequisites

  • Python 3.9 or higher
  • pip (Python package manager)
  • Git

Step 1: Clone Repository

git clone https://github.com/ak0586/gaeinova-magic.git
cd gaeinova-magic/Backend

Step 2: Create Virtual Environment

# Windows
python -m venv venv
venv\Scripts\activate

# Linux/Mac
python3 -m venv venv
source venv/bin/activate

Step 3: Install Dependencies

pip install -r requirements.txt

Step 4: Configure Environment Variables

Create a .env file in the Backend directory:

ADMIN_EMAIL=admin@example.com
ADMIN_USERNAME=admin
ADMIN_PASSWORD=your_secure_password
ADMIN_NAME=Admin User

Step 5: Run the Application

# Development mode (with auto-reload)
uvicorn main:app --reload

# Production mode
uvicorn main:app --host 0.0.0.0 --port 8000

Step 6: Access the Application


📡 API Documentation

Authentication Endpoints

Register User

POST /api/register
Content-Type: application/json

{
  "email": "user@example.com",
  "username": "johndoe",
  "password": "securepassword",
  "full_name": "John Doe",
  "phone": "1234567890"
}

Login

POST /api/login
Content-Type: application/json

{
  "username": "johndoe",
  "password": "securepassword"
}

Response:
{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "bearer"
}

Get Current User

GET /api/users/me
Authorization: Bearer <token>

Product Endpoints

Get All Products (with filters)

GET /api/products?category=Diya&min_price=50&max_price=200&search=candle&skip=0&limit=10

Get Featured Products

GET /api/products/featured

Get Single Product

GET /api/products/{product_id}

Create Product (Admin Only)

POST /api/products
Authorization: Bearer <admin_token>
Content-Type: multipart/form-data

name: Laddoo Candle
description: Handcrafted traditional candle
price: 99.00
category: Laddoo Candle
stock: 50
is_featured: true
image: <file>

Update Product (Admin Only)

PUT /api/products/{product_id}
Authorization: Bearer <admin_token>
Content-Type: application/json

{
  "name": "Updated Name",
  "price": 120.00,
  ...
}

Delete Product (Admin Only)

DELETE /api/products/{product_id}
Authorization: Bearer <admin_token>

Cart Endpoints

Get Cart

GET /api/cart
Authorization: Bearer <token>

Add to Cart

POST /api/cart
Authorization: Bearer <token>
Content-Type: application/json

{
  "product_id": 1,
  "quantity": 2
}

Update Cart Item

PUT /api/cart/{cart_item_id}?quantity=3
Authorization: Bearer <token>

Remove from Cart

DELETE /api/cart/{cart_item_id}
Authorization: Bearer <token>

Clear Cart

DELETE /api/cart
Authorization: Bearer <token>

Order Endpoints

Create Order (Checkout)

POST /api/orders
Authorization: Bearer <token>
Content-Type: application/json

{
  "shipping_address": "123 Main St, City, State 12345",
  "phone": "1234567890",
  "payment_method": "cod"
}

Get User Orders

GET /api/orders
Authorization: Bearer <token>

Get Single Order

GET /api/orders/{order_id}
Authorization: Bearer <token>

Get All Orders (Admin Only)

GET /api/admin/orders
Authorization: Bearer <admin_token>

Update Order Status (Admin Only)

PUT /api/admin/orders/{order_id}/status?status=shipped
Authorization: Bearer <admin_token>

Category Endpoints

Get All Categories

GET /api/products/categories

Add Category (Admin Only)

POST /api/categories
Authorization: Bearer <admin_token>
Content-Type: application/json

{
  "name": "New Category"
}

Delete Category (Admin Only)

DELETE /api/categories/{category_name}
Authorization: Bearer <admin_token>

Newsletter & Contact

Subscribe to Newsletter

POST /api/newsletter
Content-Type: application/json

{
  "email": "user@example.com"
}

Send Contact Message

POST /api/contact
Content-Type: application/json

{
  "name": "John Doe",
  "email": "john@example.com",
  "mobile": "1234567890",
  "message": "I have a question about..."
}

Get Contact Messages (Admin Only)

GET /api/contact-messages
Authorization: Bearer <admin_token>

🗄️ Database Schema

Entity Relationship Diagram

┌─────────────┐         ┌─────────────┐
│    User     │────┬───<│   Order     │
│             │    │    │             │
│ - id        │    │    │ - id        │
│ - email     │    │    │ - user_id   │
│ - username  │    │    │ - total     │
│ - password  │    │    │ - status    │
│ - is_admin  │    │    └─────────────┘
└─────────────┘    │           │
       │           │           │
       │           │           ├───< OrderItem
       │           │           │
       │           │    ┌─────────────┐
       │           └───<│  CartItem   │
       │                │             │
       │                │ - id        │
       │                │ - user_id   │
       │                │ - product_id│
       │                │ - quantity  │
       │                └─────────────┘
       │                       │
       │                       │
       │                ┌─────────────┐
       │                │   Product   │
       └───────────────<│             │
                        │ - id        │
                        │ - name      │
                        │ - price     │
                        │ - category  │
                        │ - stock     │
                        └─────────────┘

Tables

Table Description Key Fields
users User accounts & authentication email, username, hashed_password, is_admin
products Product catalog name, price, category, stock, image_url
cart_items Shopping cart items user_id, product_id, quantity
orders Order headers user_id, total_amount, status, payment_status
order_items Items in orders order_id, product_id, quantity, price
categories Product categories name
newsletter Newsletter subscribers email
contact_messages Customer inquiries name, email, message

🔐 Security

1. Password Security

  • Argon2 hashing (memory-hard, GPU-resistant)
  • SHA256 fallback for compatibility
  • Passwords never stored in plain text
  • Passwords never logged or exposed in responses

2. JWT Authentication

  • HS256 algorithm for token signing
  • 30-minute token expiration
  • Stateless authentication (scalable)
  • Automatic token validation on protected routes

3. Authorization

  • Role-based access control (admin vs. user)
  • Admin-only endpoints for sensitive operations
  • User-specific data isolation (users can only see their own cart/orders)

4. Input Validation

  • Pydantic schemas validate all inputs
  • Email format validation
  • Type checking for all fields
  • SQL injection prevention via ORM

5. CORS Configuration

  • Configurable allowed origins
  • Credentials support for cookies/auth headers

6. Environment Variables

  • Sensitive data in .env file
  • .gitignore prevents committing secrets
  • Easy configuration for different environments

☁️ Deployment

Recommended Platforms

1. Render.com (Easiest)

# render.yaml
services:
  - type: web
    name: gaeinova-magic-api
    env: python
    buildCommand: pip install -r requirements.txt
    startCommand: uvicorn main:app --host 0.0.0.0 --port $PORT
    envVars:
      - key: ADMIN_EMAIL
        sync: false
      - key: ADMIN_USERNAME
        sync: false
      - key: ADMIN_PASSWORD
        sync: false

2. Railway.app

# Install Railway CLI
npm i -g @railway/cli

# Login and deploy
railway login
railway init
railway up

3. Docker Deployment

# Dockerfile
FROM python:3.9-slim

WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY . .

CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
# Build and run
docker build -t gaeinova-magic .
docker run -p 8000:8000 --env-file .env gaeinova-magic

4. AWS EC2 / VPS

# Install dependencies
sudo apt update
sudo apt install python3-pip python3-venv nginx

# Setup application
git clone <repo>
cd Backend
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt

# Run with systemd
sudo nano /etc/systemd/system/gaeinova.service

# Nginx reverse proxy
sudo nano /etc/nginx/sites-available/gaeinova

📚 Interview Preparation

Quick Project Summary

"I built Gaeinova Magic, an e-commerce backend API using FastAPI. It features JWT authentication with Argon2 password hashing, a complete shopping cart and order system, admin dashboard for product management, and follows MVC architecture with SQLAlchemy ORM. The API is fully documented with Swagger UI and includes features like product filtering, image uploads, and role-based access control."

Detailed Documentation

For comprehensive interview preparation including:

  • Technology stack explanations
  • Architecture and design patterns
  • Feature implementation details
  • Security best practices
  • Common interview questions & answers

👉 See PROJECT_DOCUMENTATION.md


🧪 Testing

Manual Testing

Use the interactive Swagger UI at /docs to test all endpoints.

Example Test Flow

  1. Register a new user
  2. Login to get JWT token
  3. Browse products
  4. Add items to cart
  5. Checkout and create order
  6. View order history

🔧 Development

Running in Development Mode

uvicorn main:app --reload --log-level debug

Database Migrations

# The app auto-creates tables on startup
# For manual migrations, use Alembic:
pip install alembic
alembic init alembic
alembic revision --autogenerate -m "Initial migration"
alembic upgrade head

📝 Future Enhancements

  • Payment gateway integration (Stripe/Razorpay)
  • Email notifications (order confirmations)
  • Product reviews and ratings
  • Wishlist functionality
  • Advanced search with Elasticsearch
  • Redis caching for better performance
  • Celery for background tasks
  • GraphQL API option
  • WebSocket for real-time updates
  • Multi-language support (i18n)

👨‍💻 Developer

Ankit Kumar
Full Stack Developer & API Engineer


📄 License

Copyright © 2025 Gaeinova Magic. All Rights Reserved.

This source code is proprietary and confidential. No part of this project may be reproduced, distributed, or transmitted without prior written permission.

For permissions, contact: gaeinova.magic@gmail.com


🙏 Acknowledgements

  • FastAPI - For the amazing framework
  • SQLAlchemy - For powerful ORM capabilities
  • Passlib - For secure password hashing
  • Pydantic - For data validation
  • Uvicorn - For lightning-fast ASGI server

📞 Support

For questions or issues:

  1. Check the PROJECT_DOCUMENTATION.md
  2. Open an issue on GitHub
  3. Contact: gaeinova.magic@gmail.com

⭐ Star this repository if you found it helpful!

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors