Music Library API

Java Bootcamp Project - RESTful API for Music Album Management

Spring Boot 3.5.7 Java 17 MySQL JPA/Hibernate RESTful

🎡 Launch Application

Loads on-demand to minimize costs. Takes ~5-7 minutes to load database and Java application.

Enter your email address to be notified when ready (optional).


πŸ“‹ Project Overview

The Music Library API is a comprehensive backend application developed as a final bootcamp project, demonstrating professional-grade software engineering practices. This RESTful API provides complete CRUD operations for managing a music catalog including artists, albums, and genres with sophisticated relationship management. Album track integration can be added as the next feature.

Built following best practices for layered architecture, this project showcases expertise in Spring Boot ecosystem, database design, API development, testing strategies, and cloud deployment practices. The application features a comprehensive music library with 50 artists and over 100 albums, now deployed on AWS cloud infrastructure with production-grade reliability.

Live AWS Production API: http://project.jcarl.net/api
Deployment Status: Validated with 121 requests, 484 tests, 100% pass rate

🌟 Key Features

πŸ› οΈ Robust REST Architecture

Full Create, Read, Update, Delete functionality adhering to REST principles with proper HTTP status codes and standardized response envelopes.

πŸ”— Complex Relationships

Managed One-to-Many (Artist-Album) and Many-to-Many (Album-Genre) JPA relationships with bidirectional synchronization and orphan removal.

πŸ“„ Pagination & Sorting

Optimized data retrieval using Spring Data Pageable to handle large datasets efficiently without performance bottlenecks.

πŸ” Dynamic Search Specifications

Advanced filtering system using JPA Specifications to query by title, release date ranges, and genre associations dynamically.

βœ… Bean Validation Security

Strict data integrity enforcement using JSR-380 (Bean Validation) custom constraints at the API boundary to prevent malformed data.

πŸ›‘οΈ Global Exception Handling

Centralized @RestControllerAdvice mechanism that transforms Java exceptions into user-friendly, consistent JSON error responses.

πŸ“– Interactive API Docs

Self-documenting API using Swagger UI (OpenAPI 3.0), allowing developers to visualize and test endpoints directly in the browser.

πŸ”¬ Test-Driven Reliability

Comprehensive suite including Unit tests with Mockito, Integration tests using Testcontainers to real database interactions, and Maven Surefire test reporting.

🎡 Automated Media Enrichment

Custom integration with the iTunes Search API to automatically discover, fetch, and resize high-resolution album artwork.

πŸ› οΈ Technology Stack

Backend Framework

  • Spring Boot 3.5.7
  • Spring Web MVC
  • Spring Data JPA
  • Spring Validation

Database & ORM

  • MySQL (Production)
  • H2 Database (Testing)
  • Hibernate ORM
  • Hibernate DDL Auto-Update

Development Tools

  • Java 17
  • Maven Build Tool
  • Lombok
  • Jackson (JSON with Java 8 date/time)

API & Documentation

  • RESTful Architecture
  • SpringDoc OpenAPI 3
  • Swagger UI
  • JSON Response Format

Testing

  • JUnit 5
  • Mockito (Unit testing framework)
  • Testcontainers (Docker-based integration testing)
  • Maven Surefire (Test execution and reporting)

Cloud Deployment (AWS)

  • AWS RDS MySQL (Production Database)
  • AWS ECR (Container Registry)
  • AWS ECS Fargate (Serverless Containers)
  • Namesilo DNS API (Automated DNS Management)
  • AWS CloudShell (Docker Build Environment)
  • AWS CodeBuild (CI/CD Pipeline)
  • Docker Containerization

πŸ—οΈ Architecture Overview

The application follows a layered architecture pattern with clear separation of concerns, promoting maintainability, testability, and scalability. Each layer has distinct responsibilities and communicates through well-defined interfaces.

🚦 Controller Layer (Presentation)

Handles HTTP requests and responses, maps URLs to service methods, validates input, and formats output. Uses Spring MVC annotations for RESTful endpoint definition.

MusicLibraryController
@RestController

Main REST controller exposing all API endpoints for Artists, Albums, and Genres. Implements comprehensive OpenAPI annotations for documentation. Handles pagination with @ParameterObject Pageable.

SwaggerRedirectController
@Controller

Redirects root URL to Swagger UI for convenient API documentation access.

βš™οΈ Service Layer (Business Logic)

Contains business logic, transaction management, and orchestrates operations between controllers and repositories. Annotated with @Service and @Transactional for proper transaction boundaries.

ArtistService
@Service @Transactional

Manages artist CRUD operations with pagination support. Throws ResourceNotFoundException for missing entities. Uses constructor injection via @RequiredArgsConstructor.

AlbumService
@Service @Transactional

Handles album operations including complex many-to-many genre relationships. Implements advanced search using JPA Specifications. Manages bidirectional relationship synchronization with explicit Hibernate initialization.

GenreService
@Service @Transactional

Manages genre entities and their album associations. Provides methods for adding/removing albums from genres while maintaining referential integrity.

πŸ—ƒοΈ Repository Layer (Data Access)

Interfaces extending Spring Data JPA repositories for database operations. Provides automatic CRUD implementation and custom query methods using Spring Data naming conventions.

ArtistRepository
extends JpaRepository<Artist, Long>

Data access interface for Artist entities. Inherits standard CRUD and pagination methods from JpaRepository.

AlbumRepository
extends JpaRepository, JpaSpecificationExecutor

Repository with custom query methods: findByArtist_ArtistId() and findByGenres_GenreId(). Implements JpaSpecificationExecutor for dynamic query building.

GenreRepository
extends JpaRepository<Genre, Long>

Simple repository interface for Genre entity persistence operations.

πŸ“„ Entity Layer (Domain Model)

JPA entities representing database tables with proper relationships, validation constraints, and lifecycle callbacks. Uses Lombok for boilerplate reduction and Jackson annotations for JSON serialization control.

Artist
@Entity @Table(name="artist")

Fields: artistId (PK), name (required, max 255), description (TEXT), createdAt, updatedAt
Relationships: One-to-Many with Album (cascade ALL, orphan removal)
Features: @PrePersist/@PreUpdate for timestamps, @JsonIgnore on albums collection to prevent cycles

Album
@Entity @Table(name="album")

Fields: albumId (PK), title (required), releaseDate, coverImageUrl, trackCount, catalogNumber (unique), createdAt, updatedAt
Relationships: Many-to-One with Artist (required), Many-to-Many with Genre via join table
Features: Transient getReleaseYear() method, custom setGenres() for bidirectional sync, LAZY fetching

Genre
@Entity @Table(name="genre")

Fields: genreId (PK), name (required, max 100), description (TEXT), createdAt, updatedAt
Relationships: Many-to-Many with Album (inverse side, EAGER fetch for testing)
Features: @JsonIgnore on albums to break serialization cycles, @EqualsAndHashCode.Exclude on collections

πŸ” Specification Layer (Dynamic Queries)

Implements the Specification pattern for building dynamic, type-safe queries with JPA Criteria API.

AlbumSpecs
Specification<Album>

Provides static factory methods for album filtering:
β€’ titleContains(String) - Case-insensitive title search
β€’ releasedBetween(Integer, Integer) - Date range filtering
β€’ hasGenre(Long) - Filter by genre association with JOIN

🚨 Exception Handling Layer

Centralized exception handling using Spring's @RestControllerAdvice for consistent error responses across the API.

GlobalExceptionHandler
@RestControllerAdvice

Handles multiple exception types with specific handlers:
β€’ MethodArgumentNotValidException β†’ 400 (validation errors)
β€’ ConstraintViolationException β†’ 400 (constraint violations)
β€’ ResourceNotFoundException β†’ 404 (entity not found)
β€’ MethodArgumentTypeMismatchException β†’ 400 (type errors)
β€’ HttpMessageNotReadableException β†’ 400 (malformed JSON)
β€’ Exception β†’ 500 (unexpected errors with logging)

ResourceNotFoundException
extends RuntimeException

Custom exception thrown when requested entities don't exist. Automatically converted to 404 responses by GlobalExceptionHandler.

ApiError
@Builder

Uniform error response DTO containing: timestamp, status code, error type, message, request path, and optional validation error list. Provides consistent error format across all endpoints.

πŸ“‘ API Endpoints

All endpoints are prefixed with /api and return JSON responses.

🎀 Artist Endpoints

POST /api/artists - Create a new artist
GET /api/artists?page=0&size=20&sort=name,asc - Get paginated artists
GET /api/artists/{id} - Get artist by ID
PUT /api/artists/{id} - Update artist
DELETE /api/artists/{id} - Delete artist
GET /api/artists/{artistId}/albums - Get all albums by artist

πŸ’Ώ Album Endpoints

POST /api/albums - Create a new album
GET /api/albums?page=0&size=20 - Get paginated albums
GET /api/albums/{id} - Get album by ID
PUT /api/albums/{id} - Update album
DELETE /api/albums/{id} - Delete album

🎸 Genre Endpoints

POST /api/genres - Create a new genre
GET /api/genres?page=0&size=20 - Get paginated genres
GET /api/genres/{id} - Get genre by ID
PUT /api/genres/{id} - Update genre
DELETE /api/genres/{id} - Delete genre
GET /api/genres/{genreId}/albums - Get all albums by genre

πŸ’‘ Technical Highlights

πŸ” Data Validation

Comprehensive input validation using Bean Validation (JSR-380) annotations:

  • πŸ›‘οΈ @NotBlank, @Size for string fields
  • πŸ›‘οΈ @NotNull for required relationships
  • πŸ›‘οΈ @PositiveOrZero for numeric constraints
  • πŸ›‘οΈ Custom validation messages for user-friendly errors

πŸ”„ Bidirectional Relationships

Properly managed JPA relationships with:

  • πŸ”— Cascade operations for dependent entities
  • πŸ”— Orphan removal for data integrity
  • πŸ”— Explicit Hibernate.initialize() to prevent LazyInitializationException
  • πŸ”— @JsonIgnore to break serialization cycles
  • πŸ”— Custom setters for bidirectional synchronization

πŸ“Š Advanced Querying

Flexible data retrieval with:

  • πŸ” Spring Data JPA derived query methods
  • πŸ” JPA Specifications for dynamic filtering
  • πŸ” Pagination and sorting support
  • πŸ” Property path navigation (e.g., findByArtist_ArtistId)

βœ… Testing Strategy

Multi-layered testing approach:

  • βœ”οΈ Unit tests with Mockito for service layer isolation
  • βœ”οΈ Integration tests with @SpringBootTest
  • βœ”οΈ Testcontainers for real MySQL database testing
  • βœ”οΈ Maven Surefire - Test execution framework that generates detailed test reports
  • βœ”οΈ Separate test profile with H2 in-memory database

πŸ—„οΈ Database Management

Professional database practices:

  • βš™οΈ Hibernate DDL auto-update for automatic schema management
  • βš™οΈ Separate profiles for dev/test/production
  • βš™οΈ Proper indexing on foreign keys
  • βš™οΈ Timestamp tracking with @PrePersist/@PreUpdate

πŸ“– API Documentation

Comprehensive OpenAPI 3.0 documentation:

  • πŸ“š @Operation annotations with descriptions
  • πŸ“š @ApiResponses for all status codes
  • πŸ“š Request/response examples
  • πŸ“š Interactive Swagger UI for testing

☁️ AWS Cloud Deployment

The Music Library API is deployed on Amazon Web Services (AWS) using modern cloud-native technologies and best practices for production-grade applications. The deployment leverages containerization and serverless compute for scalability, reliability, and cost-effectiveness.

πŸ—οΈ AWS Architecture

πŸ—„οΈ AWS RDS MySQL

  • Managed relational database service
  • Automatic backups and point-in-time recovery
  • Multi-AZ deployment for high availability
  • Automated patching and maintenance

🐳 Docker Containerization

  • Application packaged as Docker container
  • Consistent environment across dev/prod
  • Isolated dependencies and runtime
  • Efficient resource utilization

πŸ“¦ AWS ECR (Elastic Container Registry)

  • Private Docker image repository
  • Secure image storage and versioning
  • Integration with ECS for deployment
  • Automated vulnerability scanning

πŸš€ AWS ECS Fargate

  • Serverless container orchestration
  • No server management required
  • Ephemeral infrastructure design
  • Pay-per-use pricing model

πŸ”§ AWS CodeBuild

  • S3-Triggered Pipeline: Automated deployments upon source artifact upload
  • Multi-Stage Builds: Optimized Docker images for minimal runtime footprint
  • Dependency Management: Integrated with AWS Public ECR mirrors
  • Artifact Handling: Automated pushing to Private ECR repository

πŸ›‘οΈ Security & Access Control

  • AWS IAM: Role-based access control (RBAC) with Principle of Least Privilege
  • VPC Security Groups: Granular network firewalling for port isolation
  • Container Security: Hardened Alpine Linux runtime (minimal attack surface)
  • Secret Management: Secure environment variable injection

πŸ› οΈ DevOps & Management

  • AWS CloudShell: Browser-based Linux environment for script dev & debugging
  • AWS CLI: Command-line interaction with ECR and ECS
  • AWS S3: Artifact storage and CodeBuild pipeline trigger
  • Bash Scripting: Custom automation for environment configuration

⌨ Operations & Observability

  • AWS CloudWatch: Real-time log aggregation and deployment troubleshooting
  • AWS CloudShell: Cloud-native Linux environment for script development
  • AWS S3: Secure artifact storage and build pipeline integration
  • Bash Scripting: Custom automation for environment configuration

πŸ“Š Current Deployment Status

☁️ Production Environment

Domain: project.jcarl.net
Port: 80 (HTTP)
DNS Provider: Namesilo with automated API-based updates
Container Platform: AWS ECS Fargate (Serverless)
Task Revision: Latest (auto-deployed via ECS)
Build Environment: AWS CloudShell + CodeBuild

βœ… Deployment Validation

The AWS deployment has been thoroughly validated using Postman collection runner with comprehensive test coverage:

πŸ“ˆ Project Metrics

πŸ”¨ Build Iterations

33+ Docker builds executed through AWS CloudShell and CodeBuild, demonstrating iterative development and continuous improvement of the containerized application.

πŸ—οΈ Infrastructure Revisions

11+ ECS task definition updates deployed, reflecting ongoing optimization of container configurations, resource allocation, and environment variables.

🌐 DNS Automation

Custom DNS update script integrated with Namesilo API to automatically update A records when ECS assigns new public IPs, ensuring zero-downtime availability.

🌐 Other Deployment Options

πŸš‚ Railway (Alternative Cloud Platform - Not Currently Used)

Features: Simple deployment, automatic HTTPS, built-in database
Use Case: Evaluated as an alternative cloud deployment option
Note: AWS ECS Fargate was selected for production deployment

πŸ–₯️ ngrok (Previous Local Development Configuration)

Features: Secure tunneling, temporary public URLs, webhook testing
Use Case: Previously used for local development, testing, and demonstration purposes
Note: This was a temporary development configuration and is no longer active

πŸ›€οΈ Deployment Journey

