CoolFace
Apppublic

MoaazMuhmmad/My-Redis_API

sourceHugging Faceupdated 3mo agoView on Hugging Face
0likes
App README

Redis API Django Project

This is a Django REST framework project integrated with Redis and Celery, deployed on Hugging Face Spaces using Docker.

๐Ÿ›’ Session-Based Cart API

A high-performance shopping cart REST API built with Django REST Framework and Redis as a fast in-memory session store. The project demonstrates real-world use of Redis as a caching/storage layer instead of a traditional database โ€” achieving near-instant cart operations.


๐Ÿ—๏ธ Architecture Overview

Client (Postman / Browser)
        โ”‚
        โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚   Django DRF     โ”‚  โ† REST API + Session Middleware
โ”‚   (Port 8000)    โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
         โ”‚
    โ”Œโ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”         โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
    โ”‚  Redis   โ”‚         โ”‚   PostgreSQL      โ”‚
    โ”‚ (Cart    โ”‚         โ”‚  (Products &      โ”‚
    โ”‚  Data)   โ”‚         โ”‚   Categories)     โ”‚
    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜         โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
         โ”‚
    โ”Œโ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
    โ”‚  RedisInsight  โ”‚  โ† Visual Redis UI (Port 5540)
    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Key Design Decision: Cart data lives in Redis (not PostgreSQL) using session-keyed hashes โ€” this gives O(1) read/write speed and automatic expiry when the session ends.


โœจ Features

  • โ€”Session-based cart โ€” no authentication required, cart is tied to the browser session
  • โ€”Redis HSET storage โ€” each cart stored as cart:{session_id} hash in Redis
  • โ€”Full product & category inventory API backed by PostgreSQL
  • โ€”Swagger UI auto-generated via drf-spectacular
  • โ€”Dockerized โ€” one command to run everything (Django + Redis + PostgreSQL + RedisInsight)
  • โ€”Admin panel auto-seeded with superuser on first run

๐Ÿงฑ Tech Stack

LayerTechnology
Backend FrameworkDjango 5.2 + Django REST Framework 3.16
Session/Cart StoreRedis 7 (via redis-py 5.2)
DatabasePostgreSQL 18
API Documentationdrf-spectacular 0.28 (Swagger/OpenAPI 3)
ContainerizationDocker + Docker Compose
Redis UIRedisInsight

๐Ÿ“ Project Structure

Session_Based_Cart/
โ”œโ”€โ”€ app/
โ”‚   โ”œโ”€โ”€ cart/                   # Cart app (Redis-powered)
โ”‚   โ”‚   โ”œโ”€โ”€ redis_cart.py       # Redis operations (add, get)
โ”‚   โ”‚   โ”œโ”€โ”€ serializers.py      # Request/Response validation
โ”‚   โ”‚   โ”œโ”€โ”€ views.py            # API endpoints
โ”‚   โ”‚   โ””โ”€โ”€ urls.py
โ”‚   โ”œโ”€โ”€ inventory/              # Products & Categories app
โ”‚   โ”‚   โ”œโ”€โ”€ models.py           # Category (tree) + Product models
โ”‚   โ”‚   โ”œโ”€โ”€ serializers.py
โ”‚   โ”‚   โ”œโ”€โ”€ views.py
โ”‚   โ”‚   โ””โ”€โ”€ urls.py
โ”‚   โ”œโ”€โ”€ core/
โ”‚   โ”‚   โ”œโ”€โ”€ settings.py         # Redis + DB config
โ”‚   โ”‚   โ””โ”€โ”€ urls.py             # Main URL routing + Swagger
โ”‚   โ””โ”€โ”€ manage.py
โ”œโ”€โ”€ docker-compose.yml
โ”œโ”€โ”€ Dockerfile
โ”œโ”€โ”€ requirements.txt
โ””โ”€โ”€ init.sql                    # DB seed data

๐Ÿš€ Quick Start (Live Demo)

Prerequisites

1. Clone the repository

bash
git clone https://github.com/iiMoaaz/Session_Based_Cart.git
cd Session_Based_Cart

2. Start all services

bash
docker compose up --build

This single command will:

  • โ€”Build the Django image
  • โ€”Start PostgreSQL and run migrations automatically
  • โ€”Start Redis
  • โ€”Create an admin superuser automatically
  • โ€”Start RedisInsight (Redis visual UI)

Wait for the log line:

django_app | Starting development server at http://0.0.0.0:8000/

3. Access the services

ServiceURLDescription
Swagger UIhttp://localhost:8000/docs/Interactive API docs
Django Adminhttp://localhost:8000/admin/Admin panel
RedisInsighthttp://localhost:5540Visual Redis browser
OpenAPI Schemahttp://localhost:8000/schema/Raw OpenAPI JSON

