A comprehensive, production-ready RESTful E-Commerce API built with Spring Boot, featuring JWT authentication, shopping cart, order management, payment processing, and review system.
- Features
- Tech Stack
- Architecture
- Database Schema
- API Endpoints
- Getting Started
- Configuration
- Usage Examples
- Testing
- Deployment
- Contributing
- License
- π User Authentication & Authorization - JWT-based secure authentication with role-based access control
- π€ User Management - Registration, profile management, address management
- π¦ Product Management - Complete CRUD operations with image upload support
- π·οΈ Category Management - Organize products into categories
- π Shopping Cart - Add, update, remove items with real-time price calculation
- π Order Management - Place orders, track status, view history, cancel orders
- π³ Payment Processing - Mock payment gateway integration
- β Review & Rating System - Users can review and rate products
- π§ Email Notifications - Automated emails for registration, orders, and status updates
- π Advanced Search & Filtering - Search products by name, filter by price, category, rating
- π Admin Dashboard - Analytics, user management, order management
- π Pagination & Sorting - Efficient data retrieval for large datasets
- β Input validation on all endpoints
- β Global exception handling
- β File upload for product images
- β Stock management with automatic updates
- β Order status workflow (Pending β Confirmed β Shipped β Delivered)
- β Low stock alerts for admins
- β Comprehensive API documentation with Swagger
- β Request/Response logging
- β Security headers and CORS configuration
| Technology | Purpose | Version |
|---|---|---|
| Java | Programming Language | 17+ |
| Spring Boot | Backend Framework | 3.2.x |
| Spring Security | Authentication & Authorization | 6.2.x |
| Spring Data JPA | Database ORM | 3.2.x |
| JWT | Token-based Authentication | 0.11.5 |
| PostgreSQL | Primary Database | 15+ |
| Hibernate | ORM Implementation | 6.4.x |
| Maven | Dependency Management | 3.9.x |
| Lombok | Reduce Boilerplate Code | 1.18.x |
| SpringDoc OpenAPI | API Documentation | 2.3.x |
| Spring Mail | Email Service | 3.2.x |
| JUnit 5 | Unit Testing | 5.10.x |
| Mockito | Mocking Framework | 5.8.x |
src/main/java/com/ecommerce/
β
βββ config/
β βββ SecurityConfig.java # Spring Security configuration
β βββ JwtAuthenticationFilter.java # JWT filter for requests
β βββ OpenAPIConfig.java # Swagger configuration
β βββ EmailConfig.java # Email configuration
β
βββ controller/
β βββ AuthController.java # Authentication endpoints
β βββ UserController.java # User management endpoints
β βββ ProductController.java # Product CRUD endpoints
β βββ CategoryController.java # Category management
β βββ CartController.java # Shopping cart operations
β βββ OrderController.java # Order management
β βββ ReviewController.java # Product reviews
β βββ PaymentController.java # Payment processing
β βββ AdminController.java # Admin dashboard
β
βββ service/
β βββ AuthService.java # Authentication logic
β βββ UserService.java # User business logic
β βββ ProductService.java # Product operations
β βββ CategoryService.java # Category operations
β βββ CartService.java # Cart management
β βββ OrderService.java # Order processing
β βββ ReviewService.java # Review management
β βββ PaymentService.java # Payment handling
β βββ EmailService.java # Email notifications
β βββ FileStorageService.java # File upload/download
β
βββ repository/
β βββ UserRepository.java
β βββ RoleRepository.java
β βββ ProductRepository.java
β βββ CategoryRepository.java
β βββ CartRepository.java
β βββ CartItemRepository.java
β βββ OrderRepository.java
β βββ OrderItemRepository.java
β βββ ReviewRepository.java
β βββ PaymentRepository.java
β βββ AddressRepository.java
β
βββ entity/
β βββ User.java # User entity
β βββ Role.java # Role entity (USER, ADMIN)
β βββ Address.java # User address entity
β βββ Product.java # Product entity
β βββ Category.java # Category entity
β βββ ProductImage.java # Product images entity
β βββ Cart.java # Shopping cart entity
β βββ CartItem.java # Cart items entity
β βββ Order.java # Order entity
β βββ OrderItem.java # Order items entity
β βββ Payment.java # Payment entity
β βββ Review.java # Product review entity
β
βββ dto/
β βββ request/ # Request DTOs
β β βββ RegisterRequestDTO.java
β β βββ LoginRequestDTO.java
β β βββ ProductRequestDTO.java
β β βββ AddToCartDTO.java
β β βββ CreateOrderDTO.java
β β βββ ReviewRequestDTO.java
β β
β βββ response/ # Response DTOs
β βββ AuthResponseDTO.java
β βββ UserResponseDTO.java
β βββ ProductResponseDTO.java
β βββ CartResponseDTO.java
β βββ OrderResponseDTO.java
β βββ ReviewResponseDTO.java
β
βββ exception/
β βββ ResourceNotFoundException.java
β βββ DuplicateResourceException.java
β βββ UnauthorizedException.java
β βββ InsufficientStockException.java
β βββ InvalidOperationException.java
β βββ GlobalExceptionHandler.java # @ControllerAdvice
β βββ ErrorResponse.java # Error response structure
β
βββ security/
β βββ JwtUtils.java # JWT token generation/validation
β βββ CustomUserDetails.java # UserDetails implementation
β βββ CustomUserDetailsService.java # Load user for authentication
β
βββ ECommerceApplication.java # Main application class
βββββββββββββββ ββββββββββββββββ
β User ββββββββββΆβ Address β
β β 1 * β β
ββββββββ¬βββββββ ββββββββββββββββ
β
β *
β
βΌ *
βββββββββββββββ
β Role β
β (USER/ADMIN)β
βββββββββββββββ
ββββββββββββββββ ββββββββββββββββ
β Category ββββββββββΆβ Product β
β β 1 * β β
ββββββββββββββββ ββββββββ¬ββββββββ
β
β 1
β
βΌ *
ββββββββββββββββ
βProductImage β
ββββββββββββββββ
βββββββββββββββ ββββββββββββββββ ββββββββββββββββ
β User ββββββββββΆβ Cart ββββββββββΆβ CartItem β
β β 1 1 β β 1 * β β
βββββββββββββββ ββββββββββββββββ ββββββββ¬ββββββββ
β
β *
βΌ 1
ββββββββββββββββ
β Product β
ββββββββββββββββ
βββββββββββββββ ββββββββββββββββ ββββββββββββββββ
β User ββββββββββΆβ Order ββββββββββΆβ OrderItem β
β β 1 * β β 1 * β β
βββββββββββββββ ββββββββ¬ββββββββ ββββββββ¬ββββββββ
β β
β 1 β *
βΌ 1 βΌ 1
ββββββββββββββββ ββββββββββββββββ
β Payment β β Product β
ββββββββββββββββ ββββββββββββββββ
βββββββββββββββ ββββββββββββββββ
β User ββββββββββΆβ Review ββββββββββββββββββββββββββ
β β 1 * β β * 1 β Product β
βββββββββββββββ ββββββββββββββββ ββββββββββββββββ
id (PK), first_name, last_name, email (unique), password,
phone_number, is_active, created_at, updated_atid (PK), name, description, price, discount_price,
stock_quantity, sku, category_id (FK), image_url,
average_rating, review_count, is_active, created_at, updated_atid (PK), order_number (unique), user_id (FK), total_amount,
status (PENDING/CONFIRMED/SHIPPED/DELIVERED/CANCELLED),
payment_status (PENDING/COMPLETED/FAILED),
shipping_address_id (FK), created_at, updated_atid (PK), user_id (FK), product_id (FK), rating (1-5),
comment, created_at, updated_at| Method | Endpoint | Description | Access |
|---|---|---|---|
| POST | /api/auth/register |
Register new user | Public |
| POST | /api/auth/login |
Login user | Public |
| POST | /api/auth/refresh-token |
Refresh JWT token | Public |
| Method | Endpoint | Description | Access |
|---|---|---|---|
| GET | /api/users/profile |
Get user profile | User |
| PUT | /api/users/profile |
Update user profile | User |
| POST | /api/users/change-password |
Change password | User |
| GET | /api/users/addresses |
Get user addresses | User |
| POST | /api/users/addresses |
Add new address | User |
| PUT | /api/users/addresses/{id} |
Update address | User |
| DELETE | /api/users/addresses/{id} |
Delete address | User |
| Method | Endpoint | Description | Access |
|---|---|---|---|
| GET | /api/categories |
Get all categories | Public |
| GET | /api/categories/{id} |
Get category by ID | Public |
| POST | /api/categories |
Create category | Admin |
| PUT | /api/categories/{id} |
Update category | Admin |
| DELETE | /api/categories/{id} |
Delete category | Admin |
| Method | Endpoint | Description | Access |
|---|---|---|---|
| GET | /api/products |
Get all products (paginated) | Public |
| GET | /api/products/{id} |
Get product by ID | Public |
| GET | /api/products/search?keyword= |
Search products | Public |
| GET | /api/products/filter |
Filter products by price, category, rating | Public |
| GET | /api/products/category/{categoryId} |
Get products by category | Public |
| POST | /api/products |
Create product | Admin |
| PUT | /api/products/{id} |
Update product | Admin |
| DELETE | /api/products/{id} |
Delete product | Admin |
| POST | /api/products/{id}/images |
Upload product images | Admin |
| Method | Endpoint | Description | Access |
|---|---|---|---|
| GET | /api/cart |
Get user's cart | User |
| POST | /api/cart/items |
Add item to cart | User |
| PUT | /api/cart/items/{itemId} |
Update cart item quantity | User |
| DELETE | /api/cart/items/{itemId} |
Remove item from cart | User |
| DELETE | /api/cart/clear |
Clear entire cart | User |
| Method | Endpoint | Description | Access |
|---|---|---|---|
| POST | /api/orders |
Create new order | User |
| GET | /api/orders |
Get user's orders | User |
| GET | /api/orders/{id} |
Get order by ID | User |
| PUT | /api/orders/{id}/cancel |
Cancel order | User |
| GET | /api/admin/orders |
Get all orders (paginated) | Admin |
| PUT | /api/admin/orders/{id}/status |
Update order status | Admin |
| Method | Endpoint | Description | Access |
|---|---|---|---|
| POST | /api/products/{productId}/reviews |
Add review | User |
| GET | /api/products/{productId}/reviews |
Get product reviews | Public |
| GET | /api/reviews/my-reviews |
Get user's reviews | User |
| PUT | /api/reviews/{id} |
Update review | User |
| DELETE | /api/reviews/{id} |
Delete review | User |
| Method | Endpoint | Description | Access |
|---|---|---|---|
| POST | /api/payments/process |
Process payment | User |
| GET | /api/payments/order/{orderId} |
Get payment details | User |
| Method | Endpoint | Description | Access |
|---|---|---|---|
| GET | /api/admin/dashboard/stats |
Get dashboard statistics | Admin |
| GET | /api/admin/orders/recent |
Get recent orders | Admin |
| GET | /api/admin/products/low-stock |
Get low stock products | Admin |
| GET | /api/admin/users |
Get all users | Admin |
| PUT | /api/admin/users/{id}/activate |
Activate user | Admin |
| PUT | /api/admin/users/{id}/deactivate |
Deactivate user | Admin |
- Java 17 or higher
- Maven 3.9+
- PostgreSQL 15+
- IDE (IntelliJ IDEA, Eclipse, VS Code)
- Postman (for API testing)
- Git
git clone https://github.com/yourusername/ecommerce-api.git
cd ecommerce-api-- Login to PostgreSQL
psql -U postgres
-- Create database
CREATE DATABASE ecommerce_db;
-- Create user (optional)
CREATE USER ecommerce_user WITH PASSWORD 'your_password';
GRANT ALL PRIVILEGES ON DATABASE ecommerce_db TO ecommerce_user;Create/Update src/main/resources/application.properties:
# Application
spring.application.name=E-Commerce API
server.port=8080
# Database Configuration
spring.datasource.url=jdbc:postgresql://localhost:5432/ecommerce_db
spring.datasource.username=postgres
spring.datasource.password=your_password
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
# JWT Configuration
jwt.secret=your-256-bit-secret-key-change-this-in-production
jwt.expiration=86400000
# File Upload Configuration
spring.servlet.multipart.enabled=true
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
file.upload-dir=./uploads
# Email Configuration (Gmail SMTP)
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username[email protected]
spring.mail.password=your-app-password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
# Logging
logging.level.root=INFO
logging.level.com.ecommerce=DEBUG
logging.file.name=logs/ecommerce.log
# Swagger/OpenAPI
springdoc.api-docs.path=/api-docs
springdoc.swagger-ui.path=/swagger-ui.htmlmvn clean installmvn spring-boot:runThe application will start on http://localhost:8080
Open browser and navigate to:
- Swagger UI: http://localhost:8080/swagger-ui.html
- API Docs: http://localhost:8080/api-docs
- Enable 2-Factor Authentication in your Gmail account
- Generate an App Password:
- Go to Google Account β Security β 2-Step Verification β App Passwords
- Select "Mail" and "Other (Custom name)"
- Copy the generated password
- Use this password in
application.properties
Generate a secure secret key (256-bit):
# Using OpenSSL
openssl rand -base64 32Replace jwt.secret in application.properties
Create uploads directory:
mkdir uploadsOr configure different path in application.properties:
file.upload-dir=/path/to/your/uploadsRequest:
POST /api/auth/register
Content-Type: application/json
{
"firstName": "John",
"lastName": "Doe",
"email": "[email protected]",
"password": "SecurePass123!",
"phoneNumber": "+1234567890"
}Response:
{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"type": "Bearer",
"user": {
"id": 1,
"firstName": "John",
"lastName": "Doe",
"email": "[email protected]",
"role": "USER"
}
}Request:
POST /api/auth/login
Content-Type: application/json
{
"email": "[email protected]",
"password": "SecurePass123!"
}Response:
{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"type": "Bearer",
"user": {
"id": 1,
"firstName": "John",
"lastName": "Doe",
"email": "[email protected]",
"role": "USER"
}
}Request:
GET /api/products?page=0&size=10&sort=price,ascResponse:
{
"content": [
{
"id": 1,
"name": "Laptop",
"description": "High performance laptop",
"price": 999.99,
"discountPrice": 899.99,
"stockQuantity": 50,
"category": "Electronics",
"imageUrl": "/uploads/laptop.jpg",
"averageRating": 4.5,
"reviewCount": 120
}
],
"page": 0,
"size": 10,
"totalElements": 100,
"totalPages": 10
}Request:
POST /api/cart/items
Authorization: Bearer <your_jwt_token>
Content-Type: application/json
{
"productId": 1,
"quantity": 2
}Response:
{
"id": 1,
"items": [
{
"id": 1,
"product": {
"id": 1,
"name": "Laptop",
"price": 999.99
},
"quantity": 2,
"subtotal": 1999.98
}
],
"totalAmount": 1999.98
}Request:
POST /api/orders
Authorization: Bearer <your_jwt_token>
Content-Type: application/json
{
"shippingAddressId": 1,
"paymentMethod": "CREDIT_CARD"
}Response:
{
"id": 1,
"orderNumber": "ORD-2024-001",
"status": "PENDING",
"paymentStatus": "PENDING",
"totalAmount": 1999.98,
"items": [
{
"productName": "Laptop",
"quantity": 2,
"price": 999.99,
"subtotal": 1999.98
}
],
"shippingAddress": {
"street": "123 Main St",
"city": "New York",
"state": "NY",
"zipCode": "10001"
},
"createdAt": "2024-01-15T10:30:00"
}Request:
POST /api/products/1/reviews
Authorization: Bearer <your_jwt_token>
Content-Type: application/json
{
"rating": 5,
"comment": "Excellent product! Highly recommended."
}Response:
{
"id": 1,
"user": {
"firstName": "John",
"lastName": "Doe"
},
"rating": 5,
"comment": "Excellent product! Highly recommended.",
"createdAt": "2024-01-15T11:00:00"
}mvn testmvn test -Dtest=ProductServiceTestmvn clean test jacoco:reportView coverage report at: target/site/jacoco/index.html
- Unit Tests: Test individual components (services, utilities)
- Integration Tests: Test complete request-response flow
- Security Tests: Test authentication and authorization
Import the Postman collection from postman/E-Commerce-API.postman_collection.json
Contains:
- All API endpoints with examples
- Environment variables for tokens
- Pre-request scripts for authentication
- Test scripts for validation
FROM openjdk:17-jdk-slim
WORKDIR /app
COPY target/*.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]version: '3.8'
services:
postgres:
image: postgres:15-alpine
environment:
POSTGRES_DB: ecommerce_db
POSTGRES_USER: postgres
POSTGRES_PASSWORD: password
ports:
- "5432:5432"
volumes:
- postgres_data:/var/lib/postgresql/data
app:
build: .
ports:
- "8080:8080"
environment:
SPRING_DATASOURCE_URL: jdbc:postgresql://postgres:5432/ecommerce_db
SPRING_DATASOURCE_USERNAME: postgres
SPRING_DATASOURCE_PASSWORD: password
depends_on:
- postgres
volumes:
postgres_data:# Build the application
mvn clean package -DskipTests
# Build and start containers
docker-compose up --build
# Stop containers
docker-compose down# Login to Heroku
heroku login
# Create app
heroku create your-ecommerce-api
# Add PostgreSQL
heroku addons:create heroku-postgresql:hobby-dev
# Deploy
git push heroku main
# Open app
heroku open- Go to Railway.app
- Click "New Project" β "Deploy from GitHub"
- Select your repository
- Add PostgreSQL database from "New" β "Database"
- Configure environment variables
- Deploy automatically
Contributions are welcome! Please follow these steps:
- Fork the repository
- Create a feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
- Follow Java naming conventions
- Use meaningful variable and method names
- Add comments for complex logic
- Write unit tests for new features
- Update documentation for API changes
This project is licensed under the MIT License - see the LICENSE file for details.
- Your Name - Initial work - @yourusername
- Spring Boot Documentation
- Baeldung Tutorials
- Stack Overflow Community
- PostgreSQL Documentation
For support, email [email protected] or create an issue in the repository.
- β Basic CRUD operations
- β JWT Authentication
- β Shopping Cart
- β Order Management
- β Payment Processing (Mock)
- β Review System
- Real payment gateway integration (Stripe/Razorpay)
- Wishlist functionality
- Product recommendations
- Real-time order tracking
- WebSocket notifications
- Advanced analytics dashboard
- Multi-currency support
- Inventory management system
- Microservices architecture
- Redis caching
- Elasticsearch for advanced search
- Mobile app integration
- Social media authentication
- Multi-vendor support
- Subscription management
- Total Endpoints: 40+
- Authentication: JWT-based
- Database Tables: 11
- Roles: 2 (USER, ADMIN)
- Average Response Time: < 200ms
- Test Coverage: 75%+
- β Password encryption with BCrypt
- β JWT token-based authentication
- β Role-based authorization
- β CORS configuration
- β Input validation and sanitization
- β SQL injection prevention
- β XSS protection
- β Rate limiting (optional)
- β Secure file upload
- Efficient database queries with JPA
- Pagination for large datasets
- Lazy loading for related entities
- Connection pooling with HikariCP
- Query optimization with indexes
- Caching support (optional)
Built with β€οΈ using Spring Boot
β If you found this project helpful, please give it a star!