AI Hints
Home›Spring Boot Tutorial›Why Validate, Bean Validation and @Valid
Spring Boot · Lesson 73 of 120

Why Validate

Never trust input.

⏱ 2 min read▶ Video at 1:38:29🎓 Free
Watch this lesson in the Spring Boot courseWatch on YouTube ↗Full Spring Boot course

Clients make mistakes. Some send empty titles, or negative prices. A few might even send bad data on purpose. Our API must check everything that comes in.

  • Clients make mistakes
  • Some on purpose
  • Check everything

Accepting junk

This controller saves whatever it receives. Here, a book with no title, no author, and a negative price. Run it. The junk is accepted, without a single complaint. In a real shop, that would end up in the database.

BookController.javajava
@RestController
public class BookController {

    @PostMapping("/books")
    public String add(@RequestBody NewBook book) {
        return "Saved: " + book;
    }
}
Output
Saved: NewBook[title=, author=, price=-5.0]
Also uses NewBook.java
public record NewBook(String title, String author, double price) {}
Also uses _curl.sh
curl --json '{"title":"","author":"","price":-5}' localhost:8080/books

Bad input we must catch

Required fields can be missing, or blank. Numbers can be negative, or far too large. Text can be too long. And emails, or dates, can have the wrong format.

ProblemExample
Missing / blank"title": ""
Out of range"price": -5
Too longa 10,000-letter title
Wrong format"email": "not-an-email"

Where to check

Check input at the edge, as soon as it arrives in the controller. Then services can trust their data. Answer bad input with four hundred, bad request. And tell the client exactly what was wrong, so they can fix it.

keyvalue
Whereat the edge: controllers
Thenservices trust the data
Status400 Bad Request
Messagesay what was wrong

Summary

Never trust input. Check it as it arrives, and answer mistakes with four hundred, and a clear message. Next, bean validation.

Key takeaways
  • Never trust input
  • Check at the edge
  • 400 + a clear message
Next up: Bean Validation — rules as annotations