Syntax highlighter header

Monday 6 February 2023

Overriding base URL for feign client with every call

We had a requirement to notify our partner of some events in our system. For implementing this callback into their system we decided to use FeignClient inside our Spring application. But the challenge we faced was to override base URL of FeignClient in every API call. Over FeignClient interface is defined as follows:

@FeignClient(name = "BrandPartnerNotificationForEnabledSku")
public interface BrandPartnerFeignClient {
    @RequestMapping(value= "{path}",method = RequestMethod.POST, consumes="application/json", produces = "application/json")
    ResponseEntity<String> callWebhook(@RequestBody String enabledSkuList, @PathVariable("path") String path, @RequestHeader Map<String,String> headers);
}

In above call we are passing http headers as a map to the call because http header requirement for different partners will be different. Next challenge was to override the URL and basic authentication for each partner for callback. We used following code for creating feign client manually rather than allowing spring to create it automatically.

BrandPartnerFeignClient brandPartnerFeignClient = new FeignClientBuilder(applicationContext).forType(BrandPartnerFeignClient.class, "client1")
		.url("http://localhost:8080/receive")
		.customize(feginBuilder-> feginBuilder.requestInterceptor(new BasicAuthRequestInterceptor("dummyuser", "dummypassword")))
		.build();
// create jsonString and headersMap
ResponseEntity<String> response = brandPartnerFeignClient.callWebhook(jsonString,"/headersasmap",headersMap);

We passed base url to method url while creating the feign client and other part of URL as path parameter. This way you can cater to same base url hosting more than one sub url.