Writes API endpoints with Spring Boot following layered architecture patterns. To be used for implementing RESTful endpoints with validation, exception handling, and business logic in Java.
Follow a layered architecture with clear separation of concerns between HTTP handling (controllers), business logic (services), and contracts/models (DTOs and entities).
The application uses three main layers:
Controllers (HTTP Layer)
↓
Services (Business Logic)
↓
Types/Models (DTOs, Entities, Error Contracts)
Organize code by technical layer:
src/main/java/com/example/app/
├── Application.java
├── controller/
│ └── ResourceController.java
├── service/
│ └── ResourceService.java
├── dto/
│ ├── CreateResourceRequest.java
│ ├── UpdateResourceRequest.java
│ └── ResourceResponse.java
├── model/
│ └── Resource.java
├── exception/
│ ├── ResourceNotFoundException.java
│ └── GlobalExceptionHandler.java
└── mapper/
└── ResourceMapper.java
Controller suffix: ResourceController.java/api/resources)Controllers should delegate business rules to services and focus on HTTP concerns:
@RestController and @RequestMappingResponseEntity with proper status codesSee ResourceController.java template for complete example implementation.
| Method | Success | Validation Error | Not Found |
|---|---|---|---|
| GET | 200 | N/A | 404 |
| POST | 201 | 400 | N/A |
| PUT | 200 | 400 | 404 |
| DELETE | 204 | N/A | 404 |
Service suffix: ResourceService.javaServices encapsulate domain and business logic:
ResourceNotFoundException) instead of returning null for missing data@Transactional)See ResourceService.java template for complete example implementation.
Resource.java, CreateResourceRequest.java, ResourceResponse.javaOrganize types into three categories:
See ResourceContracts.java template for complete example implementation.
@RestControllerAdviceCentralize exception mapping in a global handler:
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ErrorResponse> handleNotFound(ResourceNotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(new ErrorResponse("RESOURCE_NOT_FOUND", ex.getMessage()));
}
}
Key patterns:
400 Bad Requestcode, message, optional fieldErrors)Use standard Spring Boot startup and constructor injection:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Key patterns:
application.yml/application.properties@RestControllerAdvice for consistent API errors