Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate RestTemplate response?

Spring supports annotation based validation at the controller level.

(1) Is it necessary to do such validations also at the RestTemplate level for responses from REST calls?

If the answer is Yes: (2) Will there be support for that at the RestTemplate to validate responses from rest calls sometime in the future?

If the answer is No: (3) why?

like image 546
Jothi Avatar asked Oct 30 '22 02:10

Jothi


1 Answers

It is 2020 now and I still do not see the requested feature in place.

The @Valid is nice to automatically validate e.g. a posted RequestBody.

But for the validation of the body of a ResponseEntity fetched via RestTemplate, I do not see any fancy equivalent.

So the only option I know, is to do it on your own taken from here. Input is the class of your RequestEntitys body. input is the body itself.

ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<Input>> violations = validator.validate(input);
if (!violations.isEmpty()) {
  throw new ConstraintViolationException(violations);
}

So to answer your question:

  1. Yes I would validate the response!
  2. future (2020) has not brought the feature you and I miss
  3. For the reason why this is missing, I also have no answer.
like image 182
D. Spreuer Avatar answered Nov 15 '22 09:11

D. Spreuer