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:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

2. Create a DTO with Validation Annotations

public class UserRequest {

    @NotBlank(message = "Name is required")
    private String name;

    @Email(message = "Invalid email format")
    private String email;

    @Min(value = 18, message = "Age must be at least 18")
    private int age;

    // Getters and Setters
}


3. Validate with @Valid in Controller

@RestController
@RequestMapping("/api/users")
public class UserController {

    @PostMapping
    public ResponseEntity<String> createUser(@Valid @RequestBody UserRequest request) {
        // If validation passes
        return ResponseEntity.ok("User created!");
    }
}

 

Spring automatically returns 400 Bad Request if validation fails.


4. Handle Validation Errors (Custom Error Response)

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Map<String, String>> handleValidation(MethodArgumentNotValidException ex) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getFieldErrors().forEach(error ->
            errors.put(error.getField(), error.getDefaultMessage())
        );
        return ResponseEntity.badRequest().body(errors);
    }
}


🔍 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 @Validated on class-level if you want to validate method parameters (e.g., in service layer).
Back to blog

Leave a comment