Skip to content

Prady2309/Yuga-Restaurant-API

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

2 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Yuga - Restaurant & Food Delivery API

Django Django REST Framework Python PostgreSQL License

Overview

Yuga is a modern, production-ready REST API for restaurant and food delivery platforms. Built with Django and Django REST Framework, it provides comprehensive backend services for menu management, user authentication, order processing, and delivery crew management.

The API is designed with enterprise-level security, role-based access control (RBAC), and scalable architecture suitable for multi-restaurant platforms.


🎯 Key Features

1. Menu & Catalog Management

  • Browse menu items organized by categories
  • Search, filter, and sort menu items by price and popularity
  • Featured items highlighting
  • RESTful CRUD operations for administrators

2. User Authentication & Authorization

  • Token-based authentication (Django REST Framework Token Auth)
  • Role-based access control with user groups:
    • Customers - Browse menu, place orders, manage cart
    • Managers - Manage menu, approve orders, assign delivery crew
    • Delivery Crew - Accept and complete deliveries
    • Admin - Full system access

3. Shopping Cart Management

  • Add/remove items to cart
  • Automatic price calculation
  • Per-user cart isolation
  • Bulk cart operations (clear all)

4. Order Management

  • Create orders from cart items
  • Order status tracking
  • Delivery crew assignment
  • Order history and retrieval
  • Order-level and item-level tracking

5. Advanced Filtering & Pagination

  • Django Filter Backend integration
  • Search by title and category
  • Price range filtering
  • Paginated responses for performance
  • Custom ordering capabilities

6. Audit & Compliance

  • Role-based permission enforcement
  • Request validation and error handling
  • Consistent HTTP status codes
  • Detailed error messages

πŸ“‹ Tech Stack

Component Technology
Framework Django 4.x
API Framework Django REST Framework 3.x
Database PostgreSQL 13+
Authentication Token Authentication (DRF)
Filtering Django Filter
Pagination PageNumberPagination
Python Version 3.9+

πŸ—οΈ Project Structure

yuga/
β”œβ”€β”€ manage.py                 # Django management script
β”œβ”€β”€ requirements.txt          # Project dependencies
β”œβ”€β”€ README.md                 # This file
β”‚
β”œβ”€β”€ yuga/                     # Main project settings
β”‚   β”œβ”€β”€ settings.py          # Django configuration
β”‚   β”œβ”€β”€ urls.py              # Root URL routing
β”‚   β”œβ”€β”€ wsgi.py              # WSGI application
β”‚   └── asgi.py              # ASGI application
β”‚
└── restaurant/              # Django app (main backend logic)
    β”œβ”€β”€ models.py            # Database models (Category, MenuItem, Cart, Order, OrderItem)
    β”œβ”€β”€ views.py             # API views and viewsets
    β”œβ”€β”€ serializers.py       # Data serialization/deserialization
    β”œβ”€β”€ urls.py              # App-specific URL routing
    β”œβ”€β”€ admin.py             # Django admin configuration
    β”œβ”€β”€ apps.py              # App configuration
    β”œβ”€β”€ tests.py             # Unit tests
    β”œβ”€β”€ migrations/          # Database migrations
    └── __pycache__/         # Python cache files

πŸ“Š Database Models

Category

- id (Primary Key)
- slug (String, unique)
- title (String, indexed)

MenuItem

- id (Primary Key)
- title (String, indexed)
- price (Decimal, indexed)
- featured (Boolean, indexed)
- category (Foreign Key β†’ Category)

Cart

- id (Primary Key)
- user (Foreign Key β†’ User)
- menuitem (Foreign Key β†’ MenuItem)
- quantity (SmallInteger)
- unit_price (Decimal)
- price (Decimal)
- Constraint: Unique(menuitem, user)

Order

- id (Primary Key)
- user (Foreign Key β†’ User)
- delivery_crew (Foreign Key β†’ User, nullable)
- status (Boolean, indexed)
- total (Decimal)
- date (Date, indexed)

OrderItem

- id (Primary Key)
- order (Foreign Key β†’ Order)
- menuitem (Foreign Key β†’ MenuItem)
- quantity (SmallInteger)
- unit_price (Decimal)
- price (Decimal)
- Constraint: Unique(order, menuitem)

πŸ”Œ API Endpoints

Menu Items

Method Endpoint Description Permission
GET /api/menu-items/ List all menu items Public (read-only)
POST /api/menu-items/ Create menu item Manager/Admin
GET /api/menu-items/{id}/ Retrieve menu item Public
PUT /api/menu-items/{id}/ Update menu item Manager/Admin
DELETE /api/menu-items/{id}/ Delete menu item Manager/Admin

Filters: ?category=<slug>&fromPrice=<min>&toPrice=<max>&search=<query>&orderBy=<field>

Categories

Method Endpoint Description Permission
GET /api/category/ List all categories Public
POST /api/category/ Create category Manager/Admin
GET /api/category/{id}/ Retrieve category Public
PUT /api/category/{id}/ Update category Manager/Admin
DELETE /api/category/{id}/ Delete category Manager/Admin

Cart

Method Endpoint Description Permission
GET /api/cart/menu-items/ View cart Customer (authenticated)
POST /api/cart/menu-items/ Add item to cart Customer
DELETE /api/cart/menu-items/ Clear cart Customer

POST Body:

{
  "menuitem_id": 5,
  "quantity": 2
}

Response:

{
  "items": [...],
  "total_items": 5,
  "total_price": 1250.50
}

Orders

Method Endpoint Description Permission
GET /api/orders/ List orders Customer (own), Manager/Admin (all)
POST /api/orders/ Create order from cart Customer
GET /api/orders/{id}/ Retrieve order Customer (own), Manager/Admin (all)
DELETE /api/orders/{id}/ Delete order Manager/Admin

User Group Management

Method Endpoint Description Permission
GET /api/groups/manager/users/ List managers Admin
POST /api/groups/manager/users/ Add manager Admin
DELETE /api/groups/manager/users/{id}/ Remove manager Admin
GET /api/groups/delivery-crew/users/ List delivery crew Admin
POST /api/groups/delivery-crew/users/ Add delivery crew Admin
DELETE /api/groups/delivery-crew/users/{id}/ Remove delivery crew Admin

πŸ” Authentication & Authorization

Token Authentication

Every authenticated request requires the token header:

Authorization: Token <your-token-here>

User Roles & Permissions

πŸ›οΈ Customer

  • Browse menu items and categories
  • Manage personal cart
  • Create and view personal orders
  • Cannot manage menu, users, or other orders

πŸ‘¨β€πŸ’Ό Manager

  • All Customer permissions
  • Create, update, delete menu items
  • Manage categories
  • View all orders
  • Assign delivery crew to orders
  • Manage customer accounts

🚚 Delivery Crew

  • View assigned orders
  • Update order status
  • Cannot modify menu or orders

πŸ‘€ Admin

  • Full system access
  • User group management
  • Database administration
  • All CRUD operations

πŸš€ Installation & Setup

Prerequisites

  • Python 3.10+
  • PostgreSQL 13+
  • Git
  • pip or pipenv

Step 1: Clone Repository

git clone https://github.com/your-org/yuga.git
cd yuga

Step 2: Create Virtual Environment

python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

Step 3: Install Dependencies

pip install -r requirements.txt

Step 4: Configure Environment Variables

Create a .env file in the project root:

DEBUG=False
SECRET_KEY=your-secret-key-here
DATABASE_URL=postgresql://user:password@localhost:5432/yuga_db
ALLOWED_HOSTS=localhost,127.0.0.1

Step 5: Configure Database

Update settings.py with your PostgreSQL credentials:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'yuga_db',
        'USER': 'postgres',
        'PASSWORD': 'your-password',
        'HOST': 'localhost',
        'PORT': '5432',
    }
}

Step 6: Run Migrations

python manage.py migrate

Step 7: Create Superuser

python manage.py createsuperuser

Step 8: Create User Groups

python manage.py shell
from django.contrib.auth.models import Group

Group.objects.create(name='Customer')
Group.objects.create(name='Manager')
Group.objects.create(name='Delivery')
Group.objects.create(name='Admin')

Step 9: Load Sample Data (Optional)

python manage.py loaddata initial_data.json

Step 10: Run Development Server

python manage.py runserver

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


πŸ“ Example API Requests

1. Get Authentication Token

curl -X POST http://localhost:8000/api-token-auth/ \
  -H "Content-Type: application/json" \
  -d '{"username": "user123", "password": "pass123"}'

Response:

{
  "token": "abcdef123456789"
}

2. Browse Menu Items

curl -X GET "http://localhost:8000/api/menu-items/?category=pizzas&toPrice=500" \
  -H "Authorization: Token abcdef123456789"

3. Add Item to Cart

curl -X POST http://localhost:8000/api/cart/menu-items/ \
  -H "Authorization: Token abcdef123456789" \
  -H "Content-Type: application/json" \
  -d '{
    "menuitem_id": 5,
    "quantity": 2
  }'

4. Create Order

curl -X POST http://localhost:8000/api/orders/ \
  -H "Authorization: Token abcdef123456789" \
  -H "Content-Type: application/json" \
  -d '{}'

5. Assign Delivery Crew

curl -X PATCH http://localhost:8000/api/orders/10/ \
  -H "Authorization: Token abcdef123456789" \
  -H "Content-Type: application/json" \
  -d '{"delivery_crew": 15}'

πŸ§ͺ Testing

Run All Tests

python manage.py test

Run Specific App Tests

python manage.py test restaurant

Run with Coverage Report

pip install coverage
coverage run --source='.' manage.py test
coverage report
coverage html  # Generate HTML report

πŸ” Code Quality & Best Practices

Implemented Features

βœ… DRF Generics & ViewSets - Reusable, maintainable views
βœ… Django Filters - Advanced filtering without custom code
βœ… Pagination - Efficient data handling
βœ… Permission Classes - DjangoModelPermissions, DjangoModelPermissionsOrAnonReadOnly
βœ… Serializer Validation - Field-level and object-level validation
βœ… Database Constraints - Unique constraints at model level
βœ… Query Optimization - select_related() for foreign keys
βœ… Comprehensive Error Handling - Meaningful HTTP status codes
βœ… API Documentation - Browsable API interface (with DRF)

Performance Optimizations

  • Database indexing on frequently queried fields
  • Query optimization with select_related()
  • Pagination for large datasets
  • Efficient serializer design

πŸ“¦ Dependencies

Core dependencies (see requirements.txt):

Django==4.2.x
djangorestframework==3.14.x
django-filter==23.x
psycopg2-binary==2.9.x
python-decouple==3.x
gunicorn==20.x

🌐 Deployment

Using Gunicorn

pip install gunicorn
gunicorn yuga.wsgi --bind 0.0.0.0:8000

Docker Deployment

FROM python:3.9
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["gunicorn", "yuga.wsgi:application", "--bind", "0.0.0.0:8000"]

Environment Variables for Production

DEBUG=False
SECRET_KEY=<generate-strong-key>
ALLOWED_HOSTS=yourdomain.com,www.yourdomain.com
DATABASE_URL=postgresql://user:password@prod-db:5432/yuga_prod

πŸ“š API Documentation (To be available soon!)

OpenAPI/Swagger

To enable interactive API docs, install:

pip install drf-spectacular

Add to INSTALLED_APPS:

'drf_spectacular',

Access at: http://localhost:8000/api/schema/swagger/


πŸ“„ License

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


πŸŽ“ Additional Resources


πŸ”’ Security Considerations

βœ… HTTPS Only - Always use HTTPS in production
βœ… CSRF Protection - Enabled by default
βœ… SQL Injection Prevention - Using Django ORM
βœ… XSS Protection - DRF serializers escape output
βœ… Rate Limiting - Implement via Throttle classes (TODO)
βœ… API Key Rotation - Token-based auth with expiry (TODO)


πŸ“ˆ Future Roadmap

  • Advanced order tracking with real-time updates
  • Payment gateway integration (Stripe/PayPal)
  • Push notifications for customers
  • Rating & review system
  • Analytics dashboard
  • Multi-language support
  • GraphQL API endpoint
  • Mobile app API optimization

Last Updated: December 2025
Version: 1.0.0
Status: Dev Ready

About

Yuga - Restaurant & Food Delivery API

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages