Skip to content

REST API for managing products, categories, suppliers, codes, colors & customers with full CRUD, JWT auth, refresh tokens, validation, pagination, and layered architecture.Built with Java 21, Spring Boot, Spring Security, JPA/Hibernate, Lombok, ModelMapper, and PostgreSQL.

Notifications You must be signed in to change notification settings

bekirahmetli/EcommerceRestAPI

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

EcommerceRestAPI

Spring Boot Java PostgreSQL

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.

📋 Table of Contents / İçindekiler


English

Overview

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

Features

  • 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

Architecture

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 Controllers
  • business/abstracts/ - Service interfaces
  • business/concretes/ - Service implementations
  • dao/ - Spring Data JPA repositories
  • entities/ - JPA entities
  • dto/request/ - Request DTOs with validation
  • dto/response/ - Response DTOs
  • core/ - Shared components (config, exceptions, utils)
  • jwt/ - JWT and security components

Technologies

  • 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

Prerequisites

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)

Installation

  1. Clone the repository:

    git clone <repository-url>
    cd EcommerceRestAPI
  2. Create PostgreSQL database:

    CREATE DATABASE ecommerce_rest_api;
  3. 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
  4. Build the project:

    ./mvnw clean install

    Or on Windows:

    mvnw.cmd clean install
  5. 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.

Configuration

Application Properties

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=true

Key Configuration Options:

  • spring.jpa.hibernate.ddl-auto=update - Automatically creates/updates database schema
  • spring.jpa.hibernate.show-sql=true - Shows SQL queries in console (set to false in production)

JWT Configuration

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)

Database Setup

Automatic Schema Creation

With spring.jpa.hibernate.ddl-auto=update, Hibernate will automatically create/update the database schema on application startup.

Manual Schema Setup (Optional)

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);

Seed Data

Sample data is provided in db/seed.sql. To load it:

psql -U postgres -d ecommerce_rest_api -f db/seed.sql

Or 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:

  1. Register Admin User:

    POST /v1/auth/register
    {
      "username": "admin",
      "email": "[email protected]",
      "password": "admin123",
      "role": "ADMIN"
    }
  2. 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

Usage

  1. Start the application (see Installation)

  2. Access the API:

    • Base URL: http://localhost:8080
    • API endpoints are prefixed with /v1/
  3. 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
  4. Use Postman Collection:

    • Import postman/EcommerceRestAPI.postman_collection.json into Postman
    • All endpoints are pre-configured with sample requests

Authentication

Register

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ı"
  }
}

Login

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ı"
  }
}

Refresh Token

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"
  }
}

Using Access Token

Include the access token in the Authorization header for all protected endpoints:

Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

