Input Validation in REST API (Spring Boot)
Validating inputs for a REST API in Spring Boot is typically done using Java Bean Validation (JSR-380) with annotations like @NotNull, @Size, @Email, etc., and the @Valid or @Validated annotation in controllers.
✅ Step-by-Step: Input Validation in REST API (Spring Boot)
1. Add Dependency (if not already)
Spring Boot Starter Web includes it, but to be explicit:
2. Create a DTO with Validation Annotations
3. Validate with @Valid in Controller
Spring automatically returns
400 Bad Requestif validation fails.
4. Handle Validation Errors (Custom Error Response)
🔍 Common Annotations
| Annotation | Purpose |
|---|---|
@NotNull |
Must not be null |
@NotBlank |
Not null and not empty |
@Size(min, max) |
Length of string/collection |
@Email |
Valid email format |
@Min/@Max
|
Number limits |
@Pattern |
Regex matching |
💡 Tip:
- Use
@Validatedon class-level if you want to validate method parameters (e.g., in service layer).