I have POST endpoint that creates for example Books, in CreateBookRequest class I have another nested class/record that holds BigDecimal price. I want to secure this endpoint so json's (given below) will be validated as BAD_REQUEST (with custom exception will be great).
My structure:
@PostMapping(path = "/books", produces = MediaType.APPLICATION_JSON_VALUE)
ResponseEntity<Void> createBook(@Valid @RequestBody CreateBookRequest request);
public record CreateBookRequest(
@Valid
@NotNull
Price price
) {
}
public record Price(
@NotNull
BigDecimal value
) {
}
Correct JSON:
{
"price": {
"value": 60.00
}
}
Invaluid JSON's:
{
"price": null
}
{
"price": ""
}
{}
My structure with validation annotations does not work at this time, any help would be appreciated, thanks in advance.
In my case code was fine, the missing part was the dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>