Spring Boot REST API: Controller Design with DTOs and Validation
System DesignModel answerLast updated
Build a Spring Boot controller for a banking resource with proper HTTP semantics, request validation, error handling, and tests.
You're building a customer account management API for a financial services platform using Spring Boot. Your task is to implement the web layer with proper REST conventions, validation, and testing.
Context
The system manages customer accounts. Each account has:
- A unique identifier (generated)
- A 10-digit account number (unique, cannot be changed after creation)
- The account holder's name (required, 2–100 characters)
- An account category: either
CHECKINGorSAVINGS - A current balance (non-negative decimal)
- A status flag:
ACTIVE,FROZEN, orCLOSED
What You Need to Build
1. Request and Response Models
Create separate data transfer objects for:
- Creating a new account (all fields required except the ID)
- Updating an existing account (only the holder name and status can be modified)
- Returning account data to clients
Apply Jakarta Bean Validation annotations to enforce:
- Account number must be exactly 10 numeric digits
- Holder name must be 2–100 characters, not blank
- Balance must be zero or positive
- Immutable fields (account number, balance) should be explicitly rejected if present in update requests
2. Controller Endpoints
Implement AccountController at the base path /api/v1/accounts:
Create a new account:
- HTTP method and path:
POST /api/v1/accounts - Accepts a JSON payload with account details
- Returns
201 Createdwith the created resource and aLocationheader pointing to the new resource - Returns
400 Bad Requestfor validation failures
Retrieve a single account:
- HTTP method and path:
GET /api/v1/accounts/{id} - Returns
200 OKwith account details - Returns
404 Not Foundif the account doesn't exist
List accounts with optional filtering:
- HTTP method and path:
GET /api/v1/accounts - Accepts an optional query parameter
status(e.g.,?status=ACTIVE) - Returns
200 OKwith an array of matching accounts
Update an account:
- HTTP method and path:
PUT /api/v1/accounts/{id} - Replaces the holder name and status with the provided values
- Account number and balance cannot be changed through this endpoint
- Returns
200 OKon success,404 Not Foundif the ID doesn't exist
3. Error Handling
Create a global exception handler using @RestControllerAdvice that catches validation errors and domain exceptions, returning a consistent error structure containing:
timestamp(when the error occurred)status(HTTP status code as an integer)error(the HTTP status reason phrase)message(a human-readable error description)
4. Testing
Write a Spring MVC test slice using @WebMvcTest and MockMvc that verifies:
- The
POSTendpoint rejects invalid input and returns400 - The
POSTendpoint accepts valid input, returns201, and includes theLocationheader
Expectations
- Use proper HTTP status codes and headers
- Keep the controller thin—delegate business logic to a service layer
- Return consistent error responses across all failure cases
- Demonstrate that validation occurs before service methods are invoked
Hints
Hint 1
Separate your DTOs by operation—create, update, and response should be different types
Hint 2
Use @Valid in the controller and let Spring's validation handle constraint violations before your code runs
Hint 3
Build the Location header dynamically using ServletUriComponentsBuilder to handle proxies correctly
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Spring Boot REST Controller with Validation and Error Handling
Core Strategy
The question tests whether you understand HTTP as a contract and keep the web layer separate from persistence concerns. Three design choices shape the entire solution:
-
One DTO per operation. A creation request includes all required fields. An update request carries only mutable fields. The response model is read-only. This prevents mass-assignment vulnerabilities and makes immutability explicit in the type system.
-
Declarative validation at the boundary. Annotate the DTOs with Jakarta Bean Validation constraints (
@NotBlank,@Pattern,@PositiveOrZero). Place@Validon the controller parameter. Spring rejects invalid requests before your service runs, eliminating boilerplate null checks and producing consistent error messages. -
Centralized exception translation. Domain exceptions like "account not found" or "duplicate account number" are thrown from the service layer. A single
@RestControllerAdvicemaps them to HTTP responses with uniform structure. Controllers stay thin and focused on HTTP semantics.
Why This Approach Works
POST returns 201 with Location. The 201 Created status tells clients the resource was successfully created. The Location header provides the URI where the new resource lives. Building this dynamically with ServletUriComponentsBuilder.fromCurrentRequest() keeps the solution portable across environments—it captures the scheme, host, and context path from the incoming request.
Validation happens first. When @Valid fails, Spring throws MethodArgumentNotValidException before the controller method body runs. The test proves this by verifying the service was never called (verifyNoInteractions(service)). This keeps validation concerns out of business logic.
PUT is idempotent. Sending the same update request multiple times produces the same final state. The update DTO explicitly declares accountNumber and balance fields with @Null constraints. A client attempting to modify immutable fields gets an immediate 400 error, not silent data loss.
Filtering with optional parameters. The GET /api/v1/accounts?status=ACTIVE endpoint uses an optional enum parameter. When present, it filters; when absent, it returns everything. Spring automatically converts the string to the enum or raises MethodArgumentTypeMismatchException for invalid values, which the error handler maps to 400.
Consistent error shape. Every failure path—validation errors, missing resources, duplicate keys, malformed JSON—returns the same structure: timestamp, status code, error type, and message. Clients need only one error parser.
Implementation Structure
DTOs with Validation
public record CreateAccountRequest(
@NotBlank
@Pattern(regexp = "\\d{10}", message = "Account number must be exactly 10 digits")
String accountNumber,
@NotBlank
@Size(min = 2, max = 100)
String accountHolderName,
@NotNull
AccountType accountType,
@NotNull
@PositiveOrZero
BigDecimal balance
) {}
public record UpdateAccountRequest(
@NotBlank
@Size(min = 2, max = 100)
String accountHolderName,
@NotNull
AccountStatus status,
@Null(message = "Account number is immutable and cannot be updated")
String accountNumber,
@Null(message = "Balance cannot be modified through this endpoint")
BigDecimal balance
) {}
public record AccountResponse(
Long id,
String accountNumber,
String accountHolderName,
AccountType accountType,
BigDecimal balance,
AccountStatus status
) {
public static AccountResponse from(BankAccount account) {
return new AccountResponse(
account.getId(),
account.getAccountNumber(),
account.getAccountHolderName(),
account.getAccountType(),
account.getBalance(),
account.getStatus()
);
}
}
The update DTO's @Null constraints make immutability testable—any client that sends those fields gets a clear error.
Controller
@RestController
@RequestMapping("/api/v1/accounts")
public class AccountController {
private final AccountService service;
public AccountController(AccountService service) {
this.service = service;
}
@PostMapping
public ResponseEntity<AccountResponse> create(@Valid @RequestBody CreateAccountRequest request) {
AccountResponse response = service.create(request);
URI location = ServletUriComponentsBuilder
.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(response.id())
.toUri();
return ResponseEntity.created(location).body(response);
}
@GetMapping("/{id}")
public AccountResponse getById(@PathVariable Long id) {
return service.findById(id);
}
@GetMapping
public List<AccountResponse> list(@RequestParam(required = false) AccountStatus status) {
return service.findAll(status);
}
@PutMapping("/{id}")
public AccountResponse update(@PathVariable Long id, @Valid @RequestBody UpdateAccountRequest request) {
return service.update(id, request);
}
}
The controller does three things: validate input, delegate to the service, and shape HTTP responses. No business rules appear here.
Global Error Handler
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ApiError> handleValidation(MethodArgumentNotValidException ex) {
String message = ex.getBindingResult().getFieldErrors().stream()
.map(err -> err.getField() + ": " + err.getDefaultMessage())
.collect(Collectors.joining("; "));
return ResponseEntity.badRequest().body(new ApiError(
Instant.now(),
400,
"Bad Request",
message
));
}
@ExceptionHandler(AccountNotFoundException.class)
public ResponseEntity<ApiError> handleNotFound(AccountNotFoundException ex) {
return ResponseEntity.status(404).body(new ApiError(
Instant.now(),
404,
"Not Found",
ex.getMessage()
));
}
@ExceptionHandler(DuplicateAccountException.class)
public ResponseEntity<ApiError> handleDuplicate(DuplicateAccountException ex) {
return ResponseEntity.status(409).body(new ApiError(
Instant.now(),
409,
"Conflict",
ex.getMessage()
));
}
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
public ResponseEntity<ApiError> handleTypeMismatch(MethodArgumentTypeMismatchException ex) {
return ResponseEntity.badRequest().body(new ApiError(
Instant.now(),
400,
"Bad Request",
"Invalid parameter: " + ex.getName()
));
}
}
public record ApiError(Instant timestamp, int status, String error, String message) {}
This handler consolidates all error responses. Adding a new exception type requires one new method, not scattered try-catch blocks.
Test
@WebMvcTest(AccountController.class)
class AccountControllerTest {
@Autowired private MockMvc mockMvc;
@MockBean private AccountService service;
@Test
void createAccount_withInvalidData_returns400() throws Exception {
mockMvc.perform(post("/api/v1/accounts")
.contentType(MediaType.APPLICATION_JSON)
.content("""
{
"accountNumber": "12345",
"accountHolderName": "",
"accountType": "CHECKING",
"balance": -100
}
"""))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.status").value(400));
verifyNoInteractions(service);
}
@Test
void createAccount_withValidData_returns201() throws Exception {
AccountResponse response = new AccountResponse(
1L, "1234567890", "John Doe", AccountType.CHECKING,
BigDecimal.ZERO, AccountStatus.ACTIVE
);
when(service.create(any())).thenReturn(response);
mockMvc.perform(post("/api/v1/accounts")
.contentType(MediaType.APPLICATION_JSON)
.content("""
{
"accountNumber": "1234567890",
"accountHolderName": "John Doe",
"accountType": "CHECKING",
"balance": 0
}
"""))
.andExpect(status().isCreated())
.andExpect(header().exists("Location"))
.andExpect(header().string("Location", containsString("/api/v1/accounts/1")))
.andExpect(jsonPath("$.id").value(1));
}
}
The first test confirms validation happens before service invocation. The second test verifies the 201 response and Location header.
Edge Cases and Tradeoffs
Account number validation: The regex \\d{10} accepts exactly ten digits. A nine-digit number or one with letters fails immediately. Pair this with a unique database constraint to prevent races—checking existence in the service is necessary but not sufficient.
BigDecimal for money: Never use float or double for currency. Floating-point arithmetic introduces rounding errors. BigDecimal preserves precision.
Whitespace-only names: @NotBlank trims input before checking. A name of just spaces is rejected.
Optimistic locking: For concurrent updates, add a @Version field to the entity. JPA throws OptimisticLockException on stale writes, which the handler maps to 409 Conflict.
Pagination: The list endpoint is unbounded. In production, add Pageable parameters and return Page<AccountResponse> to limit memory usage and response size.
Complexity
- Single lookups (GET by ID, PUT): O(1) with a primary key index.
- Filtered list: O(k) where k is the number of matching rows. Add a database index on the
statuscolumn. - Space: O(k) for the response list; O(1) otherwise per request.
Common Mistakes
- Binding requests directly to entities. This exposes the database schema and allows clients to set arbitrary fields, including IDs and timestamps. Always use DTOs.
- Returning 200 for creation. The correct status is
201 Created, and theLocationheader is not optional—it tells clients where to find the new resource. - Ignoring immutability in PUT. Silently dropping
accountNumberfrom the update hides the mistake. Making it an error with@Nullsurfaces the problem immediately. - Inconsistent error responses. Mixing different error formats (sometimes a string, sometimes an object) breaks client parsers. Standardize on one shape.
This solution demonstrates understanding of HTTP semantics, separation of concerns, and defensive API design.