Search code examples
javaspringvalidationannotationsfeign

Feign client response validation


I have two applications A and B communicating with each other using FeignClient. As an application A I want to have validation on the data that is returned by application B. If I want to validate request parameters I can easily use @Valid annotation and annotate object with correct spring validation annotations. What about response ?

@FeignClient()
public interface AccountClient {
   @PostMapping("/accounts/account/create")
   void createAccount(@Valid CreateAccountRequest request);

   @PostMapping("/accounts/account/get")
   AccountResponse getAccount(AccountRequest request);

}
public classs AccountResponse {
   @NotNull
   public String status;
}

Code as an example. I can easily validate CreateAccountRequest in application B. But what about AccountResponse? In that case @NotNull is not working. I would prefer to avoid getting the response and manually checking if status != null cause I would have much more fields like this.


Solution

  • In this case, the response validation should work if you place @Validated onto AccountClient interface and then @Valid onto getAccount method.

    This is standard Spring validation feature, applicable not only for Feign

    import org.springframework.validation.annotation.Validated;
    import javax.validation.Valid;
    
    @Validated
    @FeignClient
    public interface AccountClient {
       @PostMapping("/accounts/account/create")
       void createAccount(@Valid CreateAccountRequest request);
    
       @Valid
       @PostMapping("/accounts/account/get")
       AccountResponse getAccount(AccountRequest request);
    
    }