Admin credentials: admin / admin


๐Ÿ“– API Endpoints

Inventory

GET /api/products/

Returns all products from PostgreSQL.

Response:

json
[
  {
    "id": 1,
    "category": 2,
    "name": "Wireless Headphones",
    "description": "Noise-cancelling over-ear headphones",
    "price": "149.99"
  }
]
GET /api/categories/

Returns all product categories.

Response:

json
[
  {
    "id": 1,
    "name": "Electronics",
    "slug": "electronics",
    "is_active": true
  }
]

Cart (Redis-powered)

POST /api/cart/add/

Adds a product to the session cart. Creates a new session automatically if one doesn't exist.

Request Body:

json
{
  "product_id": 1,
  "name": "Wireless Headphones",
  "price": 149.99,
  "quantity": 2
}

Response:

json
{
  "message": "Added to cart."
}

What happens in Redis:

HSET cart:{session_key} 1 '{"product_id": 1, "name": "Wireless Headphones", "price": 149.99, "quantity": 2}'
GET /api/cart/get/

Returns all items in the current session's cart.

Response:

json
[
  {
    "product_id": 1,
    "name": "Wireless Headphones",
    "price": 149.99,
    "quantity": 2
  }
]

๐Ÿ” How Redis Storage Works

Cart data is stored in Redis as a Hash data structure:

Key:   cart:{django_session_key}
Field: {product_id}
Value: JSON string of product data

Example in Redis CLI:

bash
HGETALL cart:abc123xyz

# Output:
# 1) "1"
# 2) "{\"product_id\": 1, \"name\": \"Headphones\", \"price\": 149.99, \"quantity\": 2}"

Why Redis instead of the database?

  • โ€”Cart reads/writes are extremely frequent โ€” Redis handles millions of ops/sec
  • โ€”Cart data is temporary by nature โ€” it doesn't need to persist long-term
  • โ€”Session expiry naturally cleans up abandoned carts

๐Ÿ› ๏ธ Local Development (Without Docker)

Requirements

  • โ€”Python 3.11+
  • โ€”Redis running locally on port 6379
  • โ€”PostgreSQL running locally
bash
# Create virtual environment
python -m venv venv
venv\Scripts\activate        # Windows
source venv/bin/activate     # macOS/Linux

# Install dependencies
pip install -r requirements.txt

# Update settings.py โ€” change Redis/DB hosts from 'redis'/'postgres' to 'localhost'

cd app
python manage.py migrate
python manage.py createsuperuser
python manage.py runserver

๐Ÿงช Testing the API Manually

Using Swagger UI (Recommended)

  1. 1.Open http://localhost:8000/docs/
  2. 2.Try POST /api/cart/add/ with a product payload
  3. 3.Try GET /api/cart/get/ to see the cart

Using curl

bash
# Add item to cart
curl -X POST http://localhost:8000/api/cart/add/ \
  -H "Content-Type: application/json" \
  -c cookies.txt -b cookies.txt \
  -d '{"product_id": 1, "name": "Headphones", "price": 149.99, "quantity": 1}'

# Get cart
curl http://localhost:8000/api/cart/get/ \
  -c cookies.txt -b cookies.txt
Note: The -c cookies.txt -b cookies.txt flags persist the session cookie across requests.

Viewing Cart Data in RedisInsight

  1. 1.Open http://localhost:5540
  2. 2.Add connection: host redis, port 6379
  3. 3.Browse keys โ€” look for cart:* keys

๐Ÿ“ฆ Dependencies

Django==5.2
djangorestframework==3.16.0
drf-spectacular==0.28.0        # Swagger/OpenAPI auto-generation
redis==5.2.1                   # Redis Python client
psycopg[binary]==3.2.7         # PostgreSQL adapter

๐Ÿ”’ Security Notes (Production Checklist)

This project is configured for development only. Before deploying to production:
  • โ€”[ ] Replace SECRET_KEY with a secure random value (use environment variables)
  • โ€”[ ] Set DEBUG = False
  • โ€”[ ] Configure ALLOWED_HOSTS with your domain
  • โ€”[ ] Change admin credentials from admin/admin
  • โ€”[ ] Add Redis password authentication
  • โ€”[ ] Use environment variables for all secrets (.env file + python-decouple)
  • โ€”[ ] Switch runserver to gunicorn or uvicorn

๐Ÿ‘จโ€๐Ÿ’ป Author

Moaz โ€” @iiMoaaz


๐Ÿ“„ License

MIT License