Protected Endpoints: All endpoints except /v1/auth/** require authentication.

API Endpoints

Authentication Endpoints

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

Category Endpoints

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 number
  • pageSize (default: 2) - Items per page

Supplier Endpoints

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]"
}

Code Endpoints

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"
}

Color Endpoints

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"
}

Customer Endpoints

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"
}

Product Endpoints

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]
}

Project Structure

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

Testing

Using Postman

  1. Import Collection:

    • Open Postman
    • Click "Import"
    • Select postman/EcommerceRestAPI.postman_collection.json
  2. Test Authentication:

    • Run "Register" request to create a user
    • Run "Login" request to get access token
    • Copy the accessToken from response
    • Set it in collection variables or use it in Authorization header
  3. 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

Manual Testing

Example: Create a Product

  1. Login:

    curl -X POST http://localhost:8080/v1/auth/login \
      -H "Content-Type: application/json" \
      -d '{
        "username": "admin",
        "password": "admin123"
      }'
  2. 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"
      }'
  3. 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]"
      }'
  4. 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"
      }'
  5. 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]
      }'

Screenshots

Swagger Documentation

Swagger Documentation

Swagger UI is available at http://localhost:8080/swagger-ui.html (if Swagger is configured).

Error Handling

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ı"
  ]
}

Business Rules

  1. Product Creation:

    • Product must have a valid categoryId, supplierId, and codeId
    • colorIds is optional (many-to-many relationship)
    • Product price and stock must be positive
  2. 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)
  3. Cascading Deletes:

    • Deleting a category/supplier/code that has products will fail (foreign key constraint)
    • You must delete products first, or handle cascade relationships

Türkçe

Genel Bakış

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ı

Özellikler

  • 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ı

Mimari

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'lar
  • business/abstracts/ - Servis arayüzleri
  • business/concretes/ - Servis implementasyonları
  • dao/ - Spring Data JPA repository'leri
  • entities/ - JPA entity'leri
  • dto/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

Teknolojiler

  • 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

Gereksinimler

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)

Kurulum

  1. Depoyu klonlayın:

    git clone <repository-url>
    cd EcommerceRestAPI
  2. PostgreSQL veritabanı oluşturun:

    CREATE DATABASE ecommerce_rest_api;
  3. Veritabanı bağlantısını yapılandırın src/main/resources/application.properties dosyasında:

    spring.datasource.url=jdbc:postgresql://localhost:5432/ecommerce_rest_api
    spring.datasource.username=postgres
    spring.datasource.password=your_password
  4. Projeyi derleyin:

    ./mvnw clean install

    Windows'ta:

    mvnw.cmd clean install
  5. 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.

Yapılandırma

Uygulama Özellikleri

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ünceller
  • spring.jpa.hibernate.show-sql=true - Konsolda SQL sorgularını gösterir (production'da false yapın)

JWT Yapılandırması

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)

Veritabanı Kurulumu

Otomatik Şema Oluşturma

spring.jpa.hibernate.ddl-auto=update ile Hibernate, uygulama başlatıldığında veritabanı şemasını otomatik olarak oluşturur/günceller.

Manuel Şema Kurulumu (Opsiyonel)

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);

Seed Veriler

Ö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.sql

Veya 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:

  1. Admin Kullanıcı Kaydet:

    POST /v1/auth/register
    {
      "username": "admin",
      "email": "[email protected]",
      "password": "admin123",
      "role": "ADMIN"
    }
  2. 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

Kullanım

  1. Uygulamayı başlatın (bkz. Kurulum)

  2. API'ye erişin:

    • Base URL: http://localhost:8080
    • API endpoint'leri /v1/ ile başlar
  3. 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
  4. Postman Koleksiyonunu Kullanın:

    • postman/EcommerceRestAPI.postman_collection.json dosyasını Postman'e import edin
    • Tüm endpoint'ler örnek isteklerle önceden yapılandırılmıştır

Kimlik Doğrulama

Kayıt

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ı"
  }
}

Giriş

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ı"
  }
}

Token Yenileme

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"
  }
}

Access Token Kullanımı

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.

API Endpoint'leri

Kimlik Doğrulama Endpoint'leri

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

Kategori Endpoint'leri

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ı

Tedarikçi Endpoint'leri

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]"
}

Kod Endpoint'leri

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"
}

Renk Endpoint'leri

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ı"
}

Müşteri Endpoint'leri

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"
}

Ürün Endpoint'leri

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ı

Proje yapısı yukarıdaki İngilizce bölümde detaylı olarak açıklanmıştır.

Test Etme

Postman Kullanarak

  1. Koleksiyonu İçe Aktarın:

    • Postman'i açın
    • "Import"a tıklayın
    • postman/EcommerceRestAPI.postman_collection.json dosyasını seçin
  2. 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
  3. 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

Ekran Görüntüleri

Swagger Dokümantasyonu

Swagger Dokümantasyonu

Swagger UI (eğer yapılandırılmışsa) http://localhost:8080/swagger-ui.html adresinde mevcuttur.

Hata Yönetimi

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ı"
  ]
}

İş Kuralları

  1. Ürün Oluşturma:

    • Ürün geçerli bir categoryId, supplierId ve codeId'ye sahip olmalıdır
    • colorIds opsiyoneldir (çoktan çoğa ilişki)
    • Ürün fiyatı ve stoku pozitif olmalıdır
  2. 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)
  3. 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

📞 Contact / İletişim

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

About

REST API for managing products, categories, suppliers, codes, colors & customers with full CRUD, JWT auth, refresh tokens, validation, pagination, and layered architecture.Built with Java 21, Spring Boot, Spring Security, JPA/Hibernate, Lombok, ModelMapper, and PostgreSQL.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages