Building a Modern REST API with Spring Boot: Best Practices and Implementation Guide

UI pattern collection

Example Mermaid Diagram

Example Table

FrameworkPopularityLearning Curve
ReactHighModerate
VueHighLow
SvelteGrowingLow

String code="secret";

Overview (H2)

JPA/Hibernate Learn to create a production-ready REST API using Spring Boot 3.x with essential features:


Prerequisites (H2)


Step 1: Project Setup (H2)

Initialize project via Spring Initializr with dependencies:

pom.xml essentials:

xml
1
<dependency>
2
<groupId>org.springframework.boot</groupId>
3
<artifactId>spring-boot-starter-data-jpa</artifactId>
4
</dependency>
5
<dependency>
6
<groupId>org.springdoc</groupId>
7
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
8
<version>2.1.0</version>
9
</dependency>

Step 2: Domain Model (H2)

Entity Class:

java
1
@Entity
2
@Getter
3
@Setter
4
@NoArgsConstructor
5
@AllArgsConstructor
6
@Builder
7
public class Product {
8
@Id
9
@GeneratedValue(strategy = GenerationType.IDENTITY)
10
private Long id;
11
12
@NotBlank(message = "Name is mandatory")
13
@Size(max = 100)
14
private String name;
15
16
@PositiveOrZero
17
private BigDecimal price;
18
19
@CreationTimestamp
20
private LocalDateTime createdAt;
21
}

Step 3: Repository Layer (H2)

JPA Repository Interface:

java
1
public interface ProductRepository extends JpaRepository<Product, Long> {
2
List<Product> findByNameContainingIgnoreCase(String name);
3
}

Step 4: Service Layer (H2)

Business Logic Implementation:

java
1
@Service
2
@RequiredArgsConstructor
3
public class ProductService {
4
5
private final ProductRepository productRepository;
6
7
public Product createProduct(Product product) {
8
return productRepository.save(product);
9
}
10
11
public Product getProductById(Long id) {
12
return productRepository.findById(id)
13
.orElseThrow(() -> new ResourceNotFoundException("Product not found"));
14
}
15
16
// Additional business methods
17
}

Step 5: REST Controller (H2)

API Endpoints:

java
1
@RestController
2
@RequestMapping("/api/v1/products")
3
@RequiredArgsConstructor
4
@Tag(name = "Product API", description = "Product management operations")
5
public class ProductController {
6
7
private final ProductService productService;
8
9
@PostMapping
10
@ResponseStatus(HttpStatus.CREATED)
11
public Product createProduct(@Valid @RequestBody Product product) {
12
return productService.createProduct(product);
13
}
14
15
@GetMapping("/{id}")
16
public ResponseEntity<Product> getProduct(@PathVariable Long id) {
17
return ResponseEntity.ok(productService.getProductById(id));
18
}
19
}

Step 6: Exception Handling (H2)

Global Exception Handler:

java
1
@RestControllerAdvice
2
public class GlobalExceptionHandler {
3
4
@ExceptionHandler(ResourceNotFoundException.class)
5
@ResponseStatus(HttpStatus.NOT_FOUND)
6
public ErrorResponse handleResourceNotFound(ResourceNotFoundException ex) {
7
return new ErrorResponse(
8
HttpStatus.NOT_FOUND.value(),
9
ex.getMessage(),
10
Instant.now()
11
);
12
}
13
14
// Handle validation errors
15
}

Step 7: Configuration (H2)

application.yml:

yaml
1
spring:
2
datasource:
3
url: jdbc:postgresql://localhost:5432/ecommerce
4
username: admin
5
password: securepass
6
jpa:
7
hibernate:
8
ddl-auto: validate
9
show-sql: true
10
11
openapi:
12
title: Product API
13
version: 1.0.0

Step 8: API Documentation (H2)

Access Swagger UI at http://localhost:8080/swagger-ui.html

Custom OpenAPI Configuration:

java
1
@Configuration
2
public class OpenApiConfig {
3
4
@Bean
5
public OpenAPI customOpenAPI() {
6
return new OpenAPI()
7
.info(new Info()
8
.title("E-Commerce API")
9
.version("1.0")
10
.description("API for product management"));
11
}
12
}

Step 9: Testing (H2)

Integration Test Example:

java
1
@SpringBootTest
2
@AutoConfigureMockMvc
3
class ProductControllerTest {
4
5
@Autowired
6
private MockMvc mockMvc;
7
8
@Test
9
void shouldCreateProduct() throws Exception {
10
mockMvc.perform(post("/api/v1/products")
11
.contentType(MediaType.APPLICATION_JSON)
12
.content("{\"name\":\"Laptop\",\"price\":999.99}"))
13
.andExpect(status().isCreated());
14
}
15
}

Best Practices (H2)

  1. Layered Architecture Maintain clear separation between controllers, services, and repositories

  2. Validation Use Hibernate Validator for input sanitization

  3. Security Implement JWT authentication with Spring Security

  4. Monitoring Add Actuator for health checks and metrics

  5. Logging Configure proper logging with SLF4J

  6. DTO Pattern Use Data Transfer Objects for API contracts

  7. Caching Implement Redis for frequent read operations


Next Steps (H2)


Conclusion (H2)

This implementation demonstrates core Spring Boot features following modern development practices. The API includes:

  1. Proper error handling
  2. Input validation
  3. Database integration
  4. API documentation
  5. Test coverage
  6. Modular architecture

GitHub Repository: spring-boot-api-demo


To run locally:

shellscript
1
mvn spring-boot:run