Spring Boot REST API Validation – Complete Guide (All Annotations)
Validation is a core responsibility of any REST API. Spring Boot provides powerful validation support using Bean Validation, but most articles explain only 2–3 annotations. This guide covers ALL commonly used validation annotations, with best practices and interview insights.
- How validation works internally in Spring Boot
- All important validation annotations with examples
- DTO-based validation best practices
- How to return clean validation error responses
- Common fresher mistakes interviewers catch
1️⃣ How Validation Works in Spring Boot
Spring Boot uses Bean Validation (JSR 380), with Hibernate Validator as the default implementation.
Client Request ↓ @RestController ↓ @Valid triggers validation ↓ Validation fails → Exception ↓ @RestControllerAdvice ↓ Error Response
2️⃣ Required Dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
3️⃣ Always Use DTOs for Validation
Never validate directly on JPA entities. Use Request DTOs.
public class UserRequest {
@NotBlank
private String name;
@Email
private String email;
@Min(18)
private Integer age;
}
Why DTOs?
- API contract control
- No DB leakage
- Better versioning
Related: Spring Boot + JPA Basics for Freshers
4️⃣ Core Validation Annotations (Most Used)
| Annotation | Used For |
|---|---|
| @NotNull | Value must not be null |
| @NotEmpty | Not null and not empty (String, Collection) |
| @NotBlank | Not null, not empty, trimmed length > 0 (String) |
| @Size | Min/max length for String/Collection |
5️⃣ Numeric Validation Annotations
| Annotation | Description |
|---|---|
| @Min | Minimum numeric value |
| @Max | Maximum numeric value |
| @Positive | Value must be > 0 |
| @PositiveOrZero | Value ≥ 0 |
| @Negative | Value < 0 |
| @NegativeOrZero | Value ≤ 0 |
6️⃣ String Pattern & Format Validation
| Annotation | Use Case |
|---|---|
| Email format | |
| @Pattern | Regex validation |
@Pattern(
regexp = "^[0-9]{10}$",
message = "Mobile number must be 10 digits"
)
private String mobile;
7️⃣ Date & Time Validation
| Annotation | Purpose |
|---|---|
| @Past | Date must be in the past |
| @PastOrPresent | Past or present |
| @Future | Date must be in the future |
| @FutureOrPresent | Future or present |
8️⃣ Using @Valid in Controller
@PostMapping("/users")
public String createUser(
@Valid @RequestBody UserRequest request) {
return "User created";
}
If validation fails:
- Method is NOT executed
- Exception is thrown automatically
Related: Spring Boot Annotations Explained
9️⃣ Validating Path Variables & Request Params
@GetMapping("/{id}")
public String getUser(
@PathVariable @Min(1) Long id) {
return "User ID " + id;
}
๐ Handling Validation Errors Cleanly
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
public Map<String, String> handleValidation(
MethodArgumentNotValidException ex) {
Map<String, String> errors = new HashMap<>();
ex.getBindingResult().getFieldErrors()
.forEach(error ->
errors.put(error.getField(), error.getDefaultMessage())
);
return errors;
}
}
Learn error handling in depth: Global Exception Handling in Spring Boot
11️⃣ Common Fresher Mistakes (Interview Gold)
- Forgetting @Valid in controller
- Validating JPA entities directly
- Not handling validation errors globally
- Using wrong annotation (@NotNull vs @NotBlank)
Final Summary
- Validation protects APIs from bad input
- @Valid triggers Bean Validation
- DTO-based validation is best practice
- Clean errors improve API quality
Mastering validation makes you look like a production-ready Spring Boot fresher.
๐งพ Master Validation in Spring Boot REST APIs
Proper validation is essential for building safe, reliable, and production-ready REST APIs. Strengthen your Spring Boot knowledge by exploring these closely related validation and REST topics.
✅ Custom Validation Annotations in Spring Boot
Learn how to create reusable custom validators when built-in annotations are not enough.
๐จ Spring Boot Global Exception Handling
Handle validation errors consistently
using @ControllerAdvice.
๐ท️ Spring Boot Annotations for REST APIs
Understand commonly used Spring annotations for building clean REST controllers.
๐ฏ Controller vs RestController
Learn the difference between MVC and REST controllers and how validation fits in.
๐ Spring Boot Interview Questions (Freshers)
Common interview questions covering validation, REST APIs, and Spring Boot basics.
๐ผ Spring Boot Interview Questions (2–5 Years)
Interview topics including validation strategies, error handling, and REST best practices.