A comprehensive Spring Boot REST API for E-Commerce Product Management with JWT authentication, refresh token mechanism, and full CRUD operations for products, categories, suppliers, codes, colors, and customers.
EcommerceRestAPI is a production-ready Spring Boot REST API application designed for e-commerce product management. The API provides comprehensive functionality for managing products, categories, suppliers, codes, colors, and customers with a robust authentication system using JWT tokens and refresh tokens.
Key Highlights:
- ✅ Full CRUD operations for all entities
- ✅ JWT-based authentication with refresh token support
- ✅ Layered architecture (Controller → Service → Repository)
- ✅ DTO-based design with validation
- ✅ Pagination support
- ✅ Comprehensive error handling
- ✅ RESTful API best practices
-
Authentication & Authorization
- JWT token-based authentication
- Refresh token mechanism (4-hour expiry)
- Role-based access control (USER, ADMIN)
- Secure password encryption with BCrypt
-
Product Management
- Complete CRUD operations
- Product-category-supplier-code relationships
- Many-to-many relationship with colors
- Pagination support
- Related entity endpoints (get supplier, category, code, colors of a product)
-
Entity Management
- Categories, Suppliers, Codes, Colors, Customers
- Full CRUD with validation
- Pagination for list endpoints
-
API Features
- RESTful API design
- Standardized response format (Result/ResultData)
- Comprehensive validation
- Error handling with meaningful messages
- CORS configuration
The project follows a layered architecture pattern:
┌─────────────────────────────────────┐
│ API Layer (Controllers) │
│ - REST endpoints │
│ - Request/Response handling │
│ - Authentication filter │
└──────────────┬──────────────────────┘
│
┌──────────────▼──────────────────────┐
│ Business Layer (Services) │
│ - Business logic │
│ - Transaction management │
│ - Exception handling │
└──────────────┬──────────────────────┘
│
┌──────────────▼──────────────────────┐
│ Data Access Layer (Repositories) │
│ - Spring Data JPA │
│ - Database operations │
└──────────────┬──────────────────────┘
│
┌──────────────▼──────────────────────┐
│ Entity Layer (Models) │
│ - JPA entities │
│ - Relationships │
└─────────────────────────────────────┘
Package Structure:
api/- REST Controllersbusiness/abstracts/- Service interfacesbusiness/concretes/- Service implementationsdao/- Spring Data JPA repositoriesentities/- JPA entitiesdto/request/- Request DTOs with validationdto/response/- Response DTOscore/- Shared components (config, exceptions, utils)jwt/- JWT and security components
- Framework: Spring Boot 3.5.6
- Language: Java 21
- Build Tool: Maven
- Database: PostgreSQL
- Security: Spring Security + JWT (jjwt 0.12.3)
- Object Mapping: ModelMapper 3.2.5
- Validation: Jakarta Validation
- Utilities: Lombok
- ORM: Spring Data JPA / Hibernate
Before you begin, ensure you have the following installed:
- Java 21 or higher
- Maven 3.6+ (or use the included Maven Wrapper)
- PostgreSQL 15+ (or compatible version)
-
Clone the repository:
git clone <repository-url> cd EcommerceRestAPI
-
Create PostgreSQL database:
CREATE DATABASE ecommerce_rest_api;
-
Configure database connection in
src/main/resources/application.properties:spring.datasource.url=jdbc:postgresql://localhost:5432/ecommerce_rest_api spring.datasource.username=postgres spring.datasource.password=your_password
-
Build the project:
./mvnw clean install
Or on Windows:
mvnw.cmd clean install
-
Run the application:
./mvnw spring-boot:run
Or on Windows:
mvnw.cmd spring-boot:run
The application will start on http://localhost:8080 by default.
The main configuration file is located at src/main/resources/application.properties:
spring.application.name=EcommerceRestAPI
# Database Configuration
spring.datasource.url=jdbc:postgresql://localhost:5432/ecommerce_rest_api
spring.datasource.username=postgres
spring.datasource.password=your_password
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.show-sql=trueKey Configuration Options:
spring.jpa.hibernate.ddl-auto=update- Automatically creates/updates database schemaspring.jpa.hibernate.show-sql=true- Shows SQL queries in console (set tofalsein production)
JWT settings are configured in JwtService.java:
- Secret Key: Defined as constant
- Access Token Expiry: 2 hours (7200000 ms)
- Refresh Token Expiry: 4 hours (14400000 ms)
With spring.jpa.hibernate.ddl-auto=update, Hibernate will automatically create/update the database schema on application startup.
If you prefer manual setup, execute the following SQL:
-- Ensure product_code_id column exists
ALTER TABLE products
ADD COLUMN IF NOT EXISTS product_code_id INTEGER;
-- Add foreign key constraint
ALTER TABLE products
ADD CONSTRAINT fk_product_code
FOREIGN KEY (product_code_id) REFERENCES code(code_id);Sample data is provided in db/seed.sql. To load it:
psql -U postgres -d ecommerce_rest_api -f db/seed.sqlOr using pgAdmin or any PostgreSQL client, execute the SQL file.
Seed Data Includes:
- 5 categories
- 5 suppliers
- 10 codes
- 8 colors
- 5 customers
- 10 products with relationships
User Registration:
- Users must be created via API using the registration endpoint
- This ensures passwords are properly hashed with BCrypt
To create users, use the API:
-
Register Admin User:
POST /v1/auth/register { "username": "admin", "email": "[email protected]", "password": "admin123", "role": "ADMIN" } -
Register Regular Users:
POST /v1/auth/register { "username": "user1", "email": "[email protected]", "password": "user123", "role": "USER" }
Why not in seed data?
- BCrypt hashes are unique each time (due to random salt)
- API registration ensures proper password hashing
- More secure and follows best practices
-
Start the application (see Installation)
-
Access the API:
- Base URL:
http://localhost:8080 - API endpoints are prefixed with
/v1/
- Base URL:
-
Authenticate:
- First, register a new user or use seed data credentials
- Login to get access token
- Use the access token in
Authorization: Bearer <token>header for protected endpoints
-
Use Postman Collection:
- Import
postman/EcommerceRestAPI.postman_collection.jsoninto Postman - All endpoints are pre-configured with sample requests
- Import
Endpoint: POST /v1/auth/register
Request Body:
{
"username": "newuser",
"email": "[email protected]",
"password": "password123",
"role": "USER"
}Response (201 Created):
{
"success": true,
"message": "201",
"httpStatus": "201",
"data": {
"accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"refreshToken": "uuid-string-here",
"username": "newuser",
"role": "USER",
"message": "Kayıt başarılı"
}
}Endpoint: POST /v1/auth/login
Request Body:
{
"username": "admin",
"password": "admin123"
}Response (200 OK):
{
"success": true,
"message": "200",
"httpStatus": "200",
"data": {
"accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"refreshToken": "new-uuid-string",
"username": "admin",
"role": "ADMIN",
"message": "Giriş başarılı"
}
}Endpoint: POST /v1/auth/refreshToken
Request Body:
{
"refreshToken": "uuid-string-from-login-response"
}Response (200 OK):
{
"success": true,
"message": "200",
"httpStatus": "200",
"data": {
"accessToken": "new-access-token",
"refreshToken": "new-refresh-token",
"username": "admin",
"role": "ADMIN",
"message": "Token yenilendi"
}
}Include the access token in the Authorization header for all protected endpoints:
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Protected Endpoints: All endpoints except /v1/auth/** require authentication.
| Method | Endpoint | Description | Auth Required |
|---|---|---|---|
| POST | /v1/auth/register |
Register new user | No |
| POST | /v1/auth/login |
Login and get tokens | No |
| POST | /v1/auth/refreshToken |
Refresh access token | No |
| Method | Endpoint | Description | Auth Required |
|---|---|---|---|
| POST | /v1/categories |
Create category | Yes |
| GET | /v1/categories/{id} |
Get category by ID | Yes |
| GET | /v1/categories |
Get all categories (paginated) | Yes |
| PUT | /v1/categories |
Update category | Yes |
| DELETE | /v1/categories/{id} |
Delete category | Yes |
Request Example (Create):
{
"categoryName": "Electronics"
}Query Parameters (List):
page(default: 0) - Page numberpageSize(default: 2) - Items per page
| Method | Endpoint | Description | Auth Required |
|---|---|---|---|
| POST | /v1/suppliers |
Create supplier | Yes |
| GET | /v1/suppliers/{id} |
Get supplier by ID | Yes |
| GET | /v1/suppliers |
Get all suppliers (paginated) | Yes |
| PUT | /v1/suppliers |
Update supplier | Yes |
| DELETE | /v1/suppliers/{id} |
Delete supplier | Yes |
Request Example (Create):
{
"companyName": "TechCorp",
"contactName": "John Doe",
"address": "Istanbul, Turkey",
"contactMail": "[email protected]"
}| Method | Endpoint | Description | Auth Required |
|---|---|---|---|
| POST | /v1/codes |
Create code | Yes |
| GET | /v1/codes/{id} |
Get code by ID | Yes |
| GET | /v1/codes |
Get all codes (paginated) | Yes |
| PUT | /v1/codes |
Update code | Yes |
| DELETE | /v1/codes/{id} |
Delete code | Yes |
Request Example (Create):
{
"codeGroup": "ELK",
"codeSerial": "001"
}| Method | Endpoint | Description | Auth Required |
|---|---|---|---|
| POST | /v1/colors |
Create color | Yes |
| GET | /v1/colors/{id} |
Get color by ID | Yes |
| GET | /v1/colors |
Get all colors (paginated) | Yes |
| PUT | /v1/colors |
Update color | Yes |
| DELETE | /v1/colors/{id} |
Delete color | Yes |
Request Example (Create):
{
"colorName": "Red"
}| Method | Endpoint | Description | Auth Required |
|---|---|---|---|
| POST | /v1/customers |
Create customer | Yes |
| GET | /v1/customers/{id} |
Get customer by ID | Yes |
| GET | /v1/customers |
Get all customers (paginated) | Yes |
| PUT | /v1/customers |
Update customer | Yes |
| DELETE | /v1/customers/{id} |
Delete customer | Yes |
Request Example (Create):
{
"customerName": "John Doe",
"customerGender": "Male",
"customerMail": "[email protected]",
"customerOnDate": "2024-01-15"
}| Method | Endpoint | Description | Auth Required |
|---|---|---|---|
| POST | /v1/products |
Create product | Yes |
| GET | /v1/products/{id} |
Get product by ID | Yes |
| GET | /v1/products |
Get all products (paginated) | Yes |
| PUT | /v1/products/{id} |
Update product | Yes |
| DELETE | /v1/products/{id} |
Delete product | Yes |
| GET | /v1/products/{id}/supplier |
Get product's supplier | Yes |
| GET | /v1/products/{id}/category |
Get product's category | Yes |
| GET | /v1/products/{id}/code |
Get product's code | Yes |
| GET | /v1/products/{id}/colors |
Get product's colors | Yes |
Request Example (Create):
{
"name": "Laptop HP 15",
"prc": 15999.99,
"stock": 50,
"supplierId": 1,
"categoryId": 1,
"codeId": 1,
"colorIds": [1, 2, 3]
}Request Example (Update):
{
"id": 1,
"name": "Laptop HP 15 Updated",
"prc": 14999.99,
"stock": 45,
"supplierId": 1,
"categoryId": 1,
"codeId": 1,
"colorIds": [1, 2]
}EcommerceRestAPI/
├── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/
│ │ │ └── example/
│ │ │ ├── EcommerceRestApiApplication.java
│ │ │ ├── api/ # REST Controllers
│ │ │ │ ├── AuthController.java
│ │ │ │ ├── CategoryController.java
│ │ │ │ ├── CodeController.java
│ │ │ │ ├── ColorController.java
│ │ │ │ ├── CustomerController.java
│ │ │ │ ├── ProductController.java
│ │ │ │ └── SupplierController.java
│ │ │ ├── business/ # Business Logic
│ │ │ │ ├── abstracts/ # Service Interfaces
│ │ │ │ │ ├── IAuthService.java
│ │ │ │ │ ├── ICategoryService.java
│ │ │ │ │ ├── ICodeService.java
│ │ │ │ │ ├── IColorService.java
│ │ │ │ │ ├── ICustomerService.java
│ │ │ │ │ ├── IProductService.java
│ │ │ │ │ ├── IRefreshTokenService.java
│ │ │ │ │ └── ISupplierService.java
│ │ │ │ └── concretes/ # Service Implementations
│ │ │ │ ├── AuthManager.java
│ │ │ │ ├── CategoryManager.java
│ │ │ │ ├── CodeManager.java
│ │ │ │ ├── ColorManager.java
│ │ │ │ ├── CustomerManager.java
│ │ │ │ ├── ProductManager.java
│ │ │ │ ├── RefreshTokenManager.java
│ │ │ │ └── SupplierManager.java
│ │ │ ├── config/ # Configuration
│ │ │ │ ├── AppConfig.java # Security beans
│ │ │ │ └── SecurityConfig.java # Security filter chain
│ │ │ ├── core/ # Shared Components
│ │ │ │ ├── config/
│ │ │ │ │ ├── GlobalExceptionHandler.java
│ │ │ │ │ └── modelMapper/
│ │ │ │ │ ├── IModelMapperService.java
│ │ │ │ │ ├── ModelManagerService.java
│ │ │ │ │ └── ModelMapperConfig.java
│ │ │ │ ├── exception/
│ │ │ │ │ └── NotFoundException.java
│ │ │ │ ├── result/
│ │ │ │ │ ├── Result.java
│ │ │ │ │ └── ResultData.java
│ │ │ │ └── utils/
│ │ │ │ ├── Msg.java
│ │ │ │ └── ResultHelper.java
│ │ │ ├── dao/ # Repositories
│ │ │ │ ├── CategoryRepo.java
│ │ │ │ ├── CodeRepo.java
│ │ │ │ ├── ColorRepo.java
│ │ │ │ ├── CustomerRepo.java
│ │ │ │ ├── ProductRepo.java
│ │ │ │ ├── RefreshTokenRepo.java
│ │ │ │ ├── SupplierRepo.java
│ │ │ │ └── UserRepo.java
│ │ │ ├── dto/ # Data Transfer Objects
│ │ │ │ ├── request/
│ │ │ │ │ ├── category/
│ │ │ │ │ ├── code/
│ │ │ │ │ ├── color/
│ │ │ │ │ ├── customer/
│ │ │ │ │ ├── product/
│ │ │ │ │ ├── supplier/
│ │ │ │ │ └── user/
│ │ │ │ └── response/
│ │ │ │ ├── category/
│ │ │ │ ├── code/
│ │ │ │ ├── color/
│ │ │ │ ├── customer/
│ │ │ │ ├── product/
│ │ │ │ ├── supplier/
│ │ │ │ └── user/
│ │ │ ├── entities/ # JPA Entities
│ │ │ │ ├── Category.java
│ │ │ │ ├── Code.java
│ │ │ │ ├── Color.java
│ │ │ │ ├── Customer.java
│ │ │ │ ├── Product.java
│ │ │ │ ├── RefreshToken.java
│ │ │ │ ├── Supplier.java
│ │ │ │ └── User.java
│ │ │ └── jwt/ # JWT Components
│ │ │ ├── AuthEntryPoint.java
│ │ │ ├── JwtAuthenticationFilter.java
│ │ │ ├── JwtService.java
│ │ │ └── RefreshTokenRequest.java
│ │ └── resources/
│ │ └── application.properties
│ └── test/
│ └── java/
│ └── com/
│ └── example/
│ └── EcommerceRestApiApplicationTests.java
├── db/
│ └── seed.sql # Sample database data
├── docs/
│ └── swagger-ss.png # Swagger documentation screenshot
├── postman/
│ └── EcommerceRestAPI.postman_collection.json # Postman collection
├── pom.xml # Maven dependencies
├── mvnw # Maven wrapper (Unix)
├── mvnw.cmd # Maven wrapper (Windows)
└── README.md # This file
-
Import Collection:
- Open Postman
- Click "Import"
- Select
postman/EcommerceRestAPI.postman_collection.json
-
Test Authentication:
- Run "Register" request to create a user
- Run "Login" request to get access token
- Copy the
accessTokenfrom response - Set it in collection variables or use it in Authorization header
-
Test Endpoints:
- All endpoints are organized by entity
- Each endpoint has sample request bodies
- Make sure to update IDs in requests based on your data
Example: Create a Product
-
Login:
curl -X POST http://localhost:8080/v1/auth/login \ -H "Content-Type: application/json" \ -d '{ "username": "admin", "password": "admin123" }'
-
Create Category (if not exists):
curl -X POST http://localhost:8080/v1/categories \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \ -d '{ "categoryName": "Electronics" }'
-
Create Supplier (if not exists):
curl -X POST http://localhost:8080/v1/suppliers \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \ -d '{ "companyName": "TechCorp", "contactName": "John Doe", "address": "Istanbul", "contactMail": "[email protected]" }'
-
Create Code (if not exists):
curl -X POST http://localhost:8080/v1/codes \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \ -d '{ "codeGroup": "ELK", "codeSerial": "001" }'
-
Create Product:
curl -X POST http://localhost:8080/v1/products \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \ -d '{ "name": "Laptop HP 15", "prc": 15999.99, "stock": 50, "supplierId": 1, "categoryId": 1, "codeId": 1, "colorIds": [1, 2] }'
Swagger UI is available at http://localhost:8080/swagger-ui.html (if Swagger is configured).
The API uses a standardized error response format:
{
"success": false,
"message": "Error message here",
"code": "400",
"data": null
}Common Error Codes:
400- Bad Request (validation errors)401- Unauthorized (authentication required)404- Not Found (resource not found)500- Internal Server Error
Validation Errors:
{
"success": false,
"message": "VALIDATE_ERROR",
"code": "400",
"data": [
"Ürün adı boş olamaz",
"Fiyat pozitif olmalı"
]
}-
Product Creation:
- Product must have a valid
categoryId,supplierId, andcodeId colorIdsis optional (many-to-many relationship)- Product price and stock must be positive
- Product must have a valid
-
Authentication:
- Access tokens expire after 2 hours
- Refresh tokens expire after 4 hours
- One refresh token per user (old token is deleted on new login)
-
Cascading Deletes:
- Deleting a category/supplier/code that has products will fail (foreign key constraint)
- You must delete products first, or handle cascade relationships
EcommerceRestAPI, JWT kimlik doğrulaması, refresh token mekanizması ve ürünler, kategoriler, tedarikçiler, kodlar, renkler ve müşteriler için tam CRUD işlemleri ile e-ticaret ürün yönetimi için tasarlanmış production-ready bir Spring Boot REST API uygulamasıdır.
Önemli Özellikler:
- ✅ Tüm entity'ler için tam CRUD işlemleri
- ✅ Refresh token desteği ile JWT tabanlı kimlik doğrulama
- ✅ Katmanlı mimari (Controller → Service → Repository)
- ✅ Validasyon ile DTO tabanlı tasarım
- ✅ Sayfalama desteği
- ✅ Kapsamlı hata yönetimi
- ✅ RESTful API en iyi uygulamaları
-
Kimlik Doğrulama ve Yetkilendirme
- JWT token tabanlı kimlik doğrulama
- Refresh token mekanizması (4 saatlik süre)
- Rol tabanlı erişim kontrolü (USER, ADMIN)
- BCrypt ile güvenli şifre şifreleme
-
Ürün Yönetimi
- Tam CRUD işlemleri
- Ürün-kategori-tedarikçi-kod ilişkileri
- Renklerle çoktan çoğa ilişki
- Sayfalama desteği
- İlgili entity endpoint'leri (ürünün tedarikçisi, kategorisi, kodu, renkleri)
-
Entity Yönetimi
- Kategoriler, Tedarikçiler, Kodlar, Renkler, Müşteriler
- Validasyon ile tam CRUD
- Liste endpoint'leri için sayfalama
-
API Özellikleri
- RESTful API tasarımı
- Standartlaştırılmış yanıt formatı (Result/ResultData)
- Kapsamlı validasyon
- Anlamlı mesajlarla hata yönetimi
- CORS yapılandırması
Proje katmanlı mimari desenini takip eder:
┌─────────────────────────────────────┐
│ API Katmanı (Controllers) │
│ - REST endpoint'leri │
│ - Request/Response işleme │
│ - Kimlik doğrulama filtresi │
└──────────────┬──────────────────────┘
│
┌──────────────▼──────────────────────┐
│ İş Mantığı Katmanı (Services) │
│ - İş mantığı │
│ - İşlem yönetimi │
│ - Exception işleme │
└──────────────┬──────────────────────┘
│
┌──────────────▼──────────────────────┐
│ Veri Erişim Katmanı (Repositories) │
│ - Spring Data JPA │
│ - Veritabanı işlemleri │
└──────────────┬──────────────────────┘
│
┌──────────────▼──────────────────────┐
│ Entity Katmanı (Models) │
│ - JPA entity'leri │
│ - İlişkiler │
└─────────────────────────────────────┘
Paket Yapısı:
api/- REST Controller'larbusiness/abstracts/- Servis arayüzleribusiness/concretes/- Servis implementasyonlarıdao/- Spring Data JPA repository'lerientities/- JPA entity'leridto/request/- Validasyon ile Request DTO'larıdto/response/- Response DTO'larıcore/- Paylaşılan bileşenler (config, exceptions, utils)jwt/- JWT ve güvenlik bileşenleri
- Framework: Spring Boot 3.5.6
- Dil: Java 21
- Build Aracı: Maven
- Veritabanı: PostgreSQL
- Güvenlik: Spring Security + JWT (jjwt 0.12.3)
- Nesne Eşleme: ModelMapper 3.2.5
- Validasyon: Jakarta Validation
- Yardımcılar: Lombok
- ORM: Spring Data JPA / Hibernate
Başlamadan önce, aşağıdakilerin yüklü olduğundan emin olun:
- Java 21 veya üzeri
- Maven 3.6+ (veya dahil edilen Maven Wrapper'ı kullanın)
- PostgreSQL 15+ (veya uyumlu sürüm)
-
Depoyu klonlayın:
git clone <repository-url> cd EcommerceRestAPI
-
PostgreSQL veritabanı oluşturun:
CREATE DATABASE ecommerce_rest_api;
-
Veritabanı bağlantısını yapılandırın
src/main/resources/application.propertiesdosyasında:spring.datasource.url=jdbc:postgresql://localhost:5432/ecommerce_rest_api spring.datasource.username=postgres spring.datasource.password=your_password
-
Projeyi derleyin:
./mvnw clean install
Windows'ta:
mvnw.cmd clean install
-
Uygulamayı çalıştırın:
./mvnw spring-boot:run
Windows'ta:
mvnw.cmd spring-boot:run
Uygulama varsayılan olarak http://localhost:8080 adresinde başlayacaktır.
Ana yapılandırma dosyası src/main/resources/application.properties konumundadır:
spring.application.name=EcommerceRestAPI
# Veritabanı Yapılandırması
spring.datasource.url=jdbc:postgresql://localhost:5432/ecommerce_rest_api
spring.datasource.username=postgres
spring.datasource.password=your_password
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.show-sql=trueÖnemli Yapılandırma Seçenekleri:
spring.jpa.hibernate.ddl-auto=update- Veritabanı şemasını otomatik olarak oluşturur/güncellerspring.jpa.hibernate.show-sql=true- Konsolda SQL sorgularını gösterir (production'dafalseyapın)
JWT ayarları JwtService.java dosyasında yapılandırılmıştır:
- Secret Key: Sabit olarak tanımlanmış
- Access Token Süresi: 2 saat (7200000 ms)
- Refresh Token Süresi: 4 saat (14400000 ms)
spring.jpa.hibernate.ddl-auto=update ile Hibernate, uygulama başlatıldığında veritabanı şemasını otomatik olarak oluşturur/günceller.
Manuel kurulum tercih ederseniz, aşağıdaki SQL'i çalıştırın:
-- product_code_id kolonunun var olduğundan emin olun
ALTER TABLE products
ADD COLUMN IF NOT EXISTS product_code_id INTEGER;
-- Foreign key constraint ekleyin
ALTER TABLE products
ADD CONSTRAINT fk_product_code
FOREIGN KEY (product_code_id) REFERENCES code(code_id);Örnek veriler db/seed.sql dosyasında sağlanmıştır. Yüklemek için:
psql -U postgres -d ecommerce_rest_api -f db/seed.sqlVeya pgAdmin veya herhangi bir PostgreSQL istemcisi kullanarak SQL dosyasını çalıştırın.
Seed Veriler İçerir:
- 5 kategori
- 5 tedarikçi
- 10 kod
- 8 renk
- 5 müşteri
- İlişkilerle 10 ürün
Kullanıcı Kaydı:
- Kullanıcılar API üzerinden kayıt endpoint'i kullanılarak oluşturulmalıdır
- Bu, şifrelerin BCrypt ile düzgün şekilde hash'lenmesini sağlar
Kullanıcı oluşturmak için API'yi kullanın:
-
Admin Kullanıcı Kaydet:
POST /v1/auth/register { "username": "admin", "email": "[email protected]", "password": "admin123", "role": "ADMIN" } -
Normal Kullanıcı Kaydet:
POST /v1/auth/register { "username": "user1", "email": "[email protected]", "password": "user123", "role": "USER" }
Neden seed verilerinde değil?
- BCrypt hash'leri her seferinde benzersizdir (rastgele salt nedeniyle)
- API kaydı düzgün şifre hash'lemesini sağlar
- Daha güvenli ve en iyi uygulamalara uygundur
-
Uygulamayı başlatın (bkz. Kurulum)
-
API'ye erişin:
- Base URL:
http://localhost:8080 - API endpoint'leri
/v1/ile başlar
- Base URL:
-
Kimlik doğrulama yapın:
- Önce yeni bir kullanıcı kaydedin veya seed veri kimlik bilgilerini kullanın
- Giriş yaparak access token alın
- Korumalı endpoint'ler için
Authorization: Bearer <token>header'ında access token'ı kullanın
-
Postman Koleksiyonunu Kullanın:
postman/EcommerceRestAPI.postman_collection.jsondosyasını Postman'e import edin- Tüm endpoint'ler örnek isteklerle önceden yapılandırılmıştır
Endpoint: POST /v1/auth/register
İstek Gövdesi:
{
"username": "newuser",
"email": "[email protected]",
"password": "password123",
"role": "USER"
}Yanıt (201 Created):
{
"success": true,
"message": "201",
"httpStatus": "201",
"data": {
"accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"refreshToken": "uuid-string-here",
"username": "newuser",
"role": "USER",
"message": "Kayıt başarılı"
}
}Endpoint: POST /v1/auth/login
İstek Gövdesi:
{
"username": "admin",
"password": "admin123"
}Yanıt (200 OK):
{
"success": true,
"message": "200",
"httpStatus": "200",
"data": {
"accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"refreshToken": "new-uuid-string",
"username": "admin",
"role": "ADMIN",
"message": "Giriş başarılı"
}
}Endpoint: POST /v1/auth/refreshToken
İstek Gövdesi:
{
"refreshToken": "uuid-string-from-login-response"
}Yanıt (200 OK):
{
"success": true,
"message": "200",
"httpStatus": "200",
"data": {
"accessToken": "new-access-token",
"refreshToken": "new-refresh-token",
"username": "admin",
"role": "ADMIN",
"message": "Token yenilendi"
}
}Tüm korumalı endpoint'ler için Authorization header'ında access token'ı ekleyin:
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Korumalı Endpoint'ler: /v1/auth/** dışındaki tüm endpoint'ler kimlik doğrulama gerektirir.
| Method | Endpoint | Açıklama | Auth Gerekli |
|---|---|---|---|
| POST | /v1/auth/register |
Yeni kullanıcı kaydet | Hayır |
| POST | /v1/auth/login |
Giriş yap ve token al | Hayır |
| POST | /v1/auth/refreshToken |
Access token yenile | Hayır |
| Method | Endpoint | Açıklama | Auth Gerekli |
|---|---|---|---|
| POST | /v1/categories |
Kategori oluştur | Evet |
| GET | /v1/categories/{id} |
ID'ye göre kategori getir | Evet |
| GET | /v1/categories |
Tüm kategorileri getir (sayfalı) | Evet |
| PUT | /v1/categories |
Kategori güncelle | Evet |
| DELETE | /v1/categories/{id} |
Kategori sil | Evet |
İstek Örneği (Oluştur):
{
"categoryName": "Elektronik"
}Query Parametreleri (Liste):
page(varsayılan: 0) - Sayfa numarasıpageSize(varsayılan: 2) - Sayfa başına öğe sayısı
| Method | Endpoint | Açıklama | Auth Gerekli |
|---|---|---|---|
| POST | /v1/suppliers |
Tedarikçi oluştur | Evet |
| GET | /v1/suppliers/{id} |
ID'ye göre tedarikçi getir | Evet |
| GET | /v1/suppliers |
Tüm tedarikçileri getir (sayfalı) | Evet |
| PUT | /v1/suppliers |
Tedarikçi güncelle | Evet |
| DELETE | /v1/suppliers/{id} |
Tedarikçi sil | Evet |
İstek Örneği (Oluştur):
{
"companyName": "TechCorp",
"contactName": "Ahmet Yılmaz",
"address": "İstanbul, Türkiye",
"contactMail": "[email protected]"
}| Method | Endpoint | Açıklama | Auth Gerekli |
|---|---|---|---|
| POST | /v1/codes |
Kod oluştur | Evet |
| GET | /v1/codes/{id} |
ID'ye göre kod getir | Evet |
| GET | /v1/codes |
Tüm kodları getir (sayfalı) | Evet |
| PUT | /v1/codes |
Kod güncelle | Evet |
| DELETE | /v1/codes/{id} |
Kod sil | Evet |
İstek Örneği (Oluştur):
{
"codeGroup": "ELK",
"codeSerial": "001"
}| Method | Endpoint | Açıklama | Auth Gerekli |
|---|---|---|---|
| POST | /v1/colors |
Renk oluştur | Evet |
| GET | /v1/colors/{id} |
ID'ye göre renk getir | Evet |
| GET | /v1/colors |
Tüm renkleri getir (sayfalı) | Evet |
| PUT | /v1/colors |
Renk güncelle | Evet |
| DELETE | /v1/colors/{id} |
Renk sil | Evet |
İstek Örneği (Oluştur):
{
"colorName": "Kırmızı"
}| Method | Endpoint | Açıklama | Auth Gerekli |
|---|---|---|---|
| POST | /v1/customers |
Müşteri oluştur | Evet |
| GET | /v1/customers/{id} |
ID'ye göre müşteri getir | Evet |
| GET | /v1/customers |
Tüm müşterileri getir (sayfalı) | Evet |
| PUT | /v1/customers |
Müşteri güncelle | Evet |
| DELETE | /v1/customers/{id} |
Müşteri sil | Evet |
İstek Örneği (Oluştur):
{
"customerName": "Ali Veli",
"customerGender": "Erkek",
"customerMail": "[email protected]",
"customerOnDate": "2024-01-15"
}| Method | Endpoint | Açıklama | Auth Gerekli |
|---|---|---|---|
| POST | /v1/products |
Ürün oluştur | Evet |
| GET | /v1/products/{id} |
ID'ye göre ürün getir | Evet |
| GET | /v1/products |
Tüm ürünleri getir (sayfalı) | Evet |
| PUT | /v1/products/{id} |
Ürün güncelle | Evet |
| DELETE | /v1/products/{id} |
Ürün sil | Evet |
| GET | /v1/products/{id}/supplier |
Ürünün tedarikçisini getir | Evet |
| GET | /v1/products/{id}/category |
Ürünün kategorisini getir | Evet |
| GET | /v1/products/{id}/code |
Ürünün kodunu getir | Evet |
| GET | /v1/products/{id}/colors |
Ürünün renklerini getir | Evet |
İstek Örneği (Oluştur):
{
"name": "Laptop HP 15",
"prc": 15999.99,
"stock": 50,
"supplierId": 1,
"categoryId": 1,
"codeId": 1,
"colorIds": [1, 2, 3]
}İstek Örneği (Güncelle):
{
"id": 1,
"name": "Laptop HP 15 Güncellendi",
"prc": 14999.99,
"stock": 45,
"supplierId": 1,
"categoryId": 1,
"codeId": 1,
"colorIds": [1, 2]
}Proje yapısı yukarıdaki İngilizce bölümde detaylı olarak açıklanmıştır.
-
Koleksiyonu İçe Aktarın:
- Postman'i açın
- "Import"a tıklayın
postman/EcommerceRestAPI.postman_collection.jsondosyasını seçin
-
Kimlik Doğrulamayı Test Edin:
- "Register" isteğini çalıştırarak kullanıcı oluşturun
- "Login" isteğini çalıştırarak access token alın
- Yanıttan
accessToken'ı kopyalayın - Koleksiyon değişkenlerinde ayarlayın veya Authorization header'ında kullanın
-
Endpoint'leri Test Edin:
- Tüm endpoint'ler entity'ye göre organize edilmiştir
- Her endpoint'te örnek istek gövdeleri vardır
- İsteklerdeki ID'leri verilerinize göre güncellediğinizden emin olun
Swagger UI (eğer yapılandırılmışsa) http://localhost:8080/swagger-ui.html adresinde mevcuttur.
API standartlaştırılmış bir hata yanıt formatı kullanır:
{
"success": false,
"message": "Hata mesajı burada",
"code": "400",
"data": null
}Yaygın Hata Kodları:
400- Bad Request (validasyon hataları)401- Unauthorized (kimlik doğrulama gerekli)404- Not Found (kaynak bulunamadı)500- Internal Server Error
Validasyon Hataları:
{
"success": false,
"message": "VALIDATE_ERROR",
"code": "400",
"data": [
"Ürün adı boş olamaz",
"Fiyat pozitif olmalı"
]
}-
Ürün Oluşturma:
- Ürün geçerli bir
categoryId,supplierIdvecodeId'ye sahip olmalıdır colorIdsopsiyoneldir (çoktan çoğa ilişki)- Ürün fiyatı ve stoku pozitif olmalıdır
- Ürün geçerli bir
-
Kimlik Doğrulama:
- Access token'lar 2 saat sonra sona erer
- Refresh token'lar 4 saat sonra sona erer
- Kullanıcı başına bir refresh token (yeni girişte eski token silinir)
-
Kaskadlı Silmeler:
- Ürünlere sahip bir kategori/tedarikçi/kod silmek başarısız olur (foreign key constraint)
- Önce ürünleri silmeniz veya cascade ilişkilerini yönetmeniz gerekir
For questions or suggestions, please open an issue on GitHub.
Sorularınız veya önerileriniz için lütfen GitHub'da bir issue açın.
Made with ❤️ using Spring Boot