A robust, scalable, and secure RESTful API for e-commerce applications. Built with FastAPI, SQLAlchemy 2.0, PostgreSQL, Redis, and Docker.
- π Secure Authentication: JWT-based authentication with JTI for potential revocation, token type validation, and role-based authorization.
- π₯ User Management: Account creation, profiles, and permission controls.
- π¦ Product Catalog: Comprehensive product management with searching and filtering.
- π Shopping Cart: Flexible cart functionality with real-time stock validation.
- π³ Order Processing: End-to-end order lifecycle management with background processing and atomic stock updates.
- π° Payment Integration: Seamless Stripe payment processing with webhook security.
- π Shipping Management: Order tracking and status updates.
- π Admin Dashboard API: Complete administrative controls with proper permission checks.
- β‘ Performance Optimized: Redis caching for API responses and query optimization.
- π‘οΈ API Protection: Rate limiting implemented using SlowAPI and Redis.
- π³ Containerized: Secure multi-stage Docker build & Docker Compose setup with non-root user and healthchecks.
- π Security Focused: Comprehensive security controls, updated dependencies, and automated vulnerability scanning scripts.
Our e-commerce backend follows a clean, layered architecture:
βββββββββββββββββββββ βββββββββββββββββββββ βββββββββββββββββββββ
β API Layer β β Service Layer β β Data Layer β
β (Controllers) βββββ>β (Business Logic) βββββ>β (Models/ORM) β
βββββββββββββββββββββ βββββββββββββββββββββ βββββββββββββββββββββ
β β
β β
βΌ βΌ
βββββββββββββββββββββ βββββββββββββββββββββ
β Security β β Database β
β (JWT, OAuth) β β (PostgreSQL) β
βββββββββββββββββββββ βββββββββββββββββββββ
- FastAPI: High-performance API framework with automatic OpenAPI documentation
- SQLAlchemy 2.0: Powerful ORM for database operations with transaction safety
- PostgreSQL: Robust relational database for production
- SQLite: Lightweight database for development and testing
- Pydantic v2: Data validation and settings management
- JWT: Secure, stateless authentication with replay protection
- Stripe API: Enterprise-grade payment processing with webhook security
- Redis: High-performance caching, session management, and rate limiting
- Alembic: Database migration tool
- Docker & Docker Compose: Containerization with security best practices
- WebSockets: Real-time order and notification updates
- Python 3.11+
- Docker and Docker Compose (for containerized deployment)
- Git
-
Clone the repository
git clone https://github.com/sundanc/e-commerce-backend.git cd e-commerce-backend -
Set up a virtual environment
python -m venv .venv source .venv/bin/activate # On Windows: .venv\Scripts\activate
-
Install dependencies
pip install -r requirements.txt
-
Set up environment variables
cp .env.example .env # Edit .env with your configuration -
Initialize the database with test data
python setup_local.py
-
Run the application
uvicorn app.main:app --reload
-
Access the API documentation
Open your browser and navigate to http://127.0.0.1:8000/docs
Important: Before building the Docker image, you must update the sha256:<PASTE_DIGEST_HERE> placeholders in the Dockerfile with the latest digest for the python:3.11-slim image. You can find this digest on Docker Hub or by running docker pull python:3.11-slim and then docker inspect python:3.11-slim | grep Digest locally.
-
Configure Environment: Ensure your
.envfile is correctly configured for the Docker environment (e.g.,DATABASE_URL=postgresql://postgres:postgres@db:5432/ecommerce,REDIS_URL=redis://redis:6379/0). -
Build and Run:
docker-compose up -d --build
The API will be available at
http://localhost:8000.
Once running, explore the interactive API documentation at /docs endpoint. My API follows RESTful principles with these main resources:
| Resource | Description |
|---|---|
/api/auth |
Authentication endpoints (login, register) |
/api/users |
User profile management |
/api/products |
Product catalog with searching and filtering |
/api/cart |
Shopping cart management |
/api/orders |
Order processing and history |
/api/admin |
Administrative operations (protected) |
e-commerce-backend/
βββ app/ # Application package
β βββ api/ # API endpoints
β β βββ deps.py # Dependency injection
β β βββ routes/ # API route modules
β βββ core/ # Core functionality
β β βββ config.py # Configuration
β β βββ security.py # Security utilities
β β βββ limiter.py # Rate limiting
β β βββ database.py # Database connection
β βββ models/ # SQLAlchemy models
β βββ schemas/ # Pydantic schemas
β βββ services/ # Business logic
β βββ utils/ # Utility functions
βββ alembic/ # Database migrations
βββ scripts/ # Helper scripts
β βββ security_scan.py # Security vulnerability scanner
βββ tests/ # Test suite
βββ docker-compose.yml # Docker Compose configuration
βββ Dockerfile # Docker configuration
βββ requirements.txt # Python dependencies
βββ setup_local.py # Local development setup
Default credentials for local development are created by the setup_local.py script. Please refer to the script for details. Do not use these credentials in production.
This project implements comprehensive security measures to protect your e-commerce platform:
- Enhanced JWT Authentication: Secure tokens with JTI tracking, proper algorithm validation, and replay protection
- Role-Based Access Control: Strict permission enforcement for user/admin operations
- Password Security: Bcrypt hashing with high work factor (12+ rounds)
- Rate Limiting: Protects authentication endpoints and API routes from abuse and brute-force attacks
- Input Validation: Thorough request validation with Pydantic schema enforcement
- Query Limiting: Protection against resource exhaustion with pagination limits
- Security Headers: Comprehensive set including CSP, HSTS, X-Content-Type-Options, and more
- HTTPS Enforcement: Automatic HTTP to HTTPS redirection in production
- Non-root Container: Docker containers run as unprivileged user
- Docker Secrets: Support for secure credential management in production
- Dependency Scanning: Built-in tools to detect vulnerabilities
- Container Health Checks: Monitoring and self-healing capabilities
- SQL Injection Prevention: Parameterized queries and ORM protection
- XSS Protection: Content-Security-Policy and proper output encoding
- CSRF Protection: API design that mitigates cross-site request forgery
- Audit Logging: Security event tracking with request IDs
We provide built-in security tools to help identify and mitigate vulnerabilities:
# Run the basic security scanner
python scripts/security_scan.py
# Run with detailed output
python scripts/security_scan.py --verbose
# Export results to JSON
python scripts/security_scan.py --json results.json
# Run comprehensive security audit
python security_audit.pyFor complete implementation details, configuration options, and production recommendations, see our SECURITY.md documentation.
The API is designed for high performance and scalability:
- Async Endpoints: Non-blocking request handling
- Connection Pooling: Efficient database connections with proper transaction isolation
- Redis Caching: Optimized data retrieval
- Pagination: For large result sets with DoS protection
- Background Tasks: For CPU-intensive operations with proper session management
For production deployment, consider these additional steps:
- Set up a proper CI/CD pipeline with security scanning
- Configure HTTPS with a valid certificate
- Set up database backups and recovery procedures
- Configure proper monitoring and logging with alerts
- Restrict CORS to trusted domains
- Set up a reverse proxy (Nginx/Traefik)
- Use Docker secrets for sensitive information
- Implement token revocation and refresh mechanisms
- Configure a Web Application Firewall (WAF)
This project is licensed under the MIT License - see the LICENSE file for details.
Contributions are welcome! Please see our CONTRIBUTING.md for guidelines.
- FastAPI for the amazing Python framework
- SQLAlchemy for the powerful ORM
- Stripe for payment processing capabilities
- All open-source projects that made this possible
Made with β€οΈ by Sundance for modern e-commerce solutions