Sub topic 1
Why validate at the API boundary
Every Spring Boot API receives data it did not create. Clients can send missing fields, wrong types, oversized strings, or values that make no business sense. This chapter explains why you check that data at the edge of your application, what that check should and should not cover, and how the rest of this tutorial builds on the idea.
Prerequisites
This chapter assumes you already know:
- Java basics, including records and annotations.
- How to build a simple REST controller with Spring MVC.
- How to add a dependency with Maven or Gradle.
- Basic HTTP concepts such as status codes and JSON bodies.
No validation library is needed yet. The code in this chapter uses plain Java so you can see the problem before the tools that solve it.
The API boundary
The API boundary is the point where data from outside your system enters your code. In a Spring MVC application, this is the controller layer. Spring takes the raw HTTP request, converts the JSON body into a Java object, and passes it to your method.
That conversion only checks the shape of the data. Jackson, the JSON library Spring uses, can tell that "age": "abc" is not a number. It cannot tell that "age": -5 is a bad age, or that "name": "" is an empty name. Both values are valid JSON and valid Java, so they arrive in your method without complaint.
Consider this request body:
{
"name": "",
"email": "not-an-email",
"age": -5
}Jackson maps it to a record without any error. If your controller trusts it, the bad values flow into the rest of the system.
What goes wrong without validation
Unchecked input causes several kinds of failure. They differ in how visible they are.
- Late, confusing errors. A
nullname passes through the controller and the service. It fails inside a repository call with aNullPointerExceptionor a database constraint error. The client gets a500 Internal Server Errorand has no idea which field was wrong. - Bad data stored silently. If the database has no matching constraint, an empty name or a negative age is saved. You find it weeks later in a report.
- Wasted work. The application may call other services, open transactions, or send emails before it discovers the input was unusable.
- Security exposure. Unbounded strings can exhaust memory or fill storage. Unexpected values can reach queries, file paths, or log lines. Validation does not replace parameterized queries or output encoding, but it narrows what can get in.
- Inconsistent error formats. When every layer reports problems in its own way, clients must handle many shapes of error.
The following controller shows the problem. It accepts anything that parses:
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/users")
public class UnsafeUserController {
public record CreateUserRequest(String name, String email, Integer age) {
}
@PostMapping
public ResponseEntity<String> create(@RequestBody CreateUserRequest request) {
// name may be null or blank, email may be garbage, age may be negative
return ResponseEntity.status(HttpStatus.CREATED)
.body("created " + request.name().toUpperCase());
}
}If the client omits name, the call to request.name().toUpperCase() throws a NullPointerException, and Spring returns a 500 response. The fault is in the client's request, so the status should be in the 4xx range. A 500 tells the client that the server is broken and the client should not retry with different data.
Manual checks and why they do not scale
The obvious fix is to check the fields by hand:
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/manual-users")
public class ManualUserController {
public record CreateUserRequest(String name, String email, Integer age) {
}
@PostMapping
public ResponseEntity<String> create(@RequestBody CreateUserRequest request) {
if (request.name() == null || request.name().isBlank()) {
return ResponseEntity.badRequest().body("name is required");
}
if (request.name().length() > 50) {
return ResponseEntity.badRequest().body("name is too long");
}
if (request.email() == null || !request.email().contains("@")) {
return ResponseEntity.badRequest().body("email is invalid");
}
if (request.age() == null || request.age() < 18) {
return ResponseEntity.badRequest().body("age must be at least 18");
}
return ResponseEntity.status(HttpStatus.CREATED).build();
}
}This works, but it has real costs:
- The rules are buried in the method body, mixed with the logic that handles the request.
- The method returns on the first problem, so a client with three bad fields needs three round trips.
- The same rules get copied into every endpoint that accepts the same data, such as create and update.
- Each developer writes the error message in a different style.
- The email check here is naive. Writing correct checks for many field types is slow and easy to get wrong.
Declarative validation
Declarative validation moves the rules out of the method body and attaches them to the data. You state what a valid object looks like, and a framework checks it. Java standardizes this approach as Jakarta Bean Validation, and Spring Boot integrates it with Hibernate Validator as the reference implementation.
The next chapters cover the details. As a preview, the same rules as above look like this:
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) {
}The rules now live with the data. Any endpoint that accepts this type can reuse them. The framework can collect every violation in one pass and report them together, and your controller method only runs when the object is valid.
How validation fits into the request flow
Validation happens after Spring has parsed the body and before your controller method runs. If it fails, the method is never called.
There are two distinct failure points. Malformed JSON or a type mismatch fails during parsing. A well-formed object that breaks a rule fails during validation. Both should end in a 4xx response, and later chapters show how to make their formats consistent.
What belongs in boundary validation
Boundary validation checks facts that can be decided from the request alone, without looking anything up. Good candidates include:
- Presence. Is a required field there, and is it non-blank?
- Size and range. Is a string within its length limit, and a number within its allowed range?
- Format. Does the value look like an email address, a postal code, or a UUID?
- Structure. Does a list have at least one element, and is each element itself valid?
- Simple relationships. Is the end date after the start date in the same request?
Some checks do not belong at the boundary because they need state or context:
| Check | Where it belongs | Reason |
|---|---|---|
| Email is not already registered | Service layer | Requires a database lookup and can race with other requests |
| User may modify this order | Authorization layer | Depends on who is calling and on stored data |
| Account has enough balance | Service layer | Depends on current state inside a transaction |
| Field is not null | Boundary | Decided from the request alone |
| Quantity is positive | Boundary | Decided from the request alone |
The uniqueness check deserves attention. Even if you check "email not taken" before saving, another request can insert the same email between your check and your insert. A database unique constraint is the only reliable guard, and the service should translate that failure into a clear error. Boundary validation is a fast, early filter, not the final defense.
Boundary validation is not the only validation
Validating at the API boundary does not mean validating only there. Several layers each protect something different:
- Boundary validation rejects malformed requests early and gives clients useful feedback.
- Business rules in the service layer enforce domain logic that needs state.
- Database constraints such as
NOT NULLandUNIQUEguarantee integrity even if a bug or another client bypasses the API.
Not every caller comes through the controller. A scheduled job, a message listener, or a test fixture can call your service directly. Chapter 13 of this tutorial covers validating beyond the controller. For now, keep the principle: the boundary is where you catch the most mistakes at the lowest cost, and it is not a substitute for the other layers.
Common mistakes
- Trusting the client UI. Browser-side checks improve user experience, but anyone can send a request with
curl. Server-side validation is required. - Using the persistence entity as the request type. Binding request JSON directly to a JPA entity ties your API rules to your storage model and can allow clients to set fields they should not. Use a separate request DTO (data transfer object), a class or record that exists only to carry request data.
- Returning 500 for bad input. If the client caused the problem, answer with 400 so the client knows to change its request.
- Reporting one error at a time. Collect all field violations and return them together.
- Leaking internals in messages. Error text should describe the rule that failed, not stack traces or class names.
What the rest of the tutorial builds
This chapter set the motivation. The following chapters build the solution step by step:
- Add the validation starter and declare constraints on a request DTO.
- Trigger validation with
@Validand see what happens on failure. - Return structured 400 responses with
@RestControllerAdviceandProblemDetail. - Validate path variables, query parameters, nested objects, and collections.
- Write custom constraints, use validation groups, and apply cross-field rules.
- Customize messages, validate outside the controller, and test all of it.
Summary
Spring converts JSON into objects but does not judge whether the values make sense. Without validation, bad input produces 500 errors, corrupt data, wasted work, and inconsistent responses. Manual checks fix some of this but scatter the rules and do not scale. Declarative validation attaches rules to the data, reports all violations at once, and keeps controllers focused. Boundary validation handles what can be decided from the request alone. State-dependent rules belong in the service layer, and integrity guarantees belong in the database.
Exercise
A client posts a user with an email that is already registered. Should you catch this with a constraint annotation on the request DTO? Explain which layers should be involved.
Show answer
No. A DTO constraint can only look at the request itself, and it cannot know what is stored in the database. The service layer should check for an existing email to give a clear error, and a database UNIQUE constraint should back it up because two concurrent requests can both pass the check. The service should translate the unique-constraint failure into a client error such as 409 Conflict.
Exercise
The UnsafeUserController in this chapter returns 500 when the name is missing. Name the cause, and name two problems that remain even if you fix it with manual if-checks in the method body.
Show answer
The cause is that the body is parsed into a record with a null name, and the method calls toUpperCase() on null, which throws a NullPointerException. Manual checks leave several problems: the rules are mixed into the handler logic and duplicated across endpoints, the method returns on the first failure so clients see one error at a time, and message styles vary between developers. Any two of these is a correct answer.