Sub topic 8
Validating a Request Body with @Valid
This chapter covers Bean Validation on a JSON request body. It assumes you can run a Spring Boot web project, read a controller method, and map a JSON body to a record with @RequestBody.
Why validate at the boundary
Jackson only checks that the JSON is well formed and that field types fit. A body such as {"title":"","author":" ","pages":-5} maps to a record without any error. Bean Validation lets you declare which values are acceptable, so the controller and service never see bad data.
Spring Boot supports this through spring-boot-starter-validation. If your project does not have it, add it to your build. spring-boot-starter-web does not include it.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>Declaring constraints
Put constraint annotations on the components of the record. They are the same annotations you would put on class fields.
public record CreateBookRequest(
@NotBlank String title,
@NotBlank String author,
@Positive int pages) {}@NotBlankrejectsnull, an empty string, and a string of only whitespace. It works on strings only.@Positiverequires a number greater than zero.- Each annotation also accepts a
messageattribute, for example@NotBlank(message = "title is required").
Triggering validation with @Valid
Constraints do nothing until the controller asks for them to be checked. Add @Valid to the @RequestBody parameter.
@PostMapping
public ResponseEntity<Book> create(@Valid @RequestBody CreateBookRequest request) {
Book saved = service.create(request);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(saved.id())
.toUri();
return ResponseEntity.created(location).body(saved);
}The order of events is:
- Spring reads the body and Jackson builds the
CreateBookRequest. - Because of
@Valid, Spring runs the validator on the new object. - If every constraint passes, the method body runs and returns 201 Created with a
Locationheader. - If any constraint fails, Spring throws
MethodArgumentNotValidExceptionand the method never runs.
What the client sees by default
Without any extra code, a failed validation gives a 400 response. The details of the body depend on your Spring Boot version and settings, so a client should not rely on its exact shape. A handler that you write yourself gives you a stable format. The error handling chapter builds on this one and covers it fully. This is the handler for validation failures, so you can see what the exception carries:
@ExceptionHandler(MethodArgumentNotValidException.class)
public ProblemDetail handleInvalidBody(MethodArgumentNotValidException ex) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
HttpStatus.BAD_REQUEST, "Request body failed validation");
Map<String, String> errors = new LinkedHashMap<>();
ex.getBindingResult().getFieldErrors()
.forEach(e -> errors.putIfAbsent(e.getField(), e.getDefaultMessage()));
problem.setProperty("errors", errors);
return problem;
}It lives in a @RestControllerAdvice class. getFieldErrors() lists one entry per failed constraint. putIfAbsent keeps the first message when a field breaks more than one rule.
Common errors
| Symptom | Likely cause |
|---|---|
| Invalid bodies are accepted | `@Valid` is missing from the parameter |
| Annotations are ignored and some do not compile | The validation starter is not on the classpath |
| `@NotBlank` fails on an `int` field | Wrong annotation for the type. Use `@Positive` or `@Min` for numbers |
| Missing `pages` passes validation | A primitive `int` defaults to 0 when the field is absent, and `@Positive` should then fail. A boxed `Integer` with `@NotNull` is clearer when you need to tell "missing" from "zero" |
Trying it
Send an invalid body and check the status code:
curl -i -X POST http://localhost:8080/api/books \
-H "Content-Type: application/json" \
-d '{"title":"","author":"Ursula K. Le Guin","pages":-5}'Expect 400 Bad Request. Two fields fail: title (blank) and pages (not positive).
Exercise
A controller method has the parameter @RequestBody CreateBookRequest request, and the record has @NotBlank on title. A client posts {"title":"","author":"X","pages":10} and receives 201 Created. What is wrong, and what is the fix?
Show answer
The parameter lacks @Valid, so Spring never runs the constraints. Change it to @Valid @RequestBody CreateBookRequest request. Also confirm that spring-boot-starter-validation is on the classpath.
Exercise
Which exception does Spring throw when a @Valid @RequestBody object fails validation, and how do you read the failing field names from it?
Show answer
It throws MethodArgumentNotValidException. Call ex.getBindingResult().getFieldErrors() and read getField() and getDefaultMessage() from each entry.