This project evolved through several deployment iterations, overcoming real-world cloud infrastructure challenges and implementing production-grade solutions. Each challenge provided valuable learning experiences in DevOps and cloud architecture.

πŸ”₯ Challenges Overcome

πŸ› Duplicate DNS A Records Bug

Diagnosed and resolved DNS resolution failures caused by duplicate A records pointing to old and new IPs. Implemented proper DNS record cleanup logic in the automation script, ensuring single authoritative A record per deployment and preventing DNS propagation conflicts.

πŸ”„ ECS Circuit Breaker Rollbacks

Resolved automatic task rollbacks triggered by ECS Circuit Breaker due to health check failures. Debugged container startup issues, corrected environment variable configurations, and validated health check endpoints to achieve stable deployments without rollbacks.

πŸ’» Windows LTSB Docker Incompatibility

Overcame local Docker Desktop limitations on Windows LTSB by pivoting to AWS CloudShell as the primary build environment. Leveraged CloudShell's pre-configured Docker and AWS CLI to establish a reliable, cloud-based build pipeline independent of local system constraints.

πŸ” IAM Permission Complexity

Navigated AWS IAM role and policy configurations to establish secure, least-privilege access patterns. Configured ECS task execution roles, ECR permissions, RDS security groups, and VPC networking to ensure secure communication between services while maintaining production security standards.

🏁 Deployment Milestones

🌐 DNS Migration: Route 53 β†’ Namesilo

Migrated from AWS Route 53 to Namesilo DNS API for automated domain management. Implemented custom DNS update automation to dynamically update A records when ECS tasks receive new public IPs, ensuring continuous availability at project.jcarl.net without manual intervention.

🐳 AWS CloudShell Integration

Leveraged AWS CloudShell as a cloud-based Docker build environment, eliminating local dependency issues and providing consistent, reproducible builds. CloudShell's pre-configured AWS CLI and Docker support streamlined the container image creation and ECR push workflow.

πŸ“¦ ECS Fargate Deployment Automation

Configured AWS ECS Fargate for serverless container orchestration with automatic task deployment. Implemented task definitions with proper resource allocation, environment variable management, and health checks for production-grade reliability and zero-downtime deployments.

πŸ’‘ Key Learnings

Technical Insights Gained

  • πŸ“ DNS Management: Automated DNS updates require careful handling of record cleanup to prevent duplicate entries and resolution conflicts
  • πŸ“ Container Health Checks: ECS Circuit Breaker provides automatic rollback protection but requires properly configured health endpoints and startup grace periods
  • πŸ“ Cloud-Based Development: AWS CloudShell eliminates local environment dependencies and provides consistent build environments across team members
  • πŸ“ Iterative Deployment: Production deployments benefit from incremental changes, comprehensive logging, and systematic troubleshooting of infrastructure issues

πŸŽ“ Learning Outcomes

This project demonstrates experience with:

Backend Development

Spring Boot, Spring MVC, dependency injection, RESTful API design, HTTP protocol

Database Design

Relational modeling, JPA/Hibernate, entity relationships, query optimization, migrations

Software Architecture

Layered architecture, separation of concerns, SOLID principles, design patterns

Testing & Quality

Unit testing, integration testing, test-driven development, code coverage

DevOps & Cloud Deployment

AWS cloud services (RDS, ECR, ECS, CloudShell, CodeBuild), Docker containerization, CI/CD pipelines, DNS automation (Namesilo API), IAM security, infrastructure as code

Best Practices

Error handling, validation, logging, documentation, code organization

πŸš€ Getting Started

Prerequisites

Running Locally

git clone https://github.com/jc-gh25/MusicLibrary.git
cd music-library
mvn spring-boot:run

Access the API at http://localhost:8080/api and Swagger UI at http://localhost:8080/swagger-ui.html

For public access: Use the AWS production URL: http://project.jcarl.net/api

Running Tests

mvn test
mvn verify (runs all tests with detailed reporting)