Sub topic 1
Why Validate Requests at the API Boundary
Prerequisites
Assume you know Java records and annotations, can build a Spring MVC controller, and understand HTTP status codes and JSON request bodies. This chapter uses Spring Boot with Jakarta Bean Validation.
Reject Invalid Data Early
The API boundary is the point where external data enters your application. Clients can send missing fields, invalid formats, or values outside the business rules. Validate this data before calling services or writing to a database.
Early validation keeps business code focused on valid input. It also gives clients a predictable 400 Bad Request response instead of an unrelated database or service error.
Jakarta Bean Validation and the Starter
Jakarta Bean Validation is a standard API for declaring rules with annotations. Hibernate Validator is the common implementation used by Spring Boot.
Add Spring Boot’s validation starter:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>The starter supplies the validation API and implementation. Spring Boot then integrates validation with Spring MVC.
Declaring Constraints on a Request DTO
A data transfer object (DTO) represents data exchanged with an API. Put input rules on the DTO so the rules stay close to the fields they describe.
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
public record CreateUserRequest(
@NotBlank @Size(max = 50) String name,
@NotBlank @Email String email,
@NotNull @Min(18) Integer age) {
}@NotBlank rejects null, empty, and whitespace-only text. @Email checks an email-like format. @Size limits the text length. @NotNull requires a value, while @Min checks a numeric lower bound.
Constraints describe invalid input, but Spring must be told when to apply them.
Triggering Validation with `@Valid`
Put @Valid on the request body parameter:
@PostMapping("/users")
public ResponseEntity<Void> create(
@Valid @RequestBody CreateUserRequest request) {
return ResponseEntity.status(HttpStatus.CREATED).build();
}Spring binds the JSON body to CreateUserRequest, runs its constraints, and only enters the method when validation succeeds. Invalid input raises a validation exception before the method body runs.
Exercise
What happens if a request omits age or sends an age of 16?
Show answer
@NotNull rejects a missing age, and @Min(18) rejects 16. Spring raises a validation exception before the controller method runs.