0

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.

2 Answers 2

1

Written a small app using spring boot 3.0.0 and JDK 19 and everything worked perfectly fine for me. Here are the snippets

@RestController
public class BookController {
    @PostMapping(path = "/books", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> createBook(@Valid @RequestBody CreateBookRequest request){
        if(request.getPrice().value() != null){
            return ResponseEntity.ok().body("Good request");
        }
        return ResponseEntity.badRequest().body("Check the request");
    }
}


import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
public class CreateBookRequest {
    @Valid
    @NotNull
    Price price;
    public Price getPrice() {
        return price;
    }
    public void setPrice(Price price) {
        this.price = price;
    }
}


public record Price(
        @NotNull
        BigDecimal value
) {
    public Price(BigDecimal value){
        this.value = value;
        }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for answer, for me it was the missing dependencyu.
0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.