Methods

Each method of a @FeignClient interface describes one endpoint. Its mapping annotation gives the HTTP method and the path, its parameters' annotations say where each argument goes, and its return type says how the response is read. The annotations are the same as a controller's.

Why

A client written with the server's own vocabulary reads like the API it calls, and a developer who knows controllers already knows how to write it. Because the generator sees the method, the starter checks it when the application starts, so a typo in a path variable fails at once, not at the first call.

Example

@FeignClient('catalog', url: r'${catalog.url}', path: '/api')
abstract interface class CatalogClient {
  // GET https://.../api/books/978-0
  @GetMapping('/books/{isbn}')
  Future<Book?> find(@PathVariable() String isbn);

  // GET /api/books?q=dune&tag=sf&tag=classic; page left out when null
  @GetMapping('/books')
  Future<List<Book>> search(
    @RequestParam('q') String query,
    @RequestParam('tag') List<String> tags, {
    @RequestParam() int? page,
  });

  // One query parameter per entry.
  @GetMapping('/books/filter')
  Future<List<Book>> filter(@RequestParam() Map<String, Object?> filters);

  // Fixed headers, with a placeholder; a header and a cookie per call.
  @PutMapping.of(path: '/books/{isbn}', headers: [r'X-Shop=${shop.name}'])
  Future<ResponseEntity<Book>> update(
    @PathVariable() String isbn,
    @RequestBody() Book book,
    @RequestHeader('If-Match') String etag,
    @CookieValue('SESSION') String? session,
  );

  // The raw response, whatever its status.
  @RequestMapping.of(path: '/books/{isbn}', method: HttpMethod.head)
  Future<HttpResponse> probe(@PathVariable() String isbn);
}

Mapping annotations

Annotation Request
@GetMapping('/books/{isbn}') GET
@PostMapping('/books') POST
@PutMapping, @PatchMapping, @DeleteMapping PUT, PATCH, DELETE
@RequestMapping.of(path: '/x', method: HttpMethod.head) any method (GET by default)

With a path, these attributes are written with the .of constructor, because a Dart constructor cannot have both an optional positional parameter and named ones: @GetMapping.of(path: '/books', headers: ['X-Shop=neon']).

Parameters

Parameter Goes to
@PathVariable() String isbn {isbn} in the path, URL-encoded. A / stays a / (see decode-slash). @PathVariable('id') for another name. A value . or .. throws an ArgumentError, as it would change the path.
@RequestParam('q') String query ?q=...; null is left out, a List repeats the parameter.
@RequestParam() Map<String, Object?> filters One query parameter per entry; a List value repeats it, null is left out.
@RequestHeader('X-Trace') String? trace A header; null is left out, a List gives several values.
@RequestHeader() Map<String, String> headers One header per entry.
@CookieValue('SESSION') String session A cookie. All cookies of a call go in one Cookie: a=1; b=2 header; null is left out.
@RequestBody() Book book The body: an object as JSON, a String as text, a Uint8List as bytes; a form with consumes: MediaType.applicationFormUrlencoded.
@RequestPart('file') MultipartFile file One part of a multipart/form-data body (see Files and multipart).
a parameter without annotation The body; only one such parameter is allowed.

Whether an argument may be left out follows from the Dart parameter, not from required and defaultValue attributes:

Parameter An argument of null
nullable (String? sort) the query parameter, header or part is left out; a path variable becomes an empty string
with a default value ({String sort = 'asc'}) not possible; without an argument, the default is sent
non-nullable not possible

Paths, query parameters, headers and cookies take single values or lists of them. Enums, DateTime and similar values are written as in JSON: an enum by its name or its @JsonValue, a date in ISO 8601. A parameter whose type is an object (@RequestParam() Book book) stops the application at startup: pass its fields as separate parameters or as a Map. When only the runtime value can tell (a parameter of type Object), an object fails the call with an EncodeException. Spaces in query parameters are sent as +.

Results

Return type From the response
Future<Book>, Future<List<Book>>, Future<Map<String, int>> The JSON body, read through the ObjectMapper.
Future<Book?> null for an empty body (or a 404 with dismiss404).
Future<void> Nothing; the status must be 2xx.
Future<String>, Future<Uint8List> The body as text, or as bytes.
Future<ResponseEntity<Book>> The status, the headers (read-only) and the body.
Future<ResponseEntity<void>> The status and headers; the body is ignored.
Future<HttpResponse> The raw response, whatever its status: no error decoding, no dismiss404 (Feign's Response).
EventStream<OrderEvent>, Stream<OrderEvent> The events of a text/event-stream response (see Server-sent events).
Stream<List<int>> The body of the answer as it arrives, whatever its content type (a large file): one request per listener, Accept: */* unless produces says otherwise, a failed status as the error decoder's exception, no reconnection.

Future<Uint8List> reads the whole body before it returns; Stream<List<int>> does not. A request body is always read whole before it is sent.

A non-nullable result with an empty body, or a body that does not fit the type, throws a DecodeException.

Form bodies

Some APIs, such as login endpoints, expect an HTML-form body. With consumes: MediaType.applicationFormUrlencoded, the body parameter is sent as name=value pairs: the entries of a Map, or the properties of an object as the ObjectMapper writes them (@JsonProperty names). The pairs are URL-encoded in the charset of the content type (UTF-8 by default), a List value repeats the name, and null values are left out. A nested object fails the call with an EncodeException.

@PostMapping.of(path: '/login', consumes: MediaType.applicationFormUrlencoded)
Future<void> login(@RequestBody() Map<String, String> form);
// sends: username=neo&password=s3cr%3Ft

Checked at startup

Every client is checked when it is created. The application stops with the reasons when it finds:

Invalid Feign client CatalogClient:
  - CatalogClient.find: the path variable {isbn} of "/books/{isbn}" has no @PathVariable parameter

In Spring (Java)

@GetMapping("/books")
List<Book> search(@RequestParam("q") String query, @RequestParam(required = false) Integer page);

The annotations are Spring's. Methods return Futures; optional arguments come from nullable Dart parameters; a method may have several Map parameters (Feign: one query map and one header map). @SpringQueryMap is not here yet.

See also