springspring-bootspring-restcontroller

Spring Rest Controller not able to validate path variable when request body is also passed in addition to path variable


I've a rest controller and one of the endpoint looks like this:

@PostMapping(value = "/myapi/{id}", produces = APPLICATION_JSON_VALUE, consumes = APPLICATION_JSON_VALUE)
public ResponseEntity<MyEntity> myApi(
          @Valid @PathVariable("id") @NotBlank String id,
          @Valid @RequestBody MyRequestPayload myRequestPayload) throws Exception)
{
  LOGGER.info("Id is {}",id);
  ...............
  .........................
  .............................
}

For some reason, when I call the API with an empty or null path variable and a request payload, the path variable is not failing the validation and the control comes inside the method block. What am I doing wrong? Kindly advise.


Solution

  • @Valid validates complex objects, containing fields annotated with constraint annotations.

    For this case, you need to use @Validated:

    The @Validated annotation is a class-level annotation that we can use to tell Spring to validate parameters that are passed into a method of the annotated class.

    So mark your controller class as @Validated, which would trigger the validation of the id path variable.

    @RestController
    @RequestMapping("/my")
    @Validated
    public class MyController {
    
      @PostMapping(value = "/myapi/{id}", produces = APPLICATION_JSON_VALUE, consumes = APPLICATION_JSON_VALUE)
      public ResponseEntity<MyEntity> myApi(
          @PathVariable("id") @NotBlank String id,
          @Valid @RequestBody MyRequestPayload myRequestPayload) throws
          Exception {
        LOGGER.info("Id is {}", id);
      }
    }
    

    Reference: Validation with Spring Boot