Declarative REST Client Communication Using OpenFeign

OpenFeign is a declarative HTTP client: you write only a Java interface with annotations, and Spring creates the code that calls the other service’s REST API.It is used because normal clients (RestClient, WebClient) need repeated code to build URLs, send requests, and read JSON, while Feign turns a remote call into a simple method call.Each interface method is mapped to a remote endpoint using familiar annotations like @GetMapping, @PostMapping, @PathVariable, and @RequestBody.In this demo, the Inventory service uses a Feign client to validate, read, and create products in the Product service.

Features

  • Interface-only client with no implementation code to write.
  • Uses the same Spring MVC annotations you already use in controllers.
  • Automatic JSON conversion for requests and responses.
  • Configurable connect and read timeouts, plus request and response logging.
  • Clear error handling through FeignException (NotFound, RetryableException).
  • Works with a fixed URL, or with a service name when combined with Eureka and a load balancer.
  • Easy to extend with fallbacks, error decoders, and interceptors.

Declarative REST Client Types

Imperative vs declarative clients

Style Meaning Example
Imperative You write the call step by step (build the request, send, read the response) RestClient, WebClient, RestTemplate
Declarative You only declare what the call looks like in an interface OpenFeign, Spring HTTP Interface

Common Feign annotations

Annotation Purpose
@EnableFeignClients Turns on Feign scanning in the main class
@FeignClient(name, url) Declares the client interface and the target service
@GetMapping, @PostMapping, @PutMapping, @DeleteMapping Maps a method to an HTTP method and path
@PathVariable("id") Puts a method argument into the URL path
@RequestParam Adds a query parameter
@RequestBody Sends the argument as the JSON body

Feign logger levels

Level What is logged
NONE Nothing (default)
BASIC Request method, URL, status, and time taken
HEADERS Basic information plus request and response headers
FULL Headers, body, and metadata of the request and response

Two ways to point a Feign client at a service

Way Example When to use
Fixed URL @FeignClient(name = "product-service", url = "http://localhost:8081") Simple setups (this demo)
Service name @FeignClient(name = "product-service") With Eureka and Spring Cloud LoadBalancer

Hands-on Experiment: Create a Product and Inventory Management System Using OpenFeign

Aim: To create two Spring Boot microservices (Product and Inventory) where the Inventory service calls the Product service through a declarative OpenFeign client, with the data stored in MySQL.

The following steps are involved in developing this hands-on experiment.

  • Step 1: Generate the Project
  • Step 2: Project Structure
  • Step 3: Create Product Micro Service
  • Step 4: Create Inventory Micro Service with the Feign Client
  • Step 5: Run the Application

Step-by-Step Application Development

Step 1: Generate the Project

Use Spring Initializr with:

  • Project: Maven
  • Language: Java
  • Spring Boot version: 3.3.x (latest stable)
  • Group: com.example
  • Artifact: product-inventory-feign-demo (parent), with modules product-service and inventory-service
  • Packaging: Jar
  • Java version: 17
  • Dependencies for product-service: Spring Web, Spring Data JPA, MySQL Driver
  • Dependencies for inventory-service: Spring Web, Spring Data JPA, MySQL Driver, OpenFeign

Download the generated ZIPs and place both services as modules inside one parent folder product-inventory-feign-demo. The ready-made multi-module project is also in the zip.

Step 2: Project Structure

Step 3: Create Product Microservice

package com.example.productservice.entity;

import jakarta.persistence.*;

import java.math.BigDecimal;

@Entity
@Table(name = "products")
public class Product {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String name;

    private String category;

    @Column(nullable = false, precision = 12, scale = 2)
    private BigDecimal price;

    public Product() {
    }

    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }

    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    public String getCategory() { return category; }
    public void setCategory(String category) { this.category = category; }

    public BigDecimal getPrice() { return price; }
    public void setPrice(BigDecimal price) { this.price = price; }
}
package com.example.productservice.repository;

import com.example.productservice.entity.Product;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
}
package com.example.productservice.service;

