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

Example Mermaid Diagram
Example Table
| Framework | Popularity | Learning Curve |
|---|---|---|
| React | High | Moderate |
| Vue | High | Low |
| Svelte | Growing | Low |
String code="secret";
Overview (H2)
JPA/Hibernate Learn to create a production-ready REST API using Spring Boot 3.x with essential
features:
JPA/Hibernatedatabase integration- Layered architecture
- Exception handling
- Validation
- Testing
- OpenAPI documentation
- Security fundamentals
Prerequisites (H2)
- Java 17+
- Maven 3.6+
- IDE (IntelliJ/VS Code)
- PostgreSQL (or H2 for development)
Step 1: Project Setup (H2)
Initialize project via Spring Initializr with dependencies:
- Spring Web
- Spring Data JPA
- Validation
- Lombok
- PostgreSQL Driver
- OpenAPI (SpringDoc)
pom.xml essentials:
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:
1@Entity2@Getter3@Setter4@NoArgsConstructor5@AllArgsConstructor6@Builder7public class Product {8@Id9@GeneratedValue(strategy = GenerationType.IDENTITY)10private Long id;1112@NotBlank(message = "Name is mandatory")13@Size(max = 100)14private String name;1516@PositiveOrZero17private BigDecimal price;1819@CreationTimestamp20private LocalDateTime createdAt;21}
Step 3: Repository Layer (H2)
JPA Repository Interface:
1public interface ProductRepository extends JpaRepository<Product, Long> {2List<Product> findByNameContainingIgnoreCase(String name);3}
Step 4: Service Layer (H2)
Business Logic Implementation:
1@Service2@RequiredArgsConstructor3public class ProductService {45private final ProductRepository productRepository;67public Product createProduct(Product product) {8return productRepository.save(product);9}1011public Product getProductById(Long id) {12return productRepository.findById(id)13.orElseThrow(() -> new ResourceNotFoundException("Product not found"));14}1516// Additional business methods17}
Step 5: REST Controller (H2)
API Endpoints:
1@RestController2@RequestMapping("/api/v1/products")3@RequiredArgsConstructor4@Tag(name = "Product API", description = "Product management operations")5public class ProductController {67private final ProductService productService;89@PostMapping10@ResponseStatus(HttpStatus.CREATED)11public Product createProduct(@Valid @RequestBody Product product) {12return productService.createProduct(product);13}1415@GetMapping("/{id}")16public ResponseEntity<Product> getProduct(@PathVariable Long id) {17return ResponseEntity.ok(productService.getProductById(id));18}19}
Step 6: Exception Handling (H2)
Global Exception Handler:
1@RestControllerAdvice2public class GlobalExceptionHandler {34@ExceptionHandler(ResourceNotFoundException.class)5@ResponseStatus(HttpStatus.NOT_FOUND)6public ErrorResponse handleResourceNotFound(ResourceNotFoundException ex) {7return new ErrorResponse(8HttpStatus.NOT_FOUND.value(),9ex.getMessage(),10Instant.now()11);12}1314// Handle validation errors15}
Step 7: Configuration (H2)
application.yml:
1spring:2datasource:3url: jdbc:postgresql://localhost:5432/ecommerce4username: admin5password: securepass6jpa:7hibernate:8ddl-auto: validate9show-sql: true1011openapi:12title: Product API13version: 1.0.0
Step 8: API Documentation (H2)
Access Swagger UI at http://localhost:8080/swagger-ui.html
Custom OpenAPI Configuration:
1@Configuration2public class OpenApiConfig {34@Bean5public OpenAPI customOpenAPI() {6return 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:
1@SpringBootTest2@AutoConfigureMockMvc3class ProductControllerTest {45@Autowired6private MockMvc mockMvc;78@Test9void shouldCreateProduct() throws Exception {10mockMvc.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)
-
Layered Architecture Maintain clear separation between controllers, services, and repositories
-
Validation Use Hibernate Validator for input sanitization
-
Security Implement JWT authentication with Spring Security
-
Monitoring Add Actuator for health checks and metrics
-
Logging Configure proper logging with SLF4J
-
DTO Pattern Use Data Transfer Objects for API contracts
-
Caching Implement Redis for frequent read operations
Next Steps (H2)
- Add JWT authentication
- Implement pagination and sorting
- Configure Docker deployment
- Add rate limiting
- Set up CI/CD pipeline
- Implement caching layer
Conclusion (H2)
This implementation demonstrates core Spring Boot features following modern development practices. The API includes:
- Proper error handling
- Input validation
- Database integration
- API documentation
- Test coverage
- Modular architecture
GitHub Repository: spring-boot-api-demo
To run locally:
1mvn spring-boot:run