Sub topic 11
Validating request bodies
This chapter adds Bean Validation to the book API. You will declare constraints on BookRequest, trigger them from the controller, and return a consistent 400 response that names each bad field. It assumes you have the controller, DTO records, and ApiExceptionHandler from the earlier chapters, and that you know basic annotations and HTTP status codes.
Why validate at the boundary
Without validation, {"title":"","author":null} reaches the service and the database. You then get a half-empty row or a confusing 500 from a database constraint. Validating at the edge rejects bad input before any business logic or transaction starts, and it gives the client a clear reason.
Bean Validation (Jakarta Validation) is a specification. Hibernate Validator is the implementation that spring-boot-starter-validation brings in. You declare rules as annotations, and Spring runs them when it binds a request.
What happens to a request
Two separate failures lead to 400. A malformed or wrongly typed body fails during parsing. A well-formed body with unacceptable values fails during validation. Only the second one is covered by constraint annotations.
Dependency check
Spring Boot stopped including validation in the web starter in version 2.3. The setup chapter added spring-boot-starter-validation, and it is required here. If it is missing, @NotBlank compiles only when another dependency supplies the annotations, and nothing enforces it. A missing starter is a common reason for validation seeming to do nothing.
Declaring constraints on the DTO
Put constraints on the request record, not on the entity. The DTO describes what a client may send, and the entity describes what is stored.
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
public record BookRequest(
@NotBlank(message = "title is required")
@Size(max = 200, message = "title must be at most 200 characters")
String title,
@NotBlank(message = "author is required")
@Size(max = 100, message = "author must be at most 100 characters")
String author) {
}Annotations on record components are applied to the matching constructor parameters and accessors, and Hibernate Validator reads them correctly. Keep the @Size limits at or below the column lengths in your schema. With ddl-auto=validate, the schema is yours to manage, so the two must agree.
Choosing the right constraint
| Annotation | Rejects | Typical use |
|---|---|---|
| `@NotNull` | `null` only | Any required value, such as a number or date |
| `@NotEmpty` | `null` and empty strings or collections | Lists that must have items |
| `@NotBlank` | `null`, empty, and whitespace-only strings | Required text such as title |
| `@Size(min, max)` | Lengths outside the range | Text length, collection size |
| `@Min`, `@Max` | Numbers outside the range | Counts, ratings |
| `@Pattern(regexp)` | Strings that do not match | Codes, such as an ISBN format |
| `@Email` | Strings that are not email-shaped | Contact fields |
Most constraints other than @NotNull, @NotEmpty, and @NotBlank treat null as valid. @Size(max = 200) alone lets a missing title through. Pair it with a not-null constraint when the field is required.
Triggering validation
Annotations do nothing until something asks the validator to run. In the controller, @Valid on the @RequestBody parameter does that. The create and update methods from the controller chapter already have it:
@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);
}
@PutMapping("/{id}")
public BookResponse update(@PathVariable Long id, @Valid @RequestBody BookRequest request) {
return service.update(id, request);
}Both write endpoints need it. A missing @Valid on PUT is a frequent bug, because people test POST and assume PUT behaves the same.
When a constraint fails, Spring throws MethodArgumentNotValidException before your controller method body runs. Its BindingResult holds one FieldError per violated constraint.
What the client sees by default
With no handler, Spring Boot returns a 400 with its default error body. That body is not shaped like the 404 ProblemDetail from ApiExceptionHandler, so clients would need to parse two formats. The next step is to handle validation errors in the same advice class.
Returning field-level errors
Add a second handler to ApiExceptionHandler. It collects the field errors into a map and attaches the map to a ProblemDetail.
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class ApiExceptionHandler {
@ExceptionHandler(BookNotFoundException.class)
public ProblemDetail handleNotFound(BookNotFoundException ex) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
problem.setTitle("Book not found");
return problem;
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ProblemDetail handleValidation(MethodArgumentNotValidException ex) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
HttpStatus.BAD_REQUEST, "Request validation failed");
problem.setTitle("Invalid request");
Map<String, String> errors = new LinkedHashMap<>();
for (FieldError error : ex.getBindingResult().getFieldErrors()) {
errors.putIfAbsent(error.getField(), error.getDefaultMessage());
}
problem.setProperty("errors", errors);
return problem;
}
}A request with a blank title and a missing author now returns a body like this:
{
"type": "about:blank",
"title": "Invalid request",
"status": 400,
"detail": "Request validation failed",
"instance": "/api/books",
"errors": {
"title": "title is required",
"author": "author is required"
}
}Key details of the handler:
putIfAbsentkeeps one message per field. A field can fail several constraints at once, for example an empty string that is both blank and too short.- A
LinkedHashMapkeeps the order stable, which makes responses and tests predictable. setPropertyadds a custom member to the problem body. Clients get the standard fields pluserrors.- Messages come from your
messageattributes. Do not echo the rejected value back unless you are sure it is safe to expose.
Edge cases
Missing, null, and unknown JSON fields
A JSON body that omits author binds null to that record component, so @NotBlank rejects it. A property the record does not have is ignored by default in Spring Boot, because it disables Jackson's FAIL_ON_UNKNOWN_PROPERTIES. A client typo such as "titel" therefore looks like a missing title.
Malformed JSON and type errors
A body such as {"title": or a value of the wrong type fails in Jackson, before validation. Spring raises HttpMessageNotReadableException, and the default response is a 400 in Boot's standard error format. Add a handler for it if you need that response to match your ProblemDetail shape. To have Spring produce ProblemDetail for its own built-in exceptions, set spring.mvc.problemdetails.enabled=true. Your own @ExceptionHandler methods still apply to the exceptions they declare.
Validating path and query parameters
@Valid covers objects. For simple parameters, put constraints directly on them:
@GetMapping("/{id}")
public BookResponse get(@PathVariable @Positive Long id) {
return service.get(id);
}In Spring Framework 6.1 and later (Spring Boot 3.2+), a violation here raises HandlerMethodValidationException, which maps to 400 by default. In earlier versions you must add @Validated to the controller class, and the exception is ConstraintViolationException, which maps to 500 unless you handle it. Check your Boot version before relying on this.
Validation is not a uniqueness check
Constraints look at one object in isolation. They cannot tell whether a title already exists. Enforce uniqueness with a database unique constraint and handle the resulting DataIntegrityViolationException, or check in the service.
Testing validation
The @WebMvcTest from the testing outline can assert both the status and the error body. This version needs Spring Boot 3.4 or later for @MockitoBean. On older versions, use @MockBean.
import static org.mockito.Mockito.verifyNoInteractions;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.MockMvc;
@WebMvcTest(BookController.class)
class BookValidationTest {
@Autowired
private MockMvc mockMvc;
@MockitoBean
private BookService service;
@Test
void createReportsEveryInvalidField() throws Exception {
mockMvc.perform(post("/api/books")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"title\":\" \"}"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.errors.title").value("title is required"))
.andExpect(jsonPath("$.errors.author").value("author is required"));
verifyNoInteractions(service);
}
@Test
void updateAlsoValidatesTheBody() throws Exception {
mockMvc.perform(put("/api/books/1")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"title\":\"Notes\",\"author\":\"\"}"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.errors.author").value("author is required"));
verifyNoInteractions(service);
}
}verifyNoInteractions(service) proves the request was rejected before reaching the service. That check catches a missing @Valid, because the mock would otherwise be called.
Common errors
- Constraints have no effect: the validation starter is missing, or
@Validis absent from the parameter. @Sizeaccepts a missing value: add@NotBlankor@NotNull.- A 500 with
ConstraintViolationExceptionon a path variable: you are on an older Boot version and need@Validatedon the controller plus a handler. - Different error formats for 404 and 400: the validation handler is missing from the advice class.
- Messages revealing internal names: set explicit
messagevalues instead of relying on defaults.
Exercise
A client sends PUT /api/books/5 with the body {"title":"Dune","author":" "}. The controller method has @RequestBody BookRequest request but no @Valid. What happens, and what is the smallest change that makes the API return a 400 with an errors entry for author?
Show answer
The request is accepted, because Spring never asks the validator to run, even though BookRequest has @NotBlank on author. The service then updates book 5 with a whitespace-only author. Adding @Valid in front of @RequestBody on the update method makes Spring validate the body. The blank author then fails @NotBlank, MethodArgumentNotValidException is thrown, and the handler in ApiExceptionHandler returns a 400 whose errors map contains "author".
Exercise
BookRequest declares only @Size(max = 200) on title. Does a request with no title field pass validation? Why, and how do you fix it?
Show answer
Yes, it passes. A missing field binds null, and @Size treats null as valid. Add @NotBlank (or @NotNull if empty text is acceptable) to title so that null is rejected.