import com.example.productservice.entity.Product;
import com.example.productservice.repository.ProductRepository;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class ProductService {

    private final ProductRepository productRepository;

    public ProductService(ProductRepository productRepository) {
        this.productRepository = productRepository;
    }

    public Product createProduct(Product product) {
        product.setId(null);
        return productRepository.save(product);
    }

    public List<Product> getAllProducts() {
        return productRepository.findAll();
    }

    public Optional<Product> getProductById(Long id) {
        return productRepository.findById(id);
    }

    public Optional<Product> updateProduct(Long id, Product updated) {
        return productRepository.findById(id).map(existing -> {
            existing.setName(updated.getName());
            existing.setCategory(updated.getCategory());
            existing.setPrice(updated.getPrice());
            return productRepository.save(existing);
        });
    }
}
package com.example.productservice.controller;

import com.example.productservice.entity.Product;
import com.example.productservice.service.ProductService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/products")
public class ProductController {

    private final ProductService productService;

    public ProductController(ProductService productService) {
        this.productService = productService;
    }

    // POST /api/products
    @PostMapping
    public ResponseEntity<Product> createProduct(@RequestBody Product product) {
        return ResponseEntity.status(HttpStatus.CREATED).body(productService.createProduct(product));
    }

    // GET /api/products
    @GetMapping
    public List<Product> getAllProducts() {
        return productService.getAllProducts();
    }

    // GET /api/products/{id}
    @GetMapping("/{id}")
    public ResponseEntity<Product> getProductById(@PathVariable Long id) {
        return productService.getProductById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    // PUT /api/products/{id}
    @PutMapping("/{id}")
    public ResponseEntity<Product> updateProduct(@PathVariable Long id, @RequestBody Product product) {
        return productService.updateProduct(id, product)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }
}
package com.example.productservice;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ProductServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(ProductServiceApplication.class, args);
    }
}
spring.application.name=product-service
server.port=8081

spring.datasource.url=jdbc:mysql://localhost:3306/product_db?createDatabaseIfNotExist=true&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=password

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

server.error.include-message=alwaysCode language: PHP (php)

Step 4: Create Inventory Micro Service with the Feign Client

package com.example.inventoryservice.entity;

import jakarta.persistence.*;

// The inventory context stores only the productId (no JPA relationship across services)
@Entity
@Table(name = "inventory")
public class InventoryItem {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false, unique = true)
    private Long productId;

    @Column(nullable = false)
    private Integer quantity;

    private String location;

    public InventoryItem() {
    }

    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }

    public Long getProductId() { return productId; }
    public void setProductId(Long productId) { this.productId = productId; }

    public Integer getQuantity() { return quantity; }
    public void setQuantity(Integer quantity) { this.quantity = quantity; }

    public String getLocation() { return location; }
    public void setLocation(String location) { this.location = location; }
}
package com.example.inventoryservice.repository;

import com.example.inventoryservice.entity.InventoryItem;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface InventoryRepository extends JpaRepository<InventoryItem, Long> {

    boolean existsByProductId(Long productId);
}
package com.example.inventoryservice.service;

import com.example.inventoryservice.entity.InventoryItem;
import com.example.inventoryservice.repository.InventoryRepository;
import feign.FeignException;
import feign.RetryableException;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
public class InventoryService {

    private final InventoryRepository inventoryRepository;
    private final ProductClient productClient;

    public InventoryService(InventoryRepository inventoryRepository, ProductClient productClient) {
        this.inventoryRepository = inventoryRepository;
        this.productClient = productClient;
    }

    // ======================= Local operations =======================

    public List<InventoryItem> getAllInventory() {
        return inventoryRepository.findAll();
    }

    public Optional<InventoryItem> getInventoryById(Long id) {
        return inventoryRepository.findById(id);
    }

