Sub topic 11
Validating request bodies
This chapter assumes you have the BookRequest record, the BookController, and the spring-boot-starter-validation dependency from the earlier chapters. You should also know what an annotation is and what a 400 status code means.
Why validate at the edge
The service layer trusts the data it receives. If a client sends {"title":"","author":"Ada"}, nothing stops an empty title from reaching the database. Bean Validation (the Jakarta Validation standard, implemented by Hibernate Validator) lets you declare the rules on the request DTO. Spring checks them before your controller method body runs.
Validate the DTO, not the entity. The rules describe what the API accepts, and the entity describes what the database stores. Those two can change independently.
Declaring constraints
Constraints are annotations on the record components. Spring applies them to the record's fields and accessors.
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
public record BookRequest(
@NotBlank @Size(max = 200) String title,
@NotBlank @Size(max = 100) String author) {
}The common constraints behave differently on null and empty values:
| Annotation | Rejects null | Rejects `""` | Rejects `" "` |
|---|---|---|---|
| `@NotNull` | yes | no | no |
| `@NotEmpty` | yes | yes | no |
| `@NotBlank` | yes | yes | yes |
@NotBlank applies only to strings. Use it for text fields. @Size treats null as valid, so combine it with @NotBlank when the field is required.
Triggering validation
Declaring constraints does nothing by itself. The controller must ask for validation with @Valid on the @RequestBody parameter, as in the earlier controller.
@PostMapping
public ResponseEntity<BookResponse> create(@Valid @RequestBody BookRequest request) {
BookResponse created = service.create(request);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(created.id())
.toUri();
return ResponseEntity.created(location).body(created);
}Put @Valid on both create and update. If you forget it on one, that endpoint accepts bad data without any error.
What happens on failure
When a constraint fails, Spring throws MethodArgumentNotValidException before the controller method runs. Spring Boot's default handling turns it into a 400 response. The exact body depends on your configuration, so don't rely on its shape yet. The next chapter replaces it with a consistent error format.
Malformed JSON, such as a missing closing brace, also gives 400. That failure happens earlier, during parsing, and raises HttpMessageNotReadableException.
Common errors
- No validation happens. Check that
spring-boot-starter-validationis in the POM. Since Spring Boot 2.3 the web starter no longer includes it. @Validis missing. The constraints are ignored without it.- Wrong import. Use
jakarta.validation.constraintsin Spring Boot 3 and later. Older projects usejavax.validation, and mixing them silently disables the rules. - A blank title is accepted. You probably used
@NotNull, which allows"". - Rules only in the entity. Entity constraints are checked at persist time and surface as database-layer exceptions, not clean 400 responses.
Testing the rule
The rejectsBlankTitle test from the testing chapter already exercises this. It posts an empty title and expects status().isBadRequest(). Add a similar test for every constraint you introduce.
Exercise
A client posts {"title":" ","author":"Ada"} to an endpoint whose controller parameter is annotated with @RequestBody but not @Valid. The record uses @NotBlank on title. What status code do you get, and what is the fix?
Show answer
The request is accepted (for example 201 Created), because Spring only checks constraints when @Valid (or @Validated) is present. Add @Valid before @RequestBody. Then the blank title fails validation and the client gets 400.
Exercise
Which annotation rejects the string " " (two spaces): @NotNull, @NotEmpty, or @NotBlank?
Show answer
Only @NotBlank. @NotNull accepts any non-null value, and @NotEmpty accepts a string that has at least one character, including spaces.