Integrating third-party APIs is a common requirement in modern applications. Traditionally, developers rely on tools like Apache HttpClient or RestTemplate to make HTTP calls. While these approaches are powerful, they often involve writing repetitive boilerplate code for handling request construction, response parsing, HTTP methods, headers, and error handling.
This is where OpenFeign comes in as a cleaner, more declarative alternative.
Why Feign?
Feign simplifies HTTP API communication by allowing developers to define REST clients using interfaces. Instead of manually building requests, you declare endpoints and let Feign handle the rest.
Key Benefits:
- Declarative API definitions
- Reduced boilerplate code
- Built-in support for encoding/decoding
- Easy logging integration
- Pluggable HTTP clients (like OkHttp)
1. Maven Dependencies
To get started with Feign, add the following dependencies:
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-core</artifactId>
<version>13.6</version>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId>
<version>13.6</version>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-gson</artifactId>
<version>13.6</version>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-slf4j</artifactId>
<version>13.5</version>
</dependency>
<!-- SLF4J API -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>2.0.17</version>
</dependency>
<!-- Log4j2 binding for SLF4J -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j2-impl</artifactId>
<version>2.24.3</version>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-jaxb</artifactId>
<version>13.6</version>
</dependency>2. Creating a Feign Client
Feign clients are instantiated using a builder pattern. Below is a sample configuration:
public ABCClient getClient() {
return Feign.builder()
.client(new OkHttpClient())
.encoder(new GsonEncoder())
.decoder(new GsonDecoder())
.logLevel(Logger.Level.FULL)
.logger(new Slf4jLogger(ABCClient.class))
.target(ABCClient.class, "https://www.abc.com/client");
}What’s happening here?
- OkHttpClient → Handles HTTP communication
- GsonEncoder/Decoder → Converts Java objects to/from JSON
- Slf4jLogger → Enables structured logging
- Logger.Level.FULL → Logs request and response details
3. Declaring HTTP APIs
With Feign, API definitions are written as interfaces.
Example: GET API
public interface ABCClient {
@RequestLine("GET /abc/search?criteria={criteria}")
@Headers({
"Content-Type: application/json",
"Authorization: {authToken}"
})
Map<String, Object> getSearchData(
@Param("authToken") String authToken,
@Param("criteria") String criteria
);
}Generic Format
@RequestLine("<HTTP_METHOD> <PATH>?param={value}")Example: POST API
@RequestLine("POST /abc/contact/update")
@Headers({
"Content-Type: application/json",
"Authorization: {authToken}"
})
Map<String, Object> updateContacts(
@Param("authToken") String authToken,
Map<String, Object> requestBody
);Feign automatically serializes the request body using the configured encoder.
4. Invoking the API
Once the client is created, calling an API becomes straightforward:
getClient().updateContacts(authToken, requestBody);No manual request building, no response parsing — Feign handles everything behind the scenes.
5. Logging Feign Requests & Responses Separately
A major advantage of Feign is its seamless logging integration. You can route Feign logs into a dedicated file using Log4j2.
Step 1: Add Appender in log4j2.xml
<RollingFile name="abcCleintfeignLog"
fileName="D:/logs/abcClient/abcClientFeign.log"
filePattern="D:/logs/abcClient/$${date:yyyy-MM-dd}/abcClientFeign-%d{yyyy-MM-dd-HH}-%i.log.gz">
<PatternLayout>
<pattern>%d{dd-MM-yyyy HH:mm:ss.SSS} [%t] %-5p %c - %m%n</pattern>
</PatternLayout>
<Policies>
<SizeBasedTriggeringPolicy size="500 MB"/>
</Policies>
<DefaultRolloverStrategy max="100"/>
</RollingFile>
<Async name="FeignRollingFile">
<AppenderRef ref="abcCleintfeignLog"/>
</Async>Step 2: Configure Logger
<Logger name="com.souravdl.abc.client" level="DEBUG" additivity="false">
<AppenderRef ref="FeignRollingFile"/>
</Logger>This ensures:
- All Feign logs are written to a dedicated file
- Logging is asynchronous for better performance
- Application logs remain clean and separate
Conclusion
OpenFeign offers a modern, developer-friendly approach to API integration in Java applications. By replacing imperative HTTP handling with declarative interfaces, it significantly reduces boilerplate code and improves maintainability.
When to Use Feign?
- Microservices communication
- Third-party API integrations
- Clean and maintainable HTTP clients
- Projects requiring structured logging
If you're still using traditional HTTP clients, adopting Feign can drastically simplify your codebase while improving readability and scalability.
Pro Tip: Combine Feign with Spring Boot (via Spring Cloud OpenFeign) for even tighter integration and configuration management.