    public InventoryItem addStock(Long id, int quantity) {
        if (quantity <= 0) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "quantity must be greater than 0");
        }
        InventoryItem item = findItem(id);
        item.setQuantity(item.getQuantity() + quantity);
        return inventoryRepository.save(item);
    }

    public InventoryItem reduceStock(Long id, int quantity) {
        InventoryItem item = findItem(id);
        if (quantity <= 0 || item.getQuantity() < quantity) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST,
                    "Insufficient stock. Available: " + item.getQuantity());
        }
        item.setQuantity(item.getQuantity() - quantity);
        return inventoryRepository.save(item);
    }

    // ======================= Operations that use the Feign client =======================

    // Create an inventory record for an EXISTING product (the product is validated with Feign GET)
    public InventoryItem createInventory(InventoryItem request) {
        if (request.getProductId() == null || request.getQuantity() == null || request.getQuantity() < 0) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST,
                    "productId and a non-negative quantity are required");
        }

        fetchProduct(request.getProductId());

        if (inventoryRepository.existsByProductId(request.getProductId())) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST,
                    "Inventory already exists for product id " + request.getProductId());
        }

        request.setId(null);
        return inventoryRepository.save(request);
    }

    // Create a NEW product in product-service (Feign POST) and its inventory record in one request
    public Map<String, Object> createProductWithStock(Map<String, Object> request) {
        if (request.get("name") == null || request.get("price") == null || request.get("quantity") == null) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "name, price and quantity are required");
        }

        Map<String, Object> productRequest = new LinkedHashMap<>();
        productRequest.put("name", request.get("name"));
        productRequest.put("category", request.get("category"));
        productRequest.put("price", request.get("price"));

        Map<String, Object> product;
        try {
            product = productClient.createProduct(productRequest);
        } catch (RetryableException e) {
            throw new ResponseStatusException(HttpStatus.SERVICE_UNAVAILABLE, "Product service is unavailable");
        }

        InventoryItem item = new InventoryItem();
        item.setProductId(Long.valueOf(String.valueOf(product.get("id"))));
        item.setQuantity(Integer.valueOf(String.valueOf(request.get("quantity"))));
        item.setLocation(request.get("location") == null ? null : String.valueOf(request.get("location")));

        return toResponse(inventoryRepository.save(item), product);
    }

    // One inventory record + its product details (Feign GET by id)
    public Map<String, Object> getInventoryWithProduct(Long id) {
        InventoryItem item = findItem(id);
        return toResponse(item, fetchProduct(item.getProductId()));
    }

    // All inventory records with product details: ONE Feign call for all products, joined in memory
    public List<Map<String, Object>> getAllInventoryWithProducts() {
        List<InventoryItem> items = inventoryRepository.findAll();

        List<Map<String, Object>> products;
        try {
            products = productClient.getAllProducts();
        } catch (RetryableException e) {
            throw new ResponseStatusException(HttpStatus.SERVICE_UNAVAILABLE, "Product service is unavailable");
        }

        Map<Long, Map<String, Object>> productMap = new HashMap<>();
        for (Map<String, Object> product : products) {
            productMap.put(Long.valueOf(String.valueOf(product.get("id"))), product);
        }

        return items.stream()
                .map(item -> toResponse(item, productMap.get(item.getProductId())))
                .toList();
    }

    // ======================= Helpers =======================

    private Map<String, Object> fetchProduct(Long productId) {
        try {
            return productClient.getProductById(productId);
        } catch (FeignException.NotFound e) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Product not found with id " + productId);
        } catch (RetryableException e) {
            throw new ResponseStatusException(HttpStatus.SERVICE_UNAVAILABLE, "Product service is unavailable");
        }
    }

    private InventoryItem findItem(Long id) {
        return inventoryRepository.findById(id)
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND,
                        "Inventory not found with id " + id));
    }

    private Map<String, Object> toResponse(InventoryItem item, Map<String, Object> product) {
        Map<String, Object> response = new LinkedHashMap<>();
        response.put("inventoryId", item.getId());
        response.put("productId", item.getProductId());
        response.put("productName", product == null ? null : product.get("name"));
        response.put("category", product == null ? null : product.get("category"));
        response.put("price", product == null ? null : product.get("price"));
        response.put("quantity", item.getQuantity());
        response.put("location", item.getLocation());
        return response;
    }
}
package com.example.inventoryservice.service;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;
import java.util.Map;

