This is a beginner’s guide for understanding Feign and it will provide a brief overview of Feign. We will discuss :
RestTemplate vs Feign
how to do basic calls with Feign (GET, POST ...)
customizing Feign components (Encoder , Retryer)
handle errors using Feign
ErrorDecoder
Introduction
We will start with the simple question: when am I going to use Feign? In today's micro-services era, it's usual to discuss synchronous and asynchronous method calls when calling another service, and even in a monolithic architecture sometimes you need to call an external service and interact with it. When to use each one depends a lot on the business logic you're creating, but we'll focus on the synchronous one here, with a particular focus on the Java platform.
In most cases, when making API rest call to another service we need to deal with :
putting up headers.
the body call.
manage the server response.
If you're a pure Java developer,
OKHttpClient
is undoubtedly your preferred library, however, if you're looking for a Spring-based option,
RestTemplate
can help, let's see some examples using these two solutions and discuss their advantages and disadvantages.
Using
OKHttpClient
we will have something like this :
Let's deep dive a little bit into the code :
1. first, create the request for the remote resource by specifying the URL, and the ( headers, body ) if needed.
2. execute the request and retrieve the response
3. deserialize the HTTP response to a concrete type. Here I used Jackson object mapper class to deserialize from JSON to PostDTO class.
Sounds good, simple configuration but we still need to deal directly with the response handling, let's see the same example using
RestTemplate
What we did here is:
1. Instantiate RestTemplate.
2. Call getForObject with the specific URL, and the desired class to map to it.
That's OK. We don't have to worry about response handling because Spring will change the incoming response into the object we want.
However, as you are aware, not all API requests are successful. We must deal with unanticipated problems in the majority of cases, some of which are caused by network status, timeouts, or simply internal server errors. Whatever the case may be, we must be prepared. We may use the
ResponseEntity
wrapper to access the request call status and body, and apply some exception handlers. Let's try this:
Using a try-catch block to catch the
HttpClientErrorException
exception is the simplest approach to create a custom error handler. You can then get the response status code, body, and headers from the
HttpClientErrorException
instance. Let's assume we miss-spelled the URL and instead of /posts we wrote /not-posts, the expected result is 404 let's execute the code.
It looks good, so what is that Feign? Why don't we just use RestTemplate? Ugghhh Confused.