Springboot
RequestBody
validation
Java
REST API

Springboot - validate RequestBody

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Introduction

Validating @RequestBody in Spring Boot protects API boundaries and keeps invalid data out of business logic. The framework supports this cleanly through Bean Validation annotations and controller method validation. A strong setup includes field rules, centralized error formatting, and tests that verify failure behavior.

Core Sections

Add validation annotations to request models

Annotate request fields with constraints that match domain rules. Keep validation close to the DTO so API requirements are obvious during code review.

java
1import jakarta.validation.constraints.Email;
2import jakarta.validation.constraints.NotBlank;
3import jakarta.validation.constraints.Size;
4
5public class CreateUserRequest {
6    @NotBlank
7    @Size(min = 2, max = 80)
8    private String name;
9
10    @NotBlank
11    @Email
12    private String email;
13
14    @Size(min = 8, max = 64)
15    private String password;
16
17    public String getName() { return name; }
18    public void setName(String name) { this.name = name; }
19    public String getEmail() { return email; }
20    public void setEmail(String email) { this.email = email; }
21    public String getPassword() { return password; }
22    public void setPassword(String password) { this.password = password; }
23}

These constraints run before service code executes. Early rejection reduces noisy null checks in business methods and makes API behavior more predictable.

Trigger validation in controllers

Add @Valid to the @RequestBody parameter so Spring performs validation automatically. Return a typed response object for clear contract boundaries.

java
1import jakarta.validation.Valid;
2import org.springframework.http.ResponseEntity;
3import org.springframework.web.bind.annotation.PostMapping;
4import org.springframework.web.bind.annotation.RequestBody;
5import org.springframework.web.bind.annotation.RestController;
6
7@RestController
8public class UserController {
9
10    @PostMapping("/users")
11    public ResponseEntity<String> createUser(@Valid @RequestBody CreateUserRequest request) {
12        return ResponseEntity.ok("created:" + request.getEmail());
13    }
14}

Without @Valid, annotations on the DTO are ignored and invalid payloads can pass through silently. This is one of the most common causes of inconsistent API validation.

Standardize validation error responses

Use @RestControllerAdvice to convert validation exceptions into consistent JSON error payloads. Clients can then parse failures reliably and show actionable messages.

java
1import org.springframework.http.ResponseEntity;
2import org.springframework.web.bind.MethodArgumentNotValidException;
3import org.springframework.web.bind.annotation.ExceptionHandler;
4import org.springframework.web.bind.annotation.RestControllerAdvice;
5
6import java.util.HashMap;
7import java.util.Map;
8
9@RestControllerAdvice
10public class ValidationErrorHandler {
11
12    @ExceptionHandler(MethodArgumentNotValidException.class)
13    public ResponseEntity<Map<String, String>> handle(MethodArgumentNotValidException ex) {
14        Map<String, String> errors = new HashMap<>();
15        ex.getBindingResult().getFieldErrors().forEach(err ->
16            errors.put(err.getField(), err.getDefaultMessage())
17        );
18        return ResponseEntity.badRequest().body(errors);
19    }
20}

Consistent error shape is critical for frontend and integration clients. It also improves observability because logs and metrics can group validation failures by field and rule.

Verification and operational checks

After implementing the fix, verify behavior with a short, repeatable check list. Confirm the happy path first, then test malformed input, missing dependencies, and permission boundaries. This sequence catches most regressions before they reach production.

When the workflow is part of automation, log inputs and outputs at a useful level. Structured logs with request identifiers make failures easier to trace and reduce debugging time during incidents. Keep the runbook close to the code so updates remain synchronized with implementation changes.

Practical rollout pattern

A reliable way to ship this pattern is to introduce one small change, measure behavior, then expand scope. Start with a constrained environment such as a local test dataset or one noncritical endpoint. Confirm logs, metrics, and error messages are understandable by someone who did not author the change. That validation step is where many teams discover unclear assumptions.

After confidence is established, document the final operating procedure in concise steps. Include exact commands, expected outputs, and a short recovery plan for common failures. Clear operational guidance reduces repeated investigation work and shortens incident response time. It also makes onboarding easier because new contributors can follow a known path instead of inferring hidden workflow details from scattered code comments.

Common Pitfalls

  • Forgetting @Valid on controller parameters and bypassing DTO rules.
  • Putting constraints on entity classes instead of request DTOs.
  • Returning inconsistent validation error formats across endpoints.
  • Allowing blank strings when domain logic requires normalized values.
  • Skipping negative tests for malformed JSON and missing fields.

Summary

  • Define validation rules directly on request DTO fields.
  • Use @Valid with @RequestBody to trigger checks.
  • Centralize error mapping with @RestControllerAdvice.
  • Keep response formats stable for API consumers.
  • Add test coverage for both valid and invalid payloads.

Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.