Spring Boot REST API: Complete Guide with Validation and Exception Handling

Building robust and production-ready REST APIs requires more than just mapping endpoints. Developers need to ensure proper request validation, handle exceptions gracefully, and return standardized error responses to clients.

This guide covers how to build a complete Spring Boot REST API featuring Jakarta Bean Validation, custom exception handling, and best practices for modern backend development.

Project Dependencies and Setup

To build a REST API with validation in Spring Boot, ensure your build configuration includes spring-boot-starter-web and spring-boot-starter-validation.

XML
Required Maven dependencies for Spring Boot Web and Validation.
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-validation</artifactId>
    </dependency>
</dependencies>

DTOs and Jakarta Validation Annotations

Using Data Transfer Objects (DTOs) decoupled from database entities prevents over-posting attacks and allows you to apply validation constraints cleanly using annotations like @NotBlank, @Email, and @Size.

Java
User creation DTO with validation annotations.
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;

public class UserRequestDto {

    @NotBlank(message = "Username cannot be blank")
    @Size(min = 3, max = 50, message = "Username must be between 3 and 50 characters")
    private String username;

    @NotBlank(message = "Email cannot be blank")
    @Email(message = "Invalid email format")
    private String email;

    // Getters and Setters
    public String getUsername() { return username; }
    public void setUsername(String username) { this.username = username; }
    public String getEmail() { return email; }
    public void setEmail(String email) { this.email = email; }
}

To trigger validation when handling requests in your controller, annotate the request body parameter with @Valid.

Global Exception Handling with @ControllerAdvice

Instead of scattering try-catch blocks across controllers, Spring Boot provides @RestControllerAdvice to handle exceptions globally and return standardized error payloads.

Java
Global exception handler capturing validation errors and custom exceptions.
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class আনন্দের
    public ResponseEntity<Map<String, Object>> handleValidationExceptions(MethodArgumentNotValidException ex) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getAllErrors().forEach(error -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });

        Map<String, Object> response = new HashMap<>();
        response.put("timestamp", LocalDateTime.now());
        response.put("status", HttpStatus.BAD_REQUEST.value());
        response.put("errors", errors);

        return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
    }
}

Summary

Structuring your Spring Boot application with dedicated DTOs, Jakarta validation constraints, and global exception handlers ensures clean separation of concerns and consistent error responses across your entire API.