Skip to content

A core Spring Boot REST API implementation with clean architecture, demonstrating fundamental web service patterns and best practices for enterprise development.

License

Notifications You must be signed in to change notification settings

adeeshperera/springboot-core-rest-api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

11 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Books API - Spring Boot REST Application

Java Spring Boot PostgreSQL Maven

A comprehensive RESTful API for managing books and authors built with Spring Boot 3.1, demonstrating modern Spring Framework patterns, JPA/Hibernate ORM, and PostgreSQL integration.

πŸ—οΈ Architecture Overview

This application follows a layered architecture pattern with clear separation of concerns:

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                          REST Controllers                       β”‚
β”‚                    (AuthorController, BookController)           β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚                          Service Layer                          β”‚
β”‚                  (AuthorService, BookService)                   β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚                         Repository Layer                        β”‚
β”‚                (Spring Data JPA Repositories)                   β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚                         Domain Layer                            β”‚
β”‚                 (Entities, DTOs, Mappers)                       β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚                      Data Persistence                           β”‚
β”‚                    (PostgreSQL Database)                        β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

πŸ”§ Technical Stack

Core Technologies

  • Java 17 - Latest LTS version with modern language features
  • Spring Boot 3.1.0 - Enterprise-grade application framework
  • Spring Data JPA - Repository abstraction over JPA/Hibernate
  • Hibernate - ORM framework for database operations
  • PostgreSQL - Production-grade relational database
  • Maven 3.9.2 - Dependency management and build automation

Development & Testing

  • Lombok - Annotation processor for reducing boilerplate code
  • ModelMapper 3.0.0 - Object mapping framework
  • H2 Database - In-memory database for testing
  • Spring Boot Test - Comprehensive testing framework
  • Docker Compose - Container orchestration for development

πŸ“Š Data Model

Entity Relationship Diagram

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”         β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   AuthorEntity  β”‚         β”‚   BookEntity    β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€         β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ id (PK)         │◄──────┐ β”‚ isbn (PK)       β”‚
β”‚ name            β”‚       β”‚ β”‚ title           β”‚
β”‚ age             β”‚       └─│ authorEntity    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜         β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Database Schema

Authors Table

CREATE TABLE authors (
    id BIGSERIAL PRIMARY KEY,
    name VARCHAR(255),
    age INTEGER
);

Books Table

CREATE TABLE books (
    isbn VARCHAR(255) PRIMARY KEY,
    title VARCHAR(255),
    author_id BIGINT REFERENCES authors(id)
);

πŸ› οΈ Project Structure

src/
β”œβ”€β”€ main/
β”‚   β”œβ”€β”€ java/com/testpjt/database/
β”‚   β”‚   β”œβ”€β”€ BooksApiApplication.java           # Main application class
β”‚   β”‚   β”œβ”€β”€ config/
β”‚   β”‚   β”‚   └── MapperConfig.java              # ModelMapper configuration
β”‚   β”‚   β”œβ”€β”€ controllers/                       # REST endpoints
β”‚   β”‚   β”‚   β”œβ”€β”€ AuthorController.java
β”‚   β”‚   β”‚   └── BookController.java
β”‚   β”‚   β”œβ”€β”€ domain/
β”‚   β”‚   β”‚   β”œβ”€β”€ dto/                           # Data Transfer Objects
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ AuthorDto.java
β”‚   β”‚   β”‚   β”‚   └── BookDto.java
β”‚   β”‚   β”‚   └── entities/                      # JPA entities
β”‚   β”‚   β”‚       β”œβ”€β”€ AuthorEntity.java
β”‚   β”‚   β”‚       └── BookEntity.java
β”‚   β”‚   β”œβ”€β”€ mappers/                           # Object mapping
β”‚   β”‚   β”‚   β”œβ”€β”€ Mapper.java
β”‚   β”‚   β”‚   └── impl/
β”‚   β”‚   β”‚       β”œβ”€β”€ AuthorMapperImpl.java
β”‚   β”‚   β”‚       └── BookMapperImpl.java
β”‚   β”‚   β”œβ”€β”€ repositories/                      # Data access layer
β”‚   β”‚   β”‚   β”œβ”€β”€ AuthorRepository.java
β”‚   β”‚   β”‚   └── BookRepository.java
β”‚   β”‚   └── services/                          # Business logic
β”‚   β”‚       β”œβ”€β”€ AuthorService.java
β”‚   β”‚       β”œβ”€β”€ BookService.java
β”‚   β”‚       └── impl/
β”‚   β”‚           β”œβ”€β”€ AuthorServiceImpl.java
β”‚   β”‚           └── BookServiceImpl.java
β”‚   └── resources/
β”‚       β”œβ”€β”€ application.properties             # Production configuration
β”‚       └── banner.txt                         # Custom application banner
└── test/
    β”œβ”€β”€ java/com/testpjt/database/
    β”‚   β”œβ”€β”€ BooksApiApplicationTests.java
    β”‚   β”œβ”€β”€ TestDataUtil.java
    β”‚   β”œβ”€β”€ controllers/                       # Integration tests
    β”‚   β”‚   β”œβ”€β”€ AuthorControllerIntegrationTests.java
    β”‚   β”‚   └── BooksControllerIntegrationTests.java
    β”‚   └── repositories/                      # Repository tests
    β”‚       β”œβ”€β”€ AuthorEntityRepositoryIntegrationTests.java
    β”‚       └── BookEntityRepositoryIntegrationTests.java
    └── resources/
        └── application.properties             # Test configuration (H2)

