Search code examples
javaspringvalidationspring-bootspring-rest

How to validate Spring Boot Rest response?


I have controller implemented with Spring Boot Rest:

@RestController
@RequestMapping("/example")
public class ExampleController {

    @Autowired
    private ExampleService exampleService;

    @GetMapping("/{id}")
    public ExampleResponse getExample(@NotNull @PathVariable("id") String id) {
        return exampleService.getExample(id);
    }
}

And response DTO:

public class ExampleResponse {

    @NotNull
    private String id;

    @NotNull
    private String otherStuff;

    // setters and getters
}

Response body is not validated. I have annotated it with @Valid but null values still pass. Request validation works well.

How to validate response body?


Solution

  • Implemented response validator:

    @Aspect
    @Component
    public class ControllerResponseValidator {
    
        Logger logger = Logger.getLogger(ControllerResponseValidator.class);
    
        @Autowired
        private Validator validator;
    
        @AfterReturning(pointcut = "execution(* com.example.controller.*.*(..))", returning = "result")
        public void validateResponse(JoinPoint joinPoint, Object result) {
            validateResponse(result);
        }
    
        private void validateResponse(Object object) {
    
            Set<ConstraintViolation<Object>> validationResults = validator.validate(object);
    
            if (validationResults.size() > 0) {
    
                StringBuffer sb = new StringBuffer();
    
                for (ConstraintViolation<Object> error : validationResults) {
                    sb.append(error.getPropertyPath()).append(" - ").append(error.getMessage()).append("\n");
                }
    
                String msg = sb.toString();
                logger.error(msg);
                throw new RestException(HttpStatus.INTERNAL_SERVER_ERROR, msg);
            }
        }
    }