What it is
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.
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.
Installation
Add org.springframework.cloud:spring-cloud-starter-openfeign dependency in pom.xmlGetting started
The smallest useful thing you can do with it, and what each part means.
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();
}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);
}
}Advanced usage
Where the library earns its place over a simpler alternative.
@GetMapping("/users")
List<User> getUsersByRole(@RequestParam("role") String role);@GetMapping("/users/{id}")
User getUserById(@PathVariable("id") Long id);@GetMapping("/users")
@Headers("Authorization: Bearer {token}")
List<User> getUsers(@Param("token") String token);import org.springframework.stereotype.Component;
@Component
public class UserClientFallback implements UserClient {
@Override
public List<User> getUsers() {
return Collections.emptyList(); // fallback response
}
}Errors and fixes
The failures you are most likely to hit, and what actually resolves them.
- 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.
Background
Why it exists, and what it was reacting to.
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.
