Sobes.tech
Junior — Middle

Can you explain how the Feign client works and how it interacts with REST API?

sobes.tech AI

Answer from AI

Feign is a declarative HTTP client for Java that simplifies REST API calls. Instead of manually writing code to send HTTP requests, you describe an interface with annotations, and Feign automatically generates the client implementation.

How it works:

  • You create an interface with methods corresponding to REST endpoints.
  • Methods are annotated, for example, with @RequestLine or Spring annotations (@GetMapping, @PostMapping).
  • Feign, upon startup, creates a proxy that, when a method is called, constructs an HTTP request to the appropriate URL, serializes parameters and body, sends the request, and deserializes the response into an object.

Example of a Feign interface:

@FeignClient(name = "userClient", url = "https://api.example.com")
public interface UserClient {
    @GetMapping("/users/{id}")
    User getUserById(@PathVariable("id") Long id);
}

Calling getUserById(123) will send a GET request to https://api.example.com/users/123 and return a User object.

Thus, Feign hides HTTP details, allowing you to work with REST APIs as if they were regular Java interface methods.