what does your spring boot api say when a request is wrong?
learn input validation, business rules and problem details in spring boot through a small price calculation example.
picture a form with a quantity field, a discount field and a calculate button. returning a total is easy when every value is correct. the interesting part is what happens when a field is missing or when two individually valid values produce an invalid result. a good backend does not make the client guess; it explains which input was rejected and why.
published: updated:

in this article
start with the boundary of the request
our example is a price preview endpoint inside a single spring boot application. the server holds a fixed unit price of 100 try; the client sends only a quantity and a discount percentage. we are not creating an order, taking payment or saving data yet. that keeps the focus on one question: should this request be accepted?
the first group of rules is simple: quantity must be between 1 and 100, discount must be between 0 and 50 and both fields must be supplied. the second rule describes a relationship: orders below 10 items cannot receive a discount above 20 percent. we will declare the first group on the request model and check the second before calculating the total. this separation shows a reader immediately what is missing data and what is a business decision.
a small example you can run
create a project with spring initializr by choosing “spring boot” and “java 25”. make sure the generated project uses spring boot 4; the example below runs unchanged on java 25. add the files to the source folder and start the application with “mvn spring-boot:run”.
the request model is a record. jakarta validation constraints such as @NotNull, @Min, @Max and @DecimalMin produce a 400 response when body validation fails. we use a wrapper type for the discount so that a missing value stays distinguishable from zero: zero is a valid discount, while leaving the field out is not.
package com.example.quotes;
import java.math.BigDecimal;
import java.math.RoundingMode;
import jakarta.validation.Valid;
import jakarta.validation.constraints.DecimalMax;
import jakarta.validation.constraints.DecimalMin;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestController
@RequestMapping("/api/quotes")
class QuoteController {
private static final BigDecimal UNIT_PRICE = new BigDecimal("100.00");
private static final BigDecimal MAX_DISCOUNT_BELOW_TEN = new BigDecimal("20");
@PostMapping("/preview")
QuotePreview preview(@Valid @RequestBody QuoteRequest request) {
if (request.quantity() < 10
&& request.discountPercent().compareTo(MAX_DISCOUNT_BELOW_TEN) > 0) {
throw new DiscountRuleViolation("Orders below 10 items allow at most 20% discount.");
}
BigDecimal total = request.quantity()
.multiply(UNIT_PRICE)
.multiply(BigDecimal.ONE.subtract(request.discountPercent().movePointLeft(2)))
.setScale(2, RoundingMode.HALF_UP);
return new QuotePreview(total, "TRY");
}
}
record QuoteRequest(
@NotNull @Min(1) @Max(100) Integer quantity,
@NotNull @DecimalMin("0") @DecimalMax("50") BigDecimal discountPercent) {
}
record QuotePreview(BigDecimal total, String currency) {
}
class DiscountRuleViolation extends RuntimeException {
DiscountRuleViolation(String message) {
super(message);
}
}
@RestControllerAdvice
class QuoteProblemHandler {
@ExceptionHandler(DiscountRuleViolation.class)
ProblemDetail onDiscountRule(DiscountRuleViolation exception) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
HttpStatus.BAD_REQUEST, exception.getMessage());
problem.setTitle("Discount rule violated");
problem.setProperty("code", "discount_rule_violated");
problem.setProperty("field", "discountPercent");
return problem;
}
}valid fields can still form an invalid request
a quantity of 2 and a discount of 30 each pass their range checks. together they violate the business rule. annotations alone cannot express that relationship. the example checks it with an explicit condition, throws a dedicated exception type and lets a @RestControllerAdvice convert it into problem details. the client can then show the explanation next to the discount input.
keeping the rule inside a small controller makes the flow easy to follow. once another entry point needs the same calculation, move the shared rule into an application or domain component. mapping the outcome to an http response can stay in the controller. validation also does not grant permission: a real sales application must independently verify who may apply a discount and what the current price is on the server.
give the client a response it can work with
problem details provides a common shape for error responses. status carries the http status, title gives a short summary and detail explains this particular occurrence. in spring boot 4 the spring.mvc.problemdetails.enabled setting converts framework errors into the same shape. validation responses add an errors extension that pairs field names with messages. define the contract your client actually needs instead of assuming every member will appear on every response.
in this example both range failures and the discount rule return 400. that is a choice for this api contract, not a rule that every business failure must return 400. a successful calculation returns 200. avoid making client decisions from the wording of a message alone, because the text may change or be translated. use the status and the field keys; add documented stable error codes when distinct business failures need different handling.
for unexpected failures use a central handler instead of wrapping every controller in a broad try/catch. never send exception messages, connection details or stack traces to the client. keep server-side records that let you correlate the request, without indiscriminately logging passwords, tokens or entire request bodies.
exercise more than the happy path
send the request below from an editor that supports .http files. two items with a 10 percent discount produce a total of 180 try. the calculation uses BigDecimal and explicitly rounds to two places with HALF_UP. in a real application the currency and the rounding policy are business requirements of their own.
POST http://localhost:8080/api/quotes/preview
Content-Type: application/json
Accept: application/json
{ "quantity": 2, "discountPercent": 10 }what the boundary cases tell us
send an empty json object first and expect 400 for the required fields. set the quantity to 0; the range check should reject it. quantity 2 with discount 30 should fail the business rule. quantity 10 with discount 30 should return 200 and a total of 700 try. a discount of 0 must remain valid. the requests look similar, but each one exercises a different behaviour.
when you automate these checks, run them through the real http pipeline. calling the controller method directly does not prove that the validation chain and the advice ordering work. @WebMvcTest isolates the web layer. a full stack test can start postgresql with testcontainers. assert the status, the response fields and the calculated value; do not mistake a punctuation change in a message for a broken business rule.
before writing the next endpoint, answer three questions: which data is required, which combinations are invalid and how can the client correct the request? once those are clear, validation stops being a random collection of if blocks and becomes a readable part of the api.
frequently asked questions
- how do i validate requests in spring boot?
- define the body as a record and add jakarta validation constraints such as @notnull, @min, @max and @decimalmin. when the controller validates the body with @valid, a constraint violation becomes a 400 problem details response. the validation chain is only proven when it runs through a real http request.
- should i keep business rules separate from field constraints?
- yes. the range of a single field is a field constraint; the relationship between fields is a business rule. a rule such as “orders below 10 items allow at most 20% discount” is enforced by a separate check before the calculation, not by a model annotation. that split keeps missing data apart from an invalid business decision.
- how should i return validation errors to the client?
- use the problem details shape: the status, a short title, an explanation of this occurrence and an errors extension that pairs field names with their messages. clients should decide from the status and the field keys rather than from message wording, and distinct business failures deserve documented, stable error codes.