spring_boot_starter_feign
spring_boot_starter_feign gives Spring for Dart declarative HTTP clients, the Dart counterpart of Spring Cloud OpenFeign. You describe a remote API as an abstract class, one method per endpoint, with the same mapping annotations as a controller. You inject it like any bean, and calling a method sends the request and gives you the decoded answer.
Why
Calling another service by hand means building URLs, encoding JSON, sending the request, checking the status and decoding the answer, for every endpoint. The starter does that part:
- the generator writes the implementation at build time, without reflection;
- JSON goes through the
ObjectMapperofspring_core_dart; - error statuses become exceptions you can catch (
FeignNotFound,FeignServiceUnavailable...); - timeouts, a limit for the whole call, logging, retries, request interceptors and fallbacks are set per client;
- multipart uploads, form bodies and server-sent events with reconnection are supported.
Use it in a server that calls other services, or in a Flutter app that calls its backend: the transport is dart:io on the VM and Flutter, fetch on the web.
Setup
# pubspec.yaml
dependencies:
spring_boot_starter_feign: ^0.9.0
dev_dependencies:
build_runner: ^2.17.0
spring_core_dart_generator: ^0.9.0 # required: writes the client implementations
spring_boot_starter_test: ^0.9.0 # MockHttpTransport, for tests
test: ^1.33.0
One import is enough: package:spring_boot_starter_feign/spring_boot_starter_feign.dart re-exports spring_boot_dart, spring_web_dart (the mapping annotations) and spring_boot_starter_logging.
Example
import 'package:spring_boot_starter_feign/spring_boot_starter_feign.dart';
import 'spring_gen/main.spring.dart';
// The catalog service's API, as the shop calls it.
@FeignClient('catalog', url: r'${catalog.url}')
abstract interface class CatalogClient {
@GetMapping('/books/{isbn}')
Future<Book> find(@PathVariable() String isbn);
// GET /books?q=dune&page=2; page is left out when null.
@GetMapping('/books')
Future<List<Book>> search(@RequestParam('q') String query, {@RequestParam() int? page});
// The book is sent as JSON; the answer gives the status and headers too.
@PostMapping('/books')
Future<ResponseEntity<Book>> create(@RequestBody() Book book);
@DeleteMapping('/books/{isbn}')
Future<void> delete(@PathVariable() String isbn);
}
class Book {
const Book({required this.isbn, required this.title});
final String isbn;
final String title;
}
@Service()
class Shop {
Shop(this.catalog); // the generated client, injected like any bean
final CatalogClient catalog;
Future<String?> title(String isbn) async {
try {
return (await catalog.find(isbn)).title;
} on FeignNotFound {
return null; // a missing book is not an error for the shop
}
}
}
@SpringBootApplication()
void main(List<String> args) => runApplication(args);
# lib/resources/application.properties
catalog.url=https://api.neon.books
spring.feign.client.config.default.read-timeout=10s
spring.feign.client.config.catalog.logger-level=basic
Classes that the client methods take or return are described for JSON automatically when they are in the same package as the client: the answers with their constructor and setters, the arguments with their getters. @Introspected() on a class describes everything.
What starts
- No
@EnableFeignClients. Every abstract class with@FeignClientin the scanned package becomes a bean, named after the interface (CatalogClient→catalogClient),@Primaryby default. - Every client is checked at startup. A path variable without a parameter, a method without a mapping, an object as a query value or a client without a URL stops the application with the reasons.
- The transport is shared. All clients send through the
HttpTransportbean (platformHttpTransport()unless you declare one).
What is inside
- Methods: mapping annotations, parameters, results, form bodies, startup checks.
- Files and multipart:
@RequestPartuploads. - Server-sent events:
EventStream<T>with reconnection. - Configuration:
spring.feign.client.config.<name>.*,@FeignClientattributes, per-client beans. - Errors, retries and timeouts: the exceptions,
ErrorDecoder,Retryer,call-timeout, fallbacks. - Interceptors: headers and tokens on every request.
- Logging:
logger-leveland masked headers. - Testing:
MockHttpTransportand the transport. - All properties: every key of the starter.
- Differences from Spring: what works differently than in Spring Cloud OpenFeign.
In Spring (Java)
@EnableFeignClients
@SpringBootApplication
class ShopApplication { ... }
@FeignClient(name = "catalog", url = "${catalog.url}")
interface CatalogClient {
@GetMapping("/books/{isbn}")
Book find(@PathVariable String isbn);
}
Differences that matter:
- Methods return
Futures; there is no@EnableFeignClients. - The properties are
spring.feign.*, notspring.cloud.openfeign.*. - No service discovery: every client needs a URL.
- The full list is on Differences from Spring.