HTTP clients

This page makes the same call three ways: fetch a book as JSON from a catalog service, decode it into a class, send a token, treat a 404 as "no such book", limit the time and retry when the connection fails.

The plain versions decode with a hand-written fromJson:

class Book {
  const Book({required this.isbn, required this.title});

  factory Book.fromJson(Map<String, dynamic> json) =>
      Book(isbn: json['isbn'] as String, title: json['title'] as String);

  final String isbn;
  final String title;
}

Fetch and decode

platformHttpTransport. You build the request, send it, check the status and decode the body.

final transport = platformHttpTransport();

Future<Book> find(String isbn) async {
  final response = await transport.send(HttpRequest(
    method: HttpMethod.get,
    url: Uri.parse('https://api.neon.books/books/$isbn'),
  ));
  if (!response.isSuccess) throw StateError('catalog: ${response.statusCode}');
  return Book.fromJson(jsonDecode(response.bodyText) as Map<String, dynamic>);
}

dio. The base URL is set once; data is already decoded from JSON. A status outside 2xx throws by default.

final dio = Dio(BaseOptions(baseUrl: 'https://api.neon.books'));

Future<Book> find(String isbn) async {
  final response = await dio.get<Map<String, dynamic>>('/books/$isbn');
  return Book.fromJson(response.data!);
}

Feign. One method per endpoint. Book needs no fromJson: classes a client returns are described for JSON from their constructor when they are in the same package.

@FeignClient('catalog', url: r'${catalog.url}')
abstract interface class CatalogClient {
  @GetMapping('/books/{isbn}')
  Future<Book> find(@PathVariable() String isbn);
}

@Service()
class Shelf {
  Shelf(this.catalog); // the generated client, injected
  final CatalogClient catalog;
}
catalog.url=https://api.neon.books

What changes: with the transport you write everything; dio removes the URL joining and the decoding step; Feign removes the method body. The Feign client needs build_runner, and the call only exists inside a Spring application, where it is injected.

A header on every request

platformHttpTransport. Added to each request you build.

headers: HttpHeaders()..setBearerAuth(tokens.accessToken),

dio. An interceptor, added once.

dio.interceptors.add(InterceptorsWrapper(
  onRequest: (options, handler) {
    options.headers['Authorization'] = 'Bearer ${tokens.accessToken}';
    handler.next(options);
  },
));

Feign. A RequestInterceptor bean applies to every client; a ready-made one sends a bearer token.

@Configuration()
class FeignSetup {
  @Bean()
  RequestInterceptor auth(TokenStore tokens) =>
      BearerTokenRequestInterceptor(() => tokens.accessToken);
}

A fixed header can also come from configuration: spring.feign.client.config.catalog.default-request-headers.X-Api-Key=${CATALOG_KEY}.

What changes: dio and Feign both set it once. Feign's interceptor runs again for every retry, so a refreshed token reaches the next attempt, and it can be limited to one client.

A missing book (404)

platformHttpTransport. Every status is a normal response, so a 404 is a check.

if (response.statusCode == HttpStatus.notFound) return null;

dio. A 404 throws a DioException that carries the response.

try {
  return Book.fromJson((await dio.get<Map<String, dynamic>>('/books/$isbn')).data!);
} on DioException catch (e) {
  if (e.response?.statusCode == 404) return null;
  rethrow;
}

Feign. A 404 throws FeignNotFound. Or let the client answer null:

@GetMapping('/books/{isbn}')
Future<Book?> find(@PathVariable() String isbn);
spring.feign.client.config.catalog.dismiss404=true

What changes: Feign has one exception class per status (FeignNotFound, FeignConflict, FeignServiceUnavailable, ...), so a catch names the case it handles. dismiss404 turns the most common case into configuration.

Timeouts

platformHttpTransport. A connect timeout on the transport; on the request, a read timeout (each wait for data) and a deadline for the whole exchange. A timeout throws HttpTransportException with isTimeout set.

final transport = platformHttpTransport(connectTimeout: const Duration(seconds: 3));

HttpRequest(
  method: HttpMethod.get,
  url: url,
  readTimeout: const Duration(seconds: 10),
  timeout: const Duration(seconds: 15),
);

dio. On the options; a timeout is a DioException with type connectionTimeout or receiveTimeout.

final dio = Dio(BaseOptions(
  baseUrl: 'https://api.neon.books',
  connectTimeout: const Duration(seconds: 3),
  receiveTimeout: const Duration(seconds: 10),
));

Feign. In configuration, per client or for all of them.

spring.feign.client.config.default.connect-timeout=3s
spring.feign.client.config.catalog.read-timeout=10s
spring.feign.client.config.catalog.call-timeout=15s

What changes: the values move from code to a file, so a test or a profile can change them. call-timeout bounds the whole call, every retry and pause included, and throws FeignCallTimeoutException. A Feign call made while a web request is handled is also limited by that request's deadline.

Retries

platformHttpTransport. A loop you write.

for (var attempt = 1; ; attempt++) {
  try {
    return await send();
  } on HttpTransportException {
    if (attempt == 3) rethrow;
    await Future<void>.delayed(Duration(milliseconds: 150 * attempt));
  }
}

dio. Not built in. The dio_smart_retry package adds an interceptor:

dio.interceptors.add(RetryInterceptor(
  dio: dio,
  retries: 2,
  retryDelays: const [Duration(milliseconds: 150), Duration(milliseconds: 225)],
));

Feign. A Retryer bean, for all clients or, with the retryer property, for one.

@Bean()
Retryer retryer() => const DefaultRetryer(maxAttempts: 3); // pauses of 150 ms, then 225 ms

What changes: Feign retries only what may succeed later: connection errors, timeouts and answers with Retry-After. An error status alone, such as a plain 503, is not retried unless an ErrorDecoder returns a RetryableException for it. Nothing is retried until a Retryer is declared.

In short

Task platformHttpTransport() dio Feign client
Base URL by hand BaseOptions(baseUrl:) @FeignClient(url:), from configuration
JSON jsonDecode + fromJson decoded data + fromJson automatic for the return type
Header on every call per request interceptor RequestInterceptor bean, or a property
404 a status check DioException, check response?.statusCode FeignNotFound, or dismiss404 gives null
Timeouts connectTimeout, readTimeout, timeout in code connectTimeout, receiveTimeout in code connect-, read-, call-timeout in configuration
Retry a loop dio_smart_retry Retryer bean
Fallback when all fails a catch a catch @FeignClient(fallback:)
Platforms VM, Flutter, web VM, Flutter, web VM, Flutter, web (on the transport)
Tests MockHttpTransport an adapter or a mock library BeanOverride<HttpTransport>(MockHttpTransport())
Build step none none build_runner

For one or two calls in a small app, the transport or dio is less to learn and needs no build step. A Feign client pays off when an app calls many endpoints, when timeouts, headers and retries should be configured per environment, or when the app already runs on Spring for Dart. The two can meet: the Feign starter sends through the HttpTransport bean, so a transport built on dio can carry Feign's calls.

See also