Sub topic 3
Validating Request Bodies and Testing the API
Assume you know Java annotations, HTTP methods and status codes, JSON, relational databases, and Maven or Gradle. This chapter connects input validation, error handling, pagination, and web-layer tests.
Validating Request Bodies
Bean Validation checks whether incoming data follows declared rules. Put constraints on a request DTO, then add @Valid to the controller parameter.
public record BookRequest(
@NotBlank(message = "title is required") String title,
@NotBlank(message = "author is required") String author) {
}
@PostMapping
public ResponseEntity<BookResponse> create(
@Valid @RequestBody BookRequest request) {
return ResponseEntity.status(HttpStatus.CREATED)
.body(service.create(request));
}@NotBlank rejects missing, empty, or whitespace-only strings. Spring returns a client error before the service runs when validation fails.
Returning Consistent Errors
Use @RestControllerAdvice for exceptions shared by all controllers. ProblemDetail provides a standard structure for HTTP API errors.
@RestControllerAdvice
class ApiExceptionHandler {
@ExceptionHandler(BookNotFoundException.class)
ProblemDetail notFound(BookNotFoundException ex) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
HttpStatus.NOT_FOUND, ex.getMessage());
problem.setTitle("Book not found");
return problem;
}
@ExceptionHandler(MethodArgumentNotValidException.class)
ProblemDetail invalid(MethodArgumentNotValidException ex) {
ProblemDetail problem = ProblemDetail.forStatus(
HttpStatus.BAD_REQUEST);
problem.setTitle("Validation failed");
problem.setProperty("errors", ex.getFieldErrors().stream()
.map(error -> error.getField() + ": " + error.getDefaultMessage())
.toList());
return problem;
}
}The service should throw domain exceptions without knowing about HTTP. The advice layer translates those exceptions into responses.
Paginating and Sorting Collections
A Pageable describes the requested page number, page size, and sort order. Spring Data reads them from query parameters.
@GetMapping
Page<BookResponse> list(Pageable pageable) {
return repository.findAll(pageable).map(BookResponse::from);
}A request such as /api/books?page=0&size=10&sort=title,asc returns the first ten books ordered by title. The response includes page metadata, such as total elements and pages.
Testing the Web Layer with MockMvc
A @WebMvcTest loads controllers, validation, and advice without starting the database. Mock the service and test HTTP behavior.
@WebMvcTest(BookController.class)
class BookControllerTest {
@Autowired MockMvc mockMvc;
@MockitoBean BookService service;
@Test
void rejectsBlankTitle() throws Exception {
mockMvc.perform(post("/api/books")
.contentType(MediaType.APPLICATION_JSON)
.content("""
{"title":"","author":"Ada"}
"""))
.andExpect(status().isBadRequest());
}
}Test status codes and response fields, not the service implementation.
Exercise
Which annotation activates request-body validation in a controller?
Show answer
@Valid activates the constraints declared on the request DTO.