Does Feign client support optional request param?
For example, I have an endpoint, but I am not finding a way to actually make the param1 optional using feign client.
@GetMapping(path = "endpoint1")
ResponseEntity request(@RequestParam(name = "param1", required = false, defaultValue = "key") String param1){}
I managed to use Optional request params with Feign by creating a customised FeignFormatterRegistrar
.
Here is the code:
package feignformatters;
import org.springframework.cloud.openfeign.FeignFormatterRegistrar;
import org.springframework.format.FormatterRegistry;
import org.springframework.stereotype.Component;
import java.util.Optional;
@Component
public class OptionalFeignFormatterRegistrar implements FeignFormatterRegistrar {
@Override
public void registerFormatters(FormatterRegistry registry) {
registry.addConverter(
Optional.class,
String.class,
optional -> {
if (optional.isPresent())
return optional.get().toString();
else
return "";
});
}
}
The following client started working fine with the previous component loaded in the project:
@FeignClient("book-service")
public interface BookServiceClient {
@GetMapping("/books")
public List<Book> getBooks(
@RequestParam("page") Optional<Integer> pageNum,
@RequestParam("size") Optional<Integer> pageSize,
@RequestParam("reader") Optional<Long> readerId);
}