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.
Add org.springframework.cloud:spring-cloud-starter-openfeign dependency in pom.xmlAdd implementation 'org.springframework.cloud:spring-cloud-starter-openfeign' in build.gradleFeign 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.
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.
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.
@GetMapping("/users")
List<User> getUsersByRole(@RequestParam("role") String role);Demonstrates sending query parameters in Feign client calls.
@GetMapping("/users/{id}")
User getUserById(@PathVariable("id") Long id);Demonstrates sending path variables in Feign client calls.
@GetMapping("/users")
@Headers("Authorization: Bearer {token}")
List<User> getUsers(@Param("token") String token);Shows how to pass custom headers dynamically in Feign requests.
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.
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.