πŸš€ Getting Started

Prerequisites

  • Java 17 or higher
  • Docker & Docker Compose (for PostgreSQL)
  • Maven 3.6+ (or use included wrapper)

Environment Setup

  1. Clone the repository

    git clone <repository-url>
    cd testpjt
  2. Start PostgreSQL with Docker Compose

    docker-compose up -d

    This starts PostgreSQL on port 5433 with credentials:

    • Host: localhost:5433
    • Database: postgres
    • Username: postgres
    • Password: changemeinprod!
  3. Build the application

    ./mvnw clean compile
  4. Run tests

    ./mvnw test
  5. Start the application

    ./mvnw spring-boot:run

The application will start on http://localhost:8080

πŸ“‹ API Documentation

Author Management

Create Author

POST /authors
Content-Type: application/json

{
    "name": "J.K. Rowling",
    "age": 58
}

Get All Authors

GET /authors

Get Author by ID

GET /authors/{id}

Update Author (Full)

PUT /authors/{id}
Content-Type: application/json

{
    "name": "Joanne Rowling",
    "age": 59
}

Update Author (Partial)

PATCH /authors/{id}
Content-Type: application/json

{
    "age": 59
}

Delete Author

DELETE /authors/{id}

Book Management

Create/Update Book

PUT /books/{isbn}
Content-Type: application/json

{
    "title": "Harry Potter and the Philosopher's Stone",
    "author": {
        "id": 1,
        "name": "J.K. Rowling",
        "age": 58
    }
}

Get All Books

GET /books

Get Book by ISBN

GET /books/{isbn}

Update Book (Partial)

PATCH /books/{isbn}
Content-Type: application/json

{
    "title": "Harry Potter and the Sorcerer's Stone"
}

Delete Book

DELETE /books/{isbn}

πŸ” Key Technical Features

Spring Boot Configuration

  • Auto-configuration for JPA, web, and data source
  • Component scanning with @SpringBootApplication
  • Profile-based configuration (development vs test)

Data Persistence

  • JPA/Hibernate for ORM with annotation-based configuration
  • PostgreSQL for production with custom port configuration
  • H2 in-memory database for testing
  • Automatic DDL generation with spring.jpa.hibernate.ddl-auto=update

Repository Pattern

  • Spring Data JPA repositories extending CrudRepository
  • Custom query methods with method naming conventions
  • JPQL queries with @Query annotation
  • Pagination support with PagingAndSortingRepository

Service Layer Design

  • Interface-based services for loose coupling
  • Dependency injection with constructor injection
  • Business logic encapsulation separate from controllers
  • Exception handling with runtime exceptions

