Sub topic 1
Why validate at the API boundary
A REST endpoint accepts data from clients you don't control. This chapter explains why you should check that data as it enters your application, and what goes wrong when you don't. Later chapters show how to do the checking with Jakarta Bean Validation.
Prerequisites
This chapter assumes you have:
- Java basics, including records and annotations.
- Experience building a simple REST controller with Spring MVC.
- Familiarity with Maven or Gradle dependencies.
- A working knowledge of HTTP status codes and JSON bodies.
The API boundary
The API boundary is the point where outside data enters your code. In a Spring MVC application, this is the controller method. Everything before it, such as the network, the JSON parser, and the client, is outside your control. Everything after it, such as services, repositories, and the database, expects well-formed data.
Spring's JSON binding checks only the shape of a request. It confirms that age is a number, not a string. It does not check that the number makes sense. A missing field becomes null, an empty name is still a valid string, and an age of -5 is still a valid integer.
What goes wrong without validation
Consider a controller that trusts its input:
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;
record CreateUserRequest(String name, String email, Integer age) {
}
@RestController
@RequestMapping("/users")
public class UserController {
@PostMapping
public ResponseEntity<Void> create(@RequestBody CreateUserRequest request) {
String initial = request.name().substring(0, 1).toUpperCase();
System.out.println("Creating user starting with " + initial);
return ResponseEntity.status(HttpStatus.CREATED).build();
}
}Send {"email": "[email protected]", "age": 30} and name is null. The call to request.name() returns null, and substring throws a NullPointerException. The client receives a 500 Internal Server Error, which tells it the server is broken when the client actually sent bad input.
Send {"name": "", ...} instead and you get a StringIndexOutOfBoundsException, again as a 500.
Costs of skipping validation
- Wrong status codes. Client mistakes should return
400 Bad Request. A 500 pollutes your error metrics and triggers alerts for problems that aren't yours. - Bad data in storage. If nothing stops an empty name, it can reach the database. Cleaning it up later is far more expensive than rejecting it.
- Late failures. An invalid value may travel through several layers before something breaks. The stack trace then points far from the real cause.
- Security exposure. Unbounded string lengths, negative quantities, and unexpected values are common starting points for abuse.
- Unhelpful feedback. Clients cannot fix a request if the response doesn't say which field was wrong.
Validate once, early, declaratively
Hand-written if checks at the top of every method work, but they repeat across controllers and are easy to forget. Bean Validation takes a different approach. You declare rules as annotations on the data class, and the framework enforces them before your method body runs.
This gives you three benefits:
- Rules live next to the data they describe, so the DTO documents its own contract.
- Services can assume their input is well-formed.
- One shared exception handler can turn every failure into a consistent error response.
Validation at the boundary does not replace all other checks. Rules that need a database lookup, such as "this email is not already registered", belong in the service layer. A later chapter covers that split.
Exercise
A client sends a JSON body with "age": "abc" to an endpoint that expects an Integer. A second client sends "age": -5. Which of these two problems does Spring's JSON binding catch on its own, and which needs validation rules?
Show answer
JSON binding rejects "abc" because it cannot convert the text to an Integer, so that request fails before your method runs. The value -5 is a valid Integer, so binding accepts it. Only a validation rule, such as a minimum-value constraint, can reject it.