Skip to content

stefanramac/java-spring-boot-api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

3 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Java Spring Boot RESTful API

A comprehensive Spring Boot RESTful API project with 10 fully-featured services demonstrating best practices for enterprise applications.

πŸ“‹ Table of Contents

✨ Features

  • 10 RESTful Services with full CRUD operations
  • Package-by-Feature structure for better modularity
  • Comprehensive Validation using Bean Validation API
  • Global Exception Handling with custom error responses
  • Standard API Response Wrapper for consistent responses
  • OpenAPI/Swagger Documentation - fully compatible with Swagger Editor
  • H2 In-Memory Database with sample data
  • Centralized Logging using SLF4J
  • Health Check Endpoint for monitoring
  • Unit Tests for service and controller layers
  • Proper HTTP Status Codes (200, 201, 400, 404, 500)

πŸ›  Technology Stack

  • Java 17
  • Spring Boot 3.1.5
  • Maven - Dependency Management
  • Spring Data JPA - Data Access
  • H2 Database - In-Memory Database
  • Springdoc OpenAPI - API Documentation
  • Lombok - Boilerplate Code Reduction
  • JUnit 5 - Testing Framework
  • Mockito - Mocking Framework

πŸ“ Project Structure

java-spring-boot-api/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ main/
β”‚   β”‚   β”œβ”€β”€ java/com/example/springbootapi/
β”‚   β”‚   β”‚   β”œβ”€β”€ SpringBootApiApplication.java
β”‚   β”‚   β”‚   β”œβ”€β”€ common/
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ config/
β”‚   β”‚   β”‚   β”‚   β”‚   └── OpenApiConfig.java
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ exception/
β”‚   β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ GlobalExceptionHandler.java
β”‚   β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ ResourceNotFoundException.java
β”‚   β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ BadRequestException.java
β”‚   β”‚   β”‚   β”‚   β”‚   └── ErrorDetails.java
β”‚   β”‚   β”‚   β”‚   └── response/
β”‚   β”‚   β”‚   β”‚       └── ApiResponse.java
β”‚   β”‚   β”‚   β”œβ”€β”€ health/
β”‚   β”‚   β”‚   β”‚   └── HealthCheckController.java
β”‚   β”‚   β”‚   β”œβ”€β”€ users/
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ User.java
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ UserRepository.java
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ UserService.java
β”‚   β”‚   β”‚   β”‚   └── UserController.java
β”‚   β”‚   β”‚   β”œβ”€β”€ products/
β”‚   β”‚   β”‚   β”œβ”€β”€ orders/
β”‚   β”‚   β”‚   β”œβ”€β”€ customers/
β”‚   β”‚   β”‚   β”œβ”€β”€ invoices/
β”‚   β”‚   β”‚   β”œβ”€β”€ payments/
β”‚   β”‚   β”‚   β”œβ”€β”€ categories/
β”‚   β”‚   β”‚   β”œβ”€β”€ reviews/
β”‚   β”‚   β”‚   β”œβ”€β”€ suppliers/
β”‚   β”‚   β”‚   └── inventory/
β”‚   β”‚   └── resources/
β”‚   β”‚       β”œβ”€β”€ application.yml
β”‚   β”‚       └── data.sql
β”‚   └── test/
β”‚       └── java/com/example/springbootapi/
β”‚           └── users/
β”‚               β”œβ”€β”€ UserServiceTest.java
β”‚               └── UserControllerTest.java
└── pom.xml

πŸ“‹ Prerequisites

Before you begin, ensure you have the following installed:

  • Java 17 or higher
  • Maven 3.6+ or higher
  • IDE (IntelliJ IDEA, Eclipse, VS Code, or similar)

πŸš€ Getting Started

1. Clone the Repository

git clone <repository-url>
cd java-spring-boot-api

2. Build the Project

mvn clean install

3. Run the Application

mvn spring-boot:run

Or run the JAR file directly:

java -jar target/spring-boot-api-1.0.0.jar

4. Access the Application

The application will start on port 8080. You can access:

  • API Base URL: http://localhost:8080/api
  • Swagger UI: http://localhost:8080/swagger-ui.html
  • OpenAPI JSON: http://localhost:8080/v3/api-docs
  • H2 Console: http://localhost:8080/h2-console
    • JDBC URL: jdbc:h2:mem:testdb
    • Username: sa
    • Password: password

πŸ“š API Documentation

Swagger UI

Access the interactive API documentation at:

http://localhost:8080/swagger-ui.html

OpenAPI Specification

Download the OpenAPI specification in JSON format:

http://localhost:8080/v3/api-docs