REST Controller Design

  • RESTful endpoints following HTTP semantics
  • Proper HTTP status codes (200, 201, 404, etc.)
  • Request/Response mapping with @RequestBody and @ResponseEntity
  • Path variables with @PathVariable

Object Mapping

  • ModelMapper for entity-DTO conversion
  • Custom mapper interfaces for type safety
  • Loose matching strategy for flexible field mapping
  • Bidirectional mapping (entity ↔ DTO)

Testing Strategy

  • Integration tests with @SpringBootTest
  • Repository tests with @DataJpaTest
  • Test data utilities for consistent test setup
  • H2 database for isolated test execution

βš™οΈ Configuration

Application Properties (Production)

# Database Configuration
spring.datasource.url=jdbc:postgresql://localhost:5433/postgres
spring.datasource.username=postgres
spring.datasource.password=changemeinprod!
spring.datasource.driver-class-name=org.postgresql.Driver

# JPA/Hibernate Configuration
spring.jpa.hibernate.ddl-auto=update

Test Configuration

# H2 In-Memory Database
spring.datasource.url=jdbc:h2:mem:testdb;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DEFAULT_NULL_ORDERING=HIGH
spring.datasource.username=sa
spring.datasource.password=password
spring.datasource.driver-class-name=org.h2.Driver

🐳 Docker Integration

The project includes Docker Compose configuration for easy PostgreSQL setup:

version: "3.1"
services:
  db:
    image: postgres
    ports:
      - "5433:5432"
    restart: always
    environment:
      POSTGRES_PASSWORD: changemeinprod!

πŸ§ͺ Testing

Running Tests

# Run all tests
./mvnw test

# Run specific test class
./mvnw test -Dtest=AuthorControllerIntegrationTests

# Run with coverage
./mvnw test jacoco:report

Test Categories

  • Unit Tests - Service layer logic
  • Integration Tests - Controller endpoints with database
  • Repository Tests - JPA repository functionality

πŸ“ˆ Performance Considerations

Database Optimization

  • Entity relationships properly mapped with JPA annotations
  • Lazy loading for associated entities
  • Query optimization with custom JPQL queries
  • Connection pooling handled by Spring Boot defaults

Application Performance

  • Stateless services for horizontal scalability
  • DTO pattern to reduce data transfer overhead
  • Efficient object mapping with ModelMapper
  • Proper HTTP caching headers in responses

πŸ”’ Security Considerations

Current State

  • Basic Spring Security configuration (implicit)
  • Database credentials in configuration files
  • No authentication/authorization implemented

Production Recommendations

  • Implement Spring Security for authentication
  • Use environment variables for sensitive configuration
  • Add input validation and sanitization
  • Implement rate limiting and CORS policies

πŸš€ Deployment

Live Deployment

🌐 The API is currently deployed and accessible at:

https://container-service-1.rgaj2b5egkhqr.ap-southeast-1.cs.amazonlightsail.com/

Base URL for API endpoints:

  • Authors: https://container-service-1.rgaj2b5egkhqr.ap-southeast-1.cs.amazonlightsail.com/authors
  • Books: https://container-service-1.rgaj2b5egkhqr.ap-southeast-1.cs.amazonlightsail.com/books

Amazon Lightsail Container Service Deployment

This application is deployed on Amazon Lightsail Container Service in the ap-southeast-1 region, providing a scalable and cost-effective cloud hosting solution.

Lightsail Deployment Features:

  • Auto-scaling: Container service automatically scales based on demand
  • Load balancing: Built-in load balancer for high availability
  • HTTPS: Automatic SSL/TLS certificate management
  • Regional deployment: Asia Pacific (Singapore) region for optimal performance
  • Container orchestration: Managed container environment

Deployment Architecture:

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                    Amazon Lightsail                            β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”‚
β”‚  β”‚           Container Service                             β”‚    β”‚
β”‚  β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”            β”‚    β”‚
β”‚  β”‚  β”‚  Spring Boot    β”‚    β”‚   PostgreSQL    β”‚            β”‚    β”‚
β”‚  β”‚  β”‚  Application    │◄──►│   Database      β”‚            β”‚    β”‚
β”‚  β”‚  β”‚  (JAR)          β”‚    β”‚   Container     β”‚            β”‚    β”‚
β”‚  β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜            β”‚    β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β”‚
β”‚                           β–²                                     β”‚
β”‚                           β”‚                                     β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”‚
β”‚  β”‚              Load Balancer + HTTPS                     β”‚    β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                              β–²
                              β”‚
                   HTTPS Traffic from Internet

Building for Production

1. Create Executable JAR

# Clean and build the application
./mvnw clean package

# The JAR file will be created at:
# target/database-0.0.1-SNAPSHOT.jar

2. Local JAR Execution

# Run the JAR locally
java -jar target/database-0.0.1-SNAPSHOT.jar

# Run with custom port
java -jar -Dserver.port=8080 target/database-0.0.1-SNAPSHOT.jar

# Run with production profile
java -jar -Dspring.profiles.active=prod target/database-0.0.1-SNAPSHOT.jar

3. JAR File Details

Property Value
File Name database-0.0.1-SNAPSHOT.jar
Location target/database-0.0.1-SNAPSHOT.jar
Type Spring Boot Fat JAR (executable)
Size ~50-70 MB (includes all dependencies)
Java Version Requires Java 17+

Container Deployment

Dockerfile Example

FROM openjdk:17-jre-slim

# Set working directory
WORKDIR /app

# Copy the JAR file
COPY target/database-0.0.1-SNAPSHOT.jar app.jar

# Expose port
EXPOSE 8080

# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD curl -f http://localhost:8080/actuator/health || exit 1

# Run the application
ENTRYPOINT ["java", "-jar", "app.jar"]

Build and Push to Lightsail

# Build Docker image
docker build -t books-api .

# Tag for Lightsail (replace with your service name)
docker tag books-api:latest books-api:latest

# Push to Lightsail Container Service
aws lightsail push-container-image \
  --service-name container-service-1 \
  --label books-api \
  --image books-api:latest

Environment Configuration

Production Environment Variables

# Database Configuration
export SPRING_DATASOURCE_URL=jdbc:postgresql://prod-db:5432/books_db
export SPRING_DATASOURCE_USERNAME=prod_user
export SPRING_DATASOURCE_PASSWORD=secure_password

# Application Configuration
export SPRING_PROFILES_ACTIVE=prod
export SERVER_PORT=8080

# Lightsail specific
export JAVA_OPTS="-Xmx512m -Xms256m"

Lightsail Container Configuration

{
	"containers": {
		"books-api": {
			"image": ":books-api.latest",
			"ports": {
				"8080": "HTTP"
			},
			"environment": {
				"SPRING_DATASOURCE_URL": "jdbc:postgresql://db:5432/books_db",
				"SPRING_DATASOURCE_USERNAME": "postgres",
				"SPRING_DATASOURCE_PASSWORD": "your_password",
				"SPRING_PROFILES_ACTIVE": "prod"
			}
		}
	},
	"publicEndpoint": {
		"containerName": "books-api",
		"containerPort": 8080,
		"healthCheck": {
			"healthyThreshold": 2,
			"unhealthyThreshold": 2,
			"timeoutSeconds": 5,
			"intervalSeconds": 30,
			"path": "/actuator/health"
		}
	}
}

Deployment Verification

After deployment, verify the API is working:

# Check health endpoint
curl https://container-service-1.rgaj2b5egkhqr.ap-southeast-1.cs.amazonlightsail.com/actuator/health

# Test authors endpoint
curl https://container-service-1.rgaj2b5egkhqr.ap-southeast-1.cs.amazonlightsail.com/authors

# Test books endpoint
curl https://container-service-1.rgaj2b5egkhqr.ap-southeast-1.cs.amazonlightsail.com/books

About

A core Spring Boot REST API implementation with clean architecture, demonstrating fundamental web service patterns and best practices for enterprise development.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages