Sub topic 3
Validating a Request Body with `@Valid`
Assume you know basic Java records, Spring Boot MVC, HTTP status codes, and JSON. This chapter focuses on how validation failures move from a controller boundary to a consistent 400 Bad Request response.
Validate the request body
@RequestBody lets Jackson map JSON to a Java object. @Valid then runs Bean Validation constraints on that object.
public record CreateBookRequest(
@NotBlank String title,
@NotBlank String author,
@Positive int pages) {}
@PostMapping
public ResponseEntity<Book> create(
@Valid @RequestBody CreateBookRequest request) {
return ResponseEntity.status(HttpStatus.CREATED)
.body(service.create(request));
}Without @Valid, the annotations do nothing. A blank title or zero page count reaches the service layer.
Validate path and query parameters
Use @Validated on the controller when constraints apply directly to method parameters.
@RestController
@Validated
class BookController {
@GetMapping("/{id}")
Book get(@PathVariable @Positive Long id) {
return service.get(id);
}
@GetMapping
List<Book> search(
@RequestParam(defaultValue = "0") @PositiveOrZero int page,
@RequestParam(defaultValue = "20") @Positive int size) {
return service.search(page, size);
}
}Spring first converts text such as "42" to Long or int, then validates the result. A value such as size=abc fails conversion before constraint validation.
Bind several query parameters to one object
A model attribute groups related query values:
public class SearchQuery {
@PositiveOrZero
private int page = 0;
@Positive
private int size = 20;
private String author;
public int getPage() { return page; }
public void setPage(int page) { this.page = page; }
public int getSize() { return size; }
public void setSize(int size) { this.size = size; }
public String getAuthor() { return author; }
public void setAuthor(String author) { this.author = author; }
}
@GetMapping
List<Book> search(@Valid SearchQuery query) {
return service.search(query);
}@Valid is needed here too. Otherwise invalid fields can be bound without validation.
Return consistent 400 responses
Use @RestControllerAdvice to format body and binding errors in one place.
@RestControllerAdvice
class ApiErrors {
@ExceptionHandler({
MethodArgumentNotValidException.class,
BindException.class,
MethodArgumentTypeMismatchException.class
})
ProblemDetail badRequest(Exception ex) {
return ProblemDetail.forStatusAndDetail(
HttpStatus.BAD_REQUEST, "Request input is invalid");
}
}In production, add field-level messages to the ProblemDetail. Common errors include forgetting @Valid, using a date format the converter does not understand, and treating missing required parameters as optional.
Choose the input style
| Input style | Best for |
|---|---|
| Path variable | Identifying one resource, such as `/books/42` |
| Query parameter | Filtering, sorting, paging, or optional values |
| Request body | Creating or updating structured data |
Try the endpoints
curl "http://localhost:8080/api/books?page=0&size=10"
curl -X POST http://localhost:8080/api/books \
-H "Content-Type: application/json" \
-d '{"title":"","author":"Ursula K. Le Guin","pages":0}'A focused MockMvc test checks the failure status:
mockMvc.perform(post("/api/books")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"title\":\"\",\"author\":\"A\",\"pages\":0}"))
.andExpect(status().isBadRequest());Exercise
Which annotation makes Bean Validation run on a JSON request body?
Show answer
@Valid on the @RequestBody parameter.