Bird
Raised Fist0
Spring Bootframework~10 mins

@Valid annotation on request body in Spring Boot - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - @Valid annotation on request body
Client sends HTTP request with JSON body
Spring Boot Controller receives request
@Valid triggers validation on request body object
Validation passes
Response sent back to client
When a client sends data, Spring Boot uses @Valid to check the data. If valid, the controller runs. If not, an error response is sent.
Execution Sample
Spring Boot
public ResponseEntity<String> createUser(@Valid @RequestBody User user) {
    return ResponseEntity.ok("User created");
}
This code checks the User object sent in the request body. If valid, it returns success.
Execution Table
StepActionInput DataValidation ResultController BehaviorResponse
1Receive HTTP POST with JSON body{"name":"Alice","age":25}Not yet validatedWaiting for validationNo response yet
2@Valid triggers validation on User object{"name":"Alice","age":25}Passes all constraintsController method executesNo response yet
3Controller returns success messageUser object validN/AReturns ResponseEntity.okHTTP 200 OK with 'User created'
4Receive HTTP POST with invalid JSON body{"name":"","age":-5}Not yet validatedWaiting for validationNo response yet
5@Valid triggers validation on User object{"name":"","age":-5}Fails: name blank, age negativeController method skippedSpring returns HTTP 400 Bad Request with error details
💡 Execution stops after sending HTTP response based on validation result
Variable Tracker
VariableStartAfter Step 2After Step 5Final
user.namenull"Alice"""""
user.agenull25-5-5
validationResultnullvalidinvalidinvalid
response.statusnull200 OK400 Bad Request400 Bad Request
Key Moments - 2 Insights
Why does the controller method not run when validation fails?
Because @Valid triggers validation before the method runs. If validation fails (see step 5 in execution_table), Spring stops and sends an error response instead.
What happens if the request body is missing required fields?
Validation fails since required constraints are not met. The execution_table row 5 shows validation failure and Spring returns 400 Bad Request.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the validation result at step 2?
ANot yet validated
BFails due to missing fields
CPasses all constraints
DController skipped
💡 Hint
Check the 'Validation Result' column at step 2 in execution_table
At which step does Spring return a 400 Bad Request response?
AStep 5
BStep 3
CStep 1
DStep 2
💡 Hint
Look at the 'Response' column in execution_table for HTTP 400 Bad Request
If the user.age was 30 instead of -5 in step 5, what would change?
AValidation would still fail
BValidation would pass and controller runs
CResponse would be 400 Bad Request
DNo change in validation result
💡 Hint
Refer to variable_tracker for user.age values and validation results
Concept Snapshot
@Valid on @RequestBody triggers automatic validation of incoming data.
If data is valid, controller method runs normally.
If invalid, Spring returns 400 Bad Request with errors.
Use validation annotations on model fields (e.g., @NotBlank, @Min).
This helps catch bad input early and keeps code clean.
Full Transcript
When a client sends a request with data, Spring Boot uses the @Valid annotation on the request body to check if the data meets rules like not empty or minimum values. If the data is good, the controller method runs and sends a success response. If the data is bad, Spring stops the method and sends back an error message with status 400. This process helps keep the app safe and user-friendly by catching mistakes early.

Practice

(1/5)
1. What is the main purpose of using the @Valid annotation on a @RequestBody parameter in a Spring Boot controller?
easy
A. To automatically check if the incoming request data meets the validation rules defined in the data class.
B. To convert the request body into a JSON string.
C. To log the request body content for debugging.
D. To cache the request body for faster access.

Solution

  1. Step 1: Understand the role of @Valid

    The @Valid annotation triggers validation of the request body object based on constraints defined in its class.
  2. Step 2: Connect validation to request handling

    When placed before @RequestBody, it ensures the data is checked before the controller method uses it.
  3. Final Answer:

    To automatically check if the incoming request data meets the validation rules defined in the data class. -> Option A
  4. Quick Check:

    @Valid validates input data [OK]
Hint: Remember: @Valid checks data correctness before method runs [OK]
Common Mistakes:
  • Thinking @Valid converts or logs data
  • Placing @Valid after @RequestBody
  • Assuming @Valid caches data
2. Which of the following is the correct way to use @Valid in a Spring Boot controller method parameter?
easy
A. public ResponseEntity create(@RequestBody User user @Valid) { ... }
B. public ResponseEntity create(@Valid User user @RequestBody) { ... }
C. public ResponseEntity create(@Valid @RequestBody User user) { ... }
D. public ResponseEntity create(User user @Valid @RequestBody) { ... }

Solution

  1. Step 1: Recall annotation order for parameters

    In Spring Boot, @Valid must come before @RequestBody on the same parameter.
  2. Step 2: Check each option's syntax

    Only public ResponseEntity create(@Valid @RequestBody User user) { ... } correctly places @Valid before @RequestBody on the parameter.
  3. Final Answer:

    public ResponseEntity create(@Valid @RequestBody User user) { ... } -> Option C
  4. Quick Check:

    Correct annotation order = public ResponseEntity create(@Valid @RequestBody User user) { ... } [OK]
Hint: Put @Valid before @RequestBody on the same parameter [OK]
Common Mistakes:
  • Placing @Valid after @RequestBody
  • Separating annotations incorrectly
  • Using @Valid without @RequestBody
3. Given the following controller method and data class, what happens when a POST request sends an empty JSON object {}?
public record User(@NotBlank String name, @Min(18) int age) {}
@PostMapping("/users")
public ResponseEntity<String> addUser(@Valid @RequestBody User user) {
    return ResponseEntity.ok("User added");
}
medium
A. The request succeeds but 'age' defaults to 0.
B. The request succeeds and returns 'User added'.
C. The request fails because @Valid is ignored on records.
D. The request fails validation because 'name' is blank and 'age' is missing.

Solution

  1. Step 1: Analyze validation constraints on User record

    @NotBlank requires 'name' to be non-empty; @Min(18) requires 'age' to be at least 18.
  2. Step 2: Consider empty JSON input effects

    Empty JSON means 'name' and 'age' are missing, so validation fails for both fields.
  3. Final Answer:

    The request fails validation because 'name' is blank and 'age' is missing. -> Option D
  4. Quick Check:

    Missing required fields cause validation failure [OK]
Hint: Empty JSON fails @NotBlank and @Min validations [OK]
Common Mistakes:
  • Assuming missing fields pass validation
  • Thinking @Valid ignores records
  • Assuming default values apply automatically
4. You have this controller method:
@PostMapping("/register")
public ResponseEntity<String> registerUser(@RequestBody @Valid User user) {
    return ResponseEntity.ok("Registered");
}
But when you send invalid data, no validation errors occur and the method runs normally. What is the most likely cause?
medium
A. Missing @Validated annotation on the controller class or configuration.
B. The User class does not have any validation annotations.
C. The @Valid annotation is placed after @RequestBody.
D. Spring Boot does not support validation on request bodies.

Solution

  1. Step 1: Check if User class has validation rules

    If the User class lacks validation annotations like @NotNull, @NotBlank, etc., @Valid has nothing to check.
  2. Step 2: Understand validation behavior

    Without constraints, validation passes silently, so the method runs normally even with invalid data.
  3. Final Answer:

    The User class does not have any validation annotations. -> Option B
  4. Quick Check:

    No constraints = no validation errors [OK]
Hint: Validation needs annotations in the data class [OK]
Common Mistakes:
  • Assuming @Validated is always required
  • Thinking annotation order causes no validation
  • Believing Spring Boot disables validation by default
5. You want to create a Spring Boot API that accepts a JSON request body for a Product with fields name (required, not blank) and price (required, positive number). Which of the following code snippets correctly applies @Valid and validation annotations to ensure invalid data is rejected automatically?
hard
A. public record Product(@NotBlank String name, @Positive double price) {} @PostMapping("/products") public ResponseEntity<String> addProduct(@Valid @RequestBody Product product) { return ResponseEntity.ok("Product added"); }
B. public class Product { public String name; public double price; } @PostMapping("/products") public ResponseEntity<String> addProduct(@RequestBody Product product) { return ResponseEntity.ok("Product added"); }
C. public record Product(String name, double price) {} @PostMapping("/products") public ResponseEntity<String> addProduct(@RequestBody @Valid Product product) { return ResponseEntity.ok("Product added"); }
D. public record Product(@NotNull String name, @Min(1) double price) {} @PostMapping("/products") public ResponseEntity<String> addProduct(@RequestBody Product product) { return ResponseEntity.ok("Product added"); }

Solution

  1. Step 1: Identify correct validation annotations

    @NotBlank ensures 'name' is not empty; @Positive ensures 'price' is greater than zero.
  2. Step 2: Check usage of @Valid and @RequestBody

    public record Product(@NotBlank String name, @Positive double price) {} @PostMapping("/products") public ResponseEntity<String> addProduct(@Valid @RequestBody Product product) { return ResponseEntity.ok("Product added"); } correctly places @Valid before @RequestBody in the controller method parameter.
  3. Step 3: Verify other options

    public class Product { public String name; public double price; } @PostMapping("/products") public ResponseEntity<String> addProduct(@RequestBody Product product) { return ResponseEntity.ok("Product added"); } lacks validation annotations and @Valid. public record Product(String name, double price) {} @PostMapping("/products") public ResponseEntity<String> addProduct(@RequestBody @Valid Product product) { return ResponseEntity.ok("Product added"); } misses validation annotations. public record Product(@NotNull String name, @Min(1) double price) {} @PostMapping("/products") public ResponseEntity<String> addProduct(@RequestBody Product product) { return ResponseEntity.ok("Product added"); } uses @Min(1) on a double (should use @Positive) and misses @Valid.
  4. Final Answer:

    public record Product(@NotBlank String name, @Positive double price) {} @PostMapping("/products") public ResponseEntity<String> addProduct(@Valid @RequestBody Product product) { return ResponseEntity.ok("Product added"); } -> Option A
  5. Quick Check:

    Use @Valid + proper annotations = public record Product(@NotBlank String name, @Positive double price) {} @PostMapping("/products") public ResponseEntity<String> addProduct(@Valid @RequestBody Product product) { return ResponseEntity.ok("Product added"); } [OK]
Hint: Use @Valid + @NotBlank and @Positive for required fields [OK]
Common Mistakes:
  • Omitting @Valid in controller method
  • Using wrong validation annotations for types
  • Not annotating fields in data class