Configure Feign Client in Spring Boot Configure Feign Client in Spring Boot

Page content

In this article, we’ll learn how to configure a Feign Client in your Spring Boot project to consume RESTFul APIs from other services.

Feign Client is a Declarative REST Client in Spring Boot Web Application. It is very useful in microservice architecture to create feign client to consume RESTFul API endpoints exposed by other microservices.

1. Project Setup

For initial setup of your Spring Boot project, you should use Spring Initializr. Choose the OpenFeign and Spring Web as dependencies. If you are not sure, click the below link for pre-selected required dependencies:-

https://start.spring.io/#!type=maven-project&language=java&platformVersion=2.3.0.RELEASE&packaging=jar&jvmVersion=1.8&groupId=com.example&artifactId=api&name=api&description=Create%20Feign%20Client%20to%20consume%20RESTFul%20APIs&packageName=com.example.api&dependencies=cloud-feign,web

Also Read here How to setup a Spring Boot project using Spring Initalizr

Assuming you chose build project as maven. A typical pom.xml for a web project look like this:-

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.3.0.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>api</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>springboot-api</name>
	<description>Create Feign Client to consume RESTFul APIs</description>

	<properties>
		<java.version>1.8</java.version>
		<spring-cloud.version>Hoxton.SR4</spring-cloud.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-openfeign</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>

	</dependencies>

	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.springframework.cloud</groupId>
				<artifactId>spring-cloud-dependencies</artifactId>
				<version>${spring-cloud.version}</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

2. Enable Feign Client

When you are working with spring boot project, you have nothing much to do to enable feign client for your project. Make sure:-

  1. You have spring-boot-starter-web and spring-cloud-starter-openfeign dependencies in your pom.xml or build.gradle
  2. You are using @SpringBootApplication and @EnableFeignClients annotations at your application starter class file ApiApplication.

Spring Boot is opinionated, when it sees the web and openfeign dependencies in the classpath, it sets up all the necessary default configuration required for Feign Client and automatically scans for the classes annotated with @FeignClient

package com.example.api;

@SpringBootApplication
@EnableFeignClients
public class ApiApplication {

	public static void main(String[] args) {
		SpringApplication.run(ApiApplication.class, args);
	}
}

3. Create Feign Client

Next, we are going to create a feign client to consume RESTFul API endpoints. Let’s create a CommentFeignClient class -

  1. Annotated with @FeignClient which auto scan by spring boot application to generate feign client from this
  2. This feign client consumes the APIs from this URL: https://jsonplaceholder.typicode.com/
package com.example.api.client;

@FeignClient(name = "commentFeignClient", url = "https://jsonplaceholder.typicode.com/")
public interface CommentFeignClient {

	@GetMapping("/comments")
    List<Comment> getAllComments();
 
    @GetMapping("/comments/{commentId}")
    Comment getCommentById(@PathVariable Long commentId);
    
    @GetMapping("/comments")
    List<Comment> getCommentsByPostId(@RequestParam Long postId);
}

4. Feign Client Configuration

Spring boot comes with default global configuration which is applied on each feign client you create such as connection timeout, read timeout and logger level. Good things is you can change these global configurations from property file.

application.yml
feign:
  client:
    config:
      default:
        connectTimeout: 5000
        readTimeout: 5000
        loggerLevel: basic

By default these configurations are applied on each feign clients. If you want to override these configuration for a specific feign client. It can be done using feign client name. Remember, we created our feign client using @FeignClient with name commentFeignClient

package com.example.api.client;

@FeignClient(name = "commentFeignClient", url = "https://jsonplaceholder.typicode.com/")
public interface CommentFeignClient {
	//...

Let’s override configuration for commentFeignClient

feign:
  client:
    config:
      default:
        connectTimeout: 5000
        readTimeout: 5000
		loggerLevel: basic
	  commentFeignClient:
        connectTimeout: 10000
        readTimeout: 12000
		loggerLevel: full
logging:
  level:
    com.example.api.client: DEBUG

Feign logging only responds to the DEBUG level so the logging level of package of feign client must be set to DEBUG level i.e. com.example.api.client, if you want to enable feign logging.

The loggerLevel that you may configure per client, tells Feign how much to log. Choices are:

  • NONE, No logging (DEFAULT).
  • BASIC, Log only the request method and URL and the response status code and execution time.
  • HEADERS, Log the basic information along with request and response headers.
  • FULL, Log the headers, body, and metadata for both requests and responses.

5. Consume Feign Client

Now since we have created feign client, let’s create a service layer class CommentService and its implementation CommentServiceImpl to consume these APIs using the feign client

public interface CommentService {

	public List<Comment> getAllComments();
	public Comment getCommentById(Long id);
	public List<Comment> getAllCommentsByPostId(Long postId);
}
@Service
public class CommentServiceImpl implements CommentService {

	@Autowired
	private CommentFeignClient commentFeignClient;

	@Override
	public List<Comment> getAllComments() {
		return commentFeignClient.getAllComments();
	}

	@Override
	public Comment getCommentById(Long id) {
		return commentFeignClient.getCommentById(id);
	}

	@Override
	public List<Comment> getAllCommentsByPostId(Long postId) {
		return commentFeignClient.getCommentsByPostId(postId);
	}

}

Now since we have created our services classes and consumed APIs using feign client. Let’s create a controller CommentController to test feign client

@RestController
@RequestMapping("/comments")
public class CommentController {

	@Autowired
	private CommentService commentService;

	@GetMapping
	public List<Comment> getAllComments() {
		return commentService.getAllComments();
	}
	
	@GetMapping(params = "postId")
	public List<Comment> getAllCommentsByUserId(@RequestParam Long postId) {
		return commentService.getAllCommentsByPostId(postId);
	}

	@GetMapping("/{id}")
	public Comment getCommentById(@PathVariable Long id) {
		return commentService.getCommentById(id);
	}
	
}

6. Test Feign Client

That’s it. You have successfully created and tested feign client to consume APIs from given endpoint.

Download the complete source code for creating feign client from github/springboot-api