Feign

Language: Java

Web

Feign was created by Netflix to provide a type-safe and declarative way to call REST services in Java. It integrates seamlessly with Spring Boot and Spring Cloud, supporting load balancing, circuit breakers, and automatic request/response mapping.

Feign is a declarative HTTP client for Java, primarily used with Spring Cloud to simplify REST API calls. It allows developers to define API clients using interfaces and annotations.

Installation

maven: Add org.springframework.cloud:spring-cloud-starter-openfeign dependency in pom.xml
gradle: Add implementation 'org.springframework.cloud:spring-cloud-starter-openfeign' in build.gradle

Usage

Feign allows developers to define Java interfaces annotated with HTTP methods, paths, and parameters. Spring Boot automatically generates the implementation and handles serialization/deserialization, making API calls simple and readable.

Defining a Feign client

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import java.util.List;

@FeignClient(name = "user-service", url = "https://api.example.com")
public interface UserClient {
    @GetMapping("/users")
    List<User> getUsers();
}

Defines a Feign client interface to fetch a list of users from the `/users` endpoint.

Enabling Feign in Spring Boot

import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnableFeignClients
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Enables Feign support in a Spring Boot application.

Passing query parameters

@GetMapping("/users")
List<User> getUsersByRole(@RequestParam("role") String role);

Demonstrates sending query parameters in Feign client calls.

Handling path variables

@GetMapping("/users/{id}")
User getUserById(@PathVariable("id") Long id);

Demonstrates sending path variables in Feign client calls.

Custom headers

@GetMapping("/users")
@Headers("Authorization: Bearer {token}")
List<User> getUsers(@Param("token") String token);

Shows how to pass custom headers dynamically in Feign requests.

Using fallback for error handling

import org.springframework.stereotype.Component;

@Component
public class UserClientFallback implements UserClient {
    @Override
    public List<User> getUsers() {
        return Collections.emptyList(); // fallback response
    }
}

Provides a fallback implementation when the Feign client call fails.

Error Handling

FeignException: Occurs when the Feign client receives a non-successful HTTP response. Check status code and error body.
HttpClientErrorException: Thrown when a 4xx HTTP error occurs. Validate request parameters and headers.
HttpServerErrorException: Thrown when a 5xx HTTP error occurs. Retry or use fallback mechanisms for resilience.

Best Practices

Use Feign clients as interfaces to improve testability and maintainability.

Leverage Spring Cloud load balancing and resilience features (e.g., Hystrix or Resilience4j) with Feign.

Handle exceptions and fallback responses gracefully.

Prefer declarative annotations over manual HTTP calls for cleaner code.

Use DTOs and proper serialization libraries (Gson, Jackson) for request/response objects.