You can import this specification into Swagger Editor (https://editor.swagger.io/) for editing and validation.

πŸ”Œ Available Services

The API includes the following 10 RESTful services:

1. Users (/api/users)

  • Manage user accounts
  • Fields: username, email, fullName, phoneNumber, active

2. Products (/api/products)

  • Manage product catalog
  • Fields: name, description, price, stockQuantity, sku, available

3. Orders (/api/orders)

  • Manage customer orders
  • Fields: orderNumber, customerId, totalAmount, status, orderDate, notes

4. Customers (/api/customers)

  • Manage customer information
  • Fields: firstName, lastName, email, phoneNumber, address, city, country

5. Invoices (/api/invoices)

  • Manage invoicing
  • Fields: invoiceNumber, customerId, orderId, amount, tax, totalAmount, issueDate, dueDate, status

6. Payments (/api/payments)

  • Manage payment transactions
  • Fields: transactionId, orderId, invoiceId, amount, paymentMethod, status, paymentDate

7. Categories (/api/categories)

  • Manage product categories
  • Fields: name, description, slug, parentCategoryId, active, displayOrder

8. Reviews (/api/reviews)

  • Manage product reviews
  • Fields: productId, userId, rating, title, comment, reviewDate, verified, helpfulCount

9. Suppliers (/api/suppliers)

  • Manage supplier information
  • Fields: companyName, contactName, email, phoneNumber, address, city, country, postalCode, active

10. Inventory (/api/inventory)

  • Manage inventory items
  • Fields: productId, warehouseLocation, quantity, reservedQuantity, reorderLevel, lastUpdated, notes, active

11. Health Check (/api/health)

  • Check application health status

🎯 API Endpoints

Each service supports the following operations:

Method Endpoint Description
GET /api/{resource} Get all items
GET /api/{resource}/{id} Get item by ID
POST /api/{resource} Create new item
PUT /api/{resource}/{id} Update item
DELETE /api/{resource}/{id} Delete item

Example Request (Create User)

curl -X POST http://localhost:8080/api/users \
  -H "Content-Type: application/json" \
  -d '{
    "username": "john_doe",
    "email": "john@example.com",
    "fullName": "John Doe",
    "phoneNumber": "+1234567890",
    "active": true
  }'

Example Response

{
  "status": "success",
  "message": "User created successfully",
  "data": {
    "id": 1,
    "username": "john_doe",
    "email": "john@example.com",
    "fullName": "John Doe",
    "phoneNumber": "+1234567890",
    "active": true
  },
  "timestamp": "2024-10-12T10:30:00"
}

πŸ§ͺ Testing

Run All Tests

mvn test

Run Specific Test Class

mvn test -Dtest=UserServiceTest

Test Coverage

The project includes unit tests for:

  • UserService - Service layer logic
  • UserController - REST endpoint behavior

You can extend these tests to other services following the same pattern.

πŸ’Ύ Database

H2 Console

Access the H2 database console at:

http://localhost:8080/h2-console

Connection Details:

  • Driver Class: org.h2.Driver
  • JDBC URL: jdbc:h2:mem:testdb
  • Username: sa
  • Password: password

Sample Data

The application automatically loads sample data on startup from data.sql. This includes:

  • 3 Users
  • 5 Products
  • 3 Customers
  • 3 Orders
  • 3 Invoices
  • 3 Payments
  • 4 Categories
  • 3 Reviews
  • 3 Suppliers
  • 5 Inventory Items

βš™οΈ Configuration

Application Properties

The main configuration is in src/main/resources/application.yml:

server:
  port: 8080

spring:
  datasource:
    url: jdbc:h2:mem:testdb
    username: sa
    password: password
  
  jpa:
    hibernate:
      ddl-auto: create-drop
    show-sql: true

springdoc:
  swagger-ui:
    path: /swagger-ui.html

Modify Port

To change the server port, update application.yml:

server:
  port: 9090

Or pass it as a command-line argument:

mvn spring-boot:run -Dspring-boot.run.arguments=--server.port=9090

πŸ“ Error Handling

The API uses standardized error responses:

Validation Error (400)

{
  "status": "error",
  "message": "Validation failed",
  "path": "/api/users",
  "timestamp": "2024-10-12T10:30:00",
  "errors": {
    "email": "Email should be valid",
    "username": "Username must be between 3 and 50 characters"
  }
}

Resource Not Found (404)

{
  "status": "error",
  "message": "User not found with id: 999",
  "path": "/api/users/999",
  "timestamp": "2024-10-12T10:30:00"
}

Internal Server Error (500)

{
  "status": "error",
  "message": "An internal server error occurred",
  "path": "/api/users",
  "timestamp": "2024-10-12T10:30:00"
}

πŸ“¦ Build for Production

Create JAR File

mvn clean package

The JAR file will be created in target/spring-boot-api-1.0.0.jar

Run Production Build

java -jar target/spring-boot-api-1.0.0.jar

πŸ” Logging

The application uses SLF4J with Logback for logging. Log levels can be configured in application.yml:

logging:
  level:
    root: INFO
    com.example.springbootapi: DEBUG

πŸŽ“ Best Practices Demonstrated

  1. Package-by-Feature - Better modularity and cohesion
  2. Separation of Concerns - Controller, Service, Repository layers
  3. Validation - Input validation using Bean Validation
  4. Exception Handling - Global exception handler for consistent error responses
  5. API Documentation - Comprehensive OpenAPI/Swagger documentation
  6. Testing - Unit tests for critical components
  7. Logging - Structured logging throughout the application
  8. Response Wrapping - Consistent response format across all endpoints

πŸ“„ License

This project is licensed under the Apache License 2.0.

πŸ‘₯ Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

πŸ“§ Contact

For questions or support, please contact: stefanramac@gmail.com


Happy Coding! πŸš€

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages