{"id":51283608,"url":"https://github.com/mattjaikaran/ecommerce-api-django-ninja","last_synced_at":"2026-06-30T03:32:08.681Z","repository":{"id":274716545,"uuid":"923348299","full_name":"mattjaikaran/ecommerce-api-django-ninja","owner":"mattjaikaran","description":"E-Commerce API built with Django Ninja and Postgres","archived":false,"fork":false,"pushed_at":"2026-05-19T16:57:04.000Z","size":1269,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2026-05-19T19:00:09.160Z","etag":null,"topics":["django","django-ninja","django-ninja-extra","postgresql"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/mattjaikaran.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-01-28T04:24:35.000Z","updated_at":"2026-05-19T16:57:25.000Z","dependencies_parsed_at":"2026-05-19T19:00:21.653Z","dependency_job_id":null,"html_url":"https://github.com/mattjaikaran/ecommerce-api-django-ninja","commit_stats":null,"previous_names":["mattjaikaran/ecommerce-api-update","mattjaikaran/ecommerce-api-django-ninja"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/mattjaikaran/ecommerce-api-django-ninja","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mattjaikaran%2Fecommerce-api-django-ninja","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mattjaikaran%2Fecommerce-api-django-ninja/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mattjaikaran%2Fecommerce-api-django-ninja/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mattjaikaran%2Fecommerce-api-django-ninja/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mattjaikaran","download_url":"https://codeload.github.com/mattjaikaran/ecommerce-api-django-ninja/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mattjaikaran%2Fecommerce-api-django-ninja/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":34951598,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-30T02:00:05.919Z","response_time":92,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["django","django-ninja","django-ninja-extra","postgresql"],"created_at":"2026-06-30T03:32:06.495Z","updated_at":"2026-06-30T03:32:08.675Z","avatar_url":"https://github.com/mattjaikaran.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Ecommerce API\n\nE-Commerce API built with Django Ninja and Postgres\n\n## Technologies\n\n- Python 3.13\n- [uv](https://docs.astral.sh/uv/) - Fast Python package installer and resolver\n- [Django 5.2](https://docs.djangoproject.com/en/5.2/)\n- [Django Ninja](https://django-ninja.dev/)\n- [Django Ninja Extra](https://eadwincode.github.io/django-ninja-extra/) a collection of extra features for Django Ninja\n- [Django Ninja JWT](https://eadwincode.github.io/django-ninja-jwt/)\n  - [Django Simple JWT](https://django-rest-framework-simplejwt.readthedocs.io/en/latest/) abstraction for Django Ninja\n- [PostgreSQL 17](https://www.postgresql.org/docs/) database\n- [Redis 7.2](https://redis.io/) for caching and Celery\n- [Pydantic](https://docs.pydantic.dev/latest/)\n- [Django Unfold Admin](https://unfoldadmin.com/)\n  - [Unfold Docs](https://github.com/unfoldadmin/django-unfold)\n- Docker \u0026 Docker Compose (optimized for OrbStack)\n- [Celery](https://docs.celeryq.dev/) for background tasks\n- [Flower](https://flower.readthedocs.io/) for Celery monitoring\n- Pytest for testing\n- Faker for generating test data\n- Gunicorn for production serving\n\n#### Dev Tools \u0026 Features\n\nAiming to use the most modern tooling and features for the best developer experience.\n\n- **uv** for fast dependency management and virtual environments\n- **Ruff** for super-fast linting and formatting (configured in `pyproject.toml`)\n- **Makefile** to run commands\n- **PyTest** for unit tests with coverage reporting\n- **Custom StartApp** command to create a new app with extended functionality for Django Ninja, Django Ninja Extra, and Django Unfold\n  - `make startapp \u003capp_name\u003e` to create a new app with extended functionality\n- **[Faker](https://faker.readthedocs.io/en/master/)** for generating realistic test data\n  - See `@/core/management/commands/generate_core_data.py` for more information\n- **[ReDoc](https://redocly.github.io/redoc/)** for interactive API documentation\n  - [Localhost Docs](http://localhost:8000/api/docs)\n- **[Debug Toolbar](https://django-debug-toolbar.readthedocs.io/en/latest)** for debugging\n- **Environment Variables** for configuration (see `env.example`)\n- **Advanced Decorators** for clean controller code:\n  - `@handle_exceptions()` - Built in error handling\n  - `@log_api_call()` - Logger for request/response\n  - `@paginate_response()` - Pagination for responses\n  - `@search_and_filter()` - Advanced filtering and search with django ninja extra\n  - `@cached_response()` - Redis caching\n  - `@require_authentication()` / `@require_admin()` - Authorization for different levels of access\n\n## Quick Start with Docker (Recommended)\n\n```bash\n# Clone the repository\ngit clone https://github.com/mattjaikaran/ecommerce-api-update\ncd ecommerce-api-update\n\n# Copy environment file\ncp env.example .env\n# Edit .env with your settings (optional for development)\n\n# Start all services (Django, PostgreSQL, Redis, Celery, Flower)\ndocker-compose up --build\n\n# In another terminal, run migrations and create superuser\ndocker-compose exec django python manage.py migrate\ndocker-compose exec django python manage.py createsuperuser\n\n# Generate test data (optional)\ndocker-compose exec django python manage.py generate_core_data\n```\n\n**Services will be available at:**\n\n- **API Documentation**: http://localhost:8000/api/docs\n- **Django Admin**: http://localhost:8000/admin\n- **Flower (Celery Monitor)**: http://localhost:5555\n- **PostgreSQL**: localhost:5432\n- **Redis**: localhost:6379\n\n## Local Development with uv (Alternative)\n\n```bash\n# Clone and navigate\ngit clone https://github.com/mattjaikaran/ecommerce-api-update\ncd ecommerce-api-update\n\n# Install uv (if not already installed)\ncurl -LsSf https://astral.sh/uv/install.sh | sh\n\n# Create virtual environment and install dependencies\nuv venv\nsource .venv/bin/activate  # On Windows: .venv\\Scripts\\activate\nuv pip install -e .\n\n# Set up environment\ncp env.example .env\n# Edit .env with your local database settings\n\n# Run migrations and create superuser\nuv run python manage.py migrate\nuv run python manage.py createsuperuser\nuv run python manage.py runserver\n```\n\n## Commands\n\n### Start a new Django App\n\n```bash\n# start a new django app with extended functionality\n# for Django Ninja, Django Ninja Extra, and Django Unfold.\n$ make startapp \u003capp_name\u003e\n```\n\n### Run Server\n\n```bash\n$ make runserver\n```\n\n### Install a library\n\nThis runs pip install \u003clibrary-name\u003e , then pip freeze \u003e requirements.txt to update the requirements.txt file\n\n```bash\n$ make install \u003clibrary-name\u003e\n# example\n# make install django-ninja-jwt\n```\n\n### Drop DB, Create DB, Migrate, Create Superuser via db-setup script\n\n```bash\n$ make db-setup\n```\n\n## Developer Experience Scripts\n\nThe project includes several powerful scripts to enhance the development workflow, located in the `scripts/` directory.\n\n### Core Scripts Overview\n\n- `test_feature.sh`: Test specific features or endpoints\n- `reset_test_data.sh`: Reset and seed test data\n- `check_health.sh`: Check API health and dependencies\n- `db_setup.sh`: Set up database and run migrations\n- `setup.sh`: Initial project setup\n- `lint.sh`: Run linting checks\n- `generate_secret_key.sh`: Generate Django secret key\n\n### Testing Features\n\nTest specific parts of the API with detailed output:\n\n```bash\n# Test all product-related endpoints\n./scripts/test_feature.sh products\n\n# Test cart features with verbose output\n./scripts/test_feature.sh -v cart\n\n# Test authentication endpoints\n./scripts/test_feature.sh auth\n\n# Test all features\n./scripts/test_feature.sh all\n```\n\n### Managing Test Data\n\nReset and seed test data for development:\n\n```bash\n# Reset all test data\n./scripts/reset_test_data.sh\n\n# Reset only product data\n./scripts/reset_test_data.sh -a products\n\n# Force reset without confirmation\n./scripts/reset_test_data.sh -f\n\n# Reset data without running migrations\n./scripts/reset_test_data.sh --no-migrations\n```\n\n### Health Checks\n\nMonitor the health of your API and dependencies:\n\n```bash\n# Run all health checks\n./scripts/check_health.sh\n\n# Run with verbose output\n./scripts/check_health.sh -v\n\n# Check specific API URL\n./scripts/check_health.sh -u http://localhost:8001\n\n# Skip specific checks\n./scripts/check_health.sh --skip-deps --skip-db\n```\n\n### Script Features\n\nAll developer scripts include:\n\n- Colored output for better visibility\n- Verbose mode for detailed information\n- Help documentation (`-h` or `--help`)\n- Error handling with descriptive messages\n- Consistent formatting and logging\n\nFor more detailed documentation about the scripts, see `scripts/README.md`.\n\n## Modern Controller Architecture\n\nAll controllers follow a professional, decorator-based pattern with:\n\n- **Built in exception handling** - Clean code with `@handle_exceptions()` decorator\n- **Request/response logging** - Logger for request/response with `@log_api_call()` decorator\n- **Advanced Filtering** - Built-in search, filtering, and pagination with `@search_and_filter()` decorator\n- **Optimized Queries** - `select_related()` and `prefetch_related()` for performance\n- **Consistent Responses** - 201 for creates, 204 for deletes, proper status codes\n- **Redis Caching** - Advanced caching with versioning, warming, and management commands with `@cached_response()` decorator\n- **Pagination** - Built-in pagination with `@paginate_response()` decorator\n- **Search and Filter** - Built-in search and filtering with `@search_and_filter()` decorator\n- **RBAC** - Role-based access control with `@require_permissions()` decorator\n\n### Example Controller Pattern:\n\n```python\n@api_controller(\"/products\", tags=[\"Products\"])\nclass ProductController:\n    @http_get(\"\", response={200: list[ProductSchema]})\n    @list_endpoint(\n        cache_timeout=300,\n        select_related=[\"category\", \"created_by\"],\n        prefetch_related=[\"variants\", \"tags\", \"images\"],\n        search_fields=[\"name\", \"description\", \"slug\"],\n        filter_fields={\"category_id\": \"exact\", \"status\": \"exact\"},\n        ordering_fields=[\"name\", \"price\", \"created_at\"],\n    )\n    @search_and_filter(\n        search_fields=[\"name\", \"description\"],\n        filter_fields={\"status\": \"exact\"},\n    )\n    def list_products(self, request):\n        return 200, Product.objects.filter(is_active=True)\n```\n\n## Production Deployment\n\n1. Update `.env` with production settings\n2. Build and run with Docker:\n\n```bash\ndocker-compose -f docker-compose.prod.yml up --build -d\n```\n\n## Testing\n\n```bash\n# Run all tests\npytest\n\n# Run specific test file\npytest path/to/test_file.py\n\n# Run with coverage\npytest --cov=.\n```\n\n## API Documentation\n\n- ReDoc: `/api/docs`\n\n## Features\n\n### Core Functionality\n\n- **Complete Ecommerce API** - Products, Cart, Orders, Customers, Payments with comprehensive features\n- **JWT Authentication** - Django Ninja JWT with refresh tokens\n- **Coupon \u0026 Promo Codes** - Flexible discount system with percentage/fixed amounts, usage limits, and expiry\n- **Gift Cards** - Purchasable and redeemable gift cards with balance tracking\n- **Subscriptions** - Recurring billing plans with Stripe Subscriptions integration\n- **Outbound Webhooks** - Event-driven webhook delivery to external systems with retry logic\n- **Feature Flags** - Runtime feature toggles for gradual rollouts and A/B testing\n- **Rate Limiting** - Per-endpoint and per-user rate limiting via Django Ratelimit\n- **OpenTelemetry** - Distributed tracing and metrics with OTLP export\n- **Advanced Caching** - Redis with versioning, warming, and management\n- **Modern Admin Panel** - Django Unfold admin interface\n- **Enhanced Searching** - Enhanced searching using django ninja extra search and filter functionality\n- **Custom Mailer Service** - Email service with HTML, plain text, and bulk email sending with templating support\n- **Interactive API Docs** - ReDoc with OpenAPI schema\n\n### Database \u0026 Storage\n\n- **PostgreSQL 17** - Primary database with optimized schema\n- **Redis 7.2** - Caching, sessions, and Celery broker\n- **File Storage** - Local development, S3-ready for production\n\n### Development Experience\n\n- **UV Package Management** - Fast Python dependency management\n- **Docker Compose** - Development and production configurations\n- **Hot Reloading** - Enhanced development server with live reload\n- **Enhanced Scripts** - Setup, testing, deployment, and quality checks with Bash and Python scripts\n- **Comprehensive Testing** - pytest with factories and fixtures\n\n### Code Quality \u0026 Monitoring\n\n- **Ruff** - Super-fast linting and formatting\n- **Error Handling** - Professional error management with decorators\n- **Request Logging** - Comprehensive API call logging\n- **Performance Monitoring** - Built-in performance tracking\n\n## Caching System\n\nThe project includes a comprehensive Redis-based caching system with the following features:\n\n### Cache Management\n\n1. **Command Line Interface**:\n\n   ```bash\n   # Warm cache for specific models\n   python manage.py cache_ops warm --models products.Product orders.Order\n\n   # Clear all cache\n   python manage.py cache_ops clear --force\n\n   # Preload common queries\n   python manage.py cache_ops preload\n\n   # Show cache statistics\n   python manage.py cache_ops stats\n\n   # Show cache versions\n   python manage.py cache_ops version\n   ```\n\n2. **Cache Decorators**:\n\n   ```python\n   from core.cache.decorators import cached_view, cached_method\n\n   @api_controller('/products')\n   class ProductController:\n       @http_get('')\n       @cached_view(timeout=300, key_prefix='products')\n       def list_products(self):\n           return Product.objects.all()\n\n       @cached_method(timeout=300, key_prefix='product')\n       def get_product_data(self, product_id):\n           return Product.objects.get(id=product_id)\n   ```\n\n3. **Versioned Cache**:\n\n   ```python\n   from core.cache.versioning import VersionedCache\n\n   # Create versioned cache for a namespace\n   cache = VersionedCache('products')\n\n   # Set and get data\n   cache.set('featured', featured_products)\n   featured = cache.get('featured')\n\n   # Invalidate all cache for namespace\n   cache.invalidate_all()\n   ```\n\n### Cache Warming\n\nThe system includes automatic cache warming for common queries:\n\n1. **Model Cache Warming**:\n\n   ```python\n   from core.cache.warming import CacheWarmer\n\n   warmer = CacheWarmer()\n   warmer.warm_model(Product, chunk_size=100)\n   ```\n\n2. **Query Preloading**:\n\n   ```python\n   from core.cache.preload import CachePreloader\n\n   preloader = CachePreloader()\n   preloader.preload_products()  # Preload product-related queries\n   preloader.preload_all()       # Preload all common queries\n   ```\n\n### Admin Interface\n\nThe Django admin includes a cache monitoring interface at `/admin/cache-monitor/` with features:\n\n- Cache statistics and metrics\n- Cache version management\n- Cache warming controls\n- Clear cache by namespace\n- Monitor cache usage\n\n### Automatic Cache Invalidation\n\nThe system automatically invalidates cache when models are updated:\n\n1. **Signal Handlers**:\n\n   ```python\n   from core.cache.signals import register_cache_signals\n\n   # In apps.py\n   def ready(self):\n       register_cache_signals()\n   ```\n\n2. **Related Model Invalidation**:\n   - When a model is updated, related models' cache is automatically invalidated\n   - Handles both forward and reverse relationships\n\n### Configuration\n\nAdd to your `settings.py`:\n\n```python\nCACHES = {\n    'default': {\n        'BACKEND': 'django_redis.cache.RedisCache',\n        'LOCATION': 'redis://127.0.0.1:6379/1',\n        'OPTIONS': {\n            'CLIENT_CLASS': 'django_redis.client.DefaultClient',\n            'PARSER_CLASS': 'redis.connection.HiredisParser',\n            'SOCKET_CONNECT_TIMEOUT': 5,\n            'SOCKET_TIMEOUT': 5,\n            'COMPRESSOR': 'django_redis.compressors.zlib.ZlibCompressor',\n            'IGNORE_EXCEPTIONS': True,\n        }\n    }\n}\n\n# Cache time to live in seconds\nCACHE_TTL = 60 * 15  # 15 minutes\nCACHE_KEY_PREFIX = 'ecommerce'\n\n# Session backend\nSESSION_ENGINE = 'django.contrib.sessions.backends.cache'\nSESSION_CACHE_ALIAS = 'default'\n```\n\n## Documentation\n\nComprehensive documentation is available in the `docs/` directory:\n\n- **[Architecture](docs/architecture.md)** - Detailed system architecture with diagrams and technical specifications\n- **[System Design](docs/system-design.md)** - Implementation details, current status, and technology stack\n- **[User Journeys](docs/user_journeys.md)** - Customer experience flows and interaction patterns\n- **[Machine Learning Features](docs/machine-learning-features.md)** - ML roadmap and learning objectives\n- **[Project Tasks](docs/todos.md)** - Implementation status and remaining tasks\n\n### App-Specific Documentation\n\nEach app includes its own README with detailed information:\n\n- **[Core App](core/README.md)** - Authentication, users, customers, and base functionality\n- **[Products App](products/README.md)** - Product management, categories, and inventory\n- **[Cart App](cart/README.md)** - Shopping cart and session management\n- **[Orders App](orders/README.md)** - Order processing, payments, and fulfillment\n- **[Scripts](scripts/README.md)** - Development scripts and automation tools\n\n## Project Structure\n\n```\necommerce-api-update/\n├── api/                        # Django project config (settings, urls, wsgi)\n│   ├── config/                 # Environment-specific settings\n│   └── utils/                  # Shared utilities and decorators\n├── core/                       # Users, customers, addresses, auth, base models\n├── products/                   # Product catalog, variants, categories, inventory\n├── cart/                       # Shopping cart and session management\n├── orders/                     # Order processing, line items, fulfillment\n├── payments/                   # Stripe integration, payment records, webhooks\n├── coupons/                    # Promo codes, discount rules, usage tracking\n├── gift_cards/                 # Gift card issuance, redemption, balance ledger\n├── subscriptions/              # Recurring plans, Stripe Subscriptions, billing\n├── outbound_webhooks/          # Event delivery to external endpoints, retry DLQ\n├── feature_flags/              # Runtime feature toggles, rollout rules\n├── analytics/                  # Event tracking, reporting aggregates\n├── scripts/                    # Developer shell scripts (setup, test, health)\n├── docs/                       # Architecture, system design, user journeys\n├── docker-compose.yml          # Development stack\n├── docker-compose.prod.yml     # Production stack\n├── pyproject.toml              # Dependencies and tool config (uv / ruff)\n└── Makefile                    # Common development commands\n```\n\n## Database\n\n```bash\n$ psql my_db # enter shell\n$ createdb --username=USERNAME my_db # create db\n$ dropdb my_db # drop db\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmattjaikaran%2Fecommerce-api-django-ninja","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmattjaikaran%2Fecommerce-api-django-ninja","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmattjaikaran%2Fecommerce-api-django-ninja/lists"}