// Declarative REST client: only an interface, Spring creates the implementation at runtime.
// Each method is mapped to an endpoint of product-service using normal Spring MVC annotations.
@FeignClient(name = "product-service", url = "${product.service.url}")
public interface ProductClient {

    @GetMapping("/api/products/{id}")
    Map<String, Object> getProductById(@PathVariable("id") Long id);

    @GetMapping("/api/products")
    List<Map<String, Object>> getAllProducts();

    @PostMapping("/api/products")
    Map<String, Object> createProduct(@RequestBody Map<String, Object> product);
}
package com.example.inventoryservice.controller;

import com.example.inventoryservice.entity.InventoryItem;
import com.example.inventoryservice.service.InventoryService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/inventory")
public class InventoryController {

    private final InventoryService inventoryService;

    public InventoryController(InventoryService inventoryService) {
        this.inventoryService = inventoryService;
    }

    // POST /api/inventory  (product is validated using Feign)
    @PostMapping
    public ResponseEntity<InventoryItem> createInventory(@RequestBody InventoryItem item) {
        return ResponseEntity.status(HttpStatus.CREATED).body(inventoryService.createInventory(item));
    }

    // POST /api/inventory/products  (creates the product through Feign, then its inventory)
    @PostMapping("/products")
    public ResponseEntity<Map<String, Object>> createProductWithStock(@RequestBody Map<String, Object> request) {
        return ResponseEntity.status(HttpStatus.CREATED).body(inventoryService.createProductWithStock(request));
    }

    // GET /api/inventory
    @GetMapping
    public List<InventoryItem> getAllInventory() {
        return inventoryService.getAllInventory();
    }

    // GET /api/inventory/{id}
    @GetMapping("/{id}")
    public ResponseEntity<InventoryItem> getInventoryById(@PathVariable Long id) {
        return inventoryService.getInventoryById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    // GET /api/inventory/{id}/details  (inventory + product details using Feign)
    @GetMapping("/{id}/details")
    public Map<String, Object> getInventoryWithProduct(@PathVariable Long id) {
        return inventoryService.getInventoryWithProduct(id);
    }

    // GET /api/inventory/with-products  (all inventory + product details using Feign)
    @GetMapping("/with-products")
    public List<Map<String, Object>> getAllInventoryWithProducts() {
        return inventoryService.getAllInventoryWithProducts();
    }

    // PUT /api/inventory/{id}/add-stock?quantity=10
    @PutMapping("/{id}/add-stock")
    public InventoryItem addStock(@PathVariable Long id, @RequestParam int quantity) {
        return inventoryService.addStock(id, quantity);
    }

    // PUT /api/inventory/{id}/reduce-stock?quantity=5
    @PutMapping("/{id}/reduce-stock")
    public InventoryItem reduceStock(@PathVariable Long id, @RequestParam int quantity) {
        return inventoryService.reduceStock(id, quantity);
    }
}
package com.example.inventoryservice;

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

@SpringBootApplication
@EnableFeignClients
public class InventoryServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(InventoryServiceApplication.class, args);
    }
}
spring.application.name=inventory-service
server.port=8082

spring.datasource.url=jdbc:mysql://localhost:3306/inventory_db?createDatabaseIfNotExist=true&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=password

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

server.error.include-message=always

# URL used by the Feign client
product.service.url=http://localhost:8081

# Feign settings (milliseconds) and request/response logging
spring.cloud.openfeign.client.config.default.connect-timeout=3000
spring.cloud.openfeign.client.config.default.read-timeout=5000
spring.cloud.openfeign.client.config.default.logger-level=full
logging.level.com.example.inventoryservice.service.ProductClient=DEBUGCode language: PHP (php)

Step 5: Run the Service one by one

i. Product microservice

ii. inventory microservice

Scroll to Top