Darter

Darter logo

A dart/flutter skeleton for wrapping an HTTP API: you describe each endpoint as a typed value, and a client turns that description into a request, sends it through a transport you supply, and decodes the response. (just like aphid, but dart)

Note: there will be no dung-beetle equivalent for this template as there are already a bunch of API parsers and builders that already exist. Should there be a template that Smiduweorc will use it will be a generic one that will use swagger_parser or build_runner.

Darter is not a package you depend on. It is a template you copy, rename, and fill with your own API's endpoints; the result is your package. The pubspec.yaml says publish_to: none so the template itself cannot be published by accident.

What you get is a pure Dart package with one runtime dependency, package:http, so the wrapper you build runs in a Flutter app, on the Dart VM and on the web. Importing it opens no connection, reads no environment and prints nothing.

Starting a wrapper from this template

Requires Dart 3.13 or later, plus lefthook and git-cliff on your PATH.

  1. Copy this directory, then run git init, lefthook install and dart pub get.
  2. Rename the package: name in pubspec.yaml, the entry point lib/darter.dart, and every package:darter/ import. Update description and repository too.
  3. Replace lib/src/resources/example.dart with your first resource (see Writing a wrapper), then update the export lines in the entry point and replace test/example_test.dart and example/example.dart.
  4. If your wrapper is going to pub.dev, delete publish_to: none from pubspec.yaml. If it stays private (a path or git dependency of your own apps), keep it.

Not included

The wrapper builds the request, sends it once through the caller's http.Client, and reports what came back. Everything else is left to the consumer:

  • Retries and backoff. Use RetryClient from package:http/retry.dart or another http.BaseClient wrapper (see Where the excluded behaviour goes).
  • Caching and request deduplication. Use an http.BaseClient wrapper or the data layer above the wrapper.
  • Circuit breakers and rate limiting. Their state is process-wide, so they belong in an http.BaseClient wrapper shared with the rest of the process.
  • Pooling, proxies, TLS and timeouts. They come from the http.Client the consumer passes (IOClient, BrowserClient, cupertino_http, cronet_http); per-call cancellation is the abortTrigger argument.
  • Input validation. The API already checks its inputs; the types say what it accepts.
  • Logging and metrics. Use an http.BaseClient wrapper, which sees every request and response.
  • Reading configuration from the environment. Platform.environment does not exist on the web; the consumer passes the base URL and headers to the constructor.
  • Closing the http.Client. The caller made it and may share it.

Unlike aphid, a response of the wrong shape is an error: Dart's fromJson builds a real object and checks every field it reads, so a mismatch is a DecodeException.

What using your wrapper looks like

This is the code the people depending on your wrapper write, shown with the example resource. Replace your_api with your package's name.

  1. Create one http.Client for the life of the app, and one ApiClient per API on top of it:

    import "package:http/http.dart" as http;
    import "package:your_api/your_api.dart";
    
    final httpClient = http.Client();
    final api = ApiClient(
      baseUrl: Uri.parse("https://api.example.com/v1"),
      httpClient: httpClient,
      headers: {"authorization": "Bearer $token"},
    );
    
  2. Send an operation and handle the failure you care about:

    try {
      final page = await api.request(listExamples(perPage: 50));
      print("${page.examples.length} of ${page.total}");
    } on HttpStatusException catch (error) {
      if (error.statusCode != 404) rethrow;
      // error.body holds the API's own error payload.
    }
    
  3. Close the http.Client when nothing uses it any more:

    httpClient.close();
    

example/example.dart is the same flow against a canned response, so dart run example/example.dart runs without a network.

Writing a wrapper

Operations and the client

An operation is a plain value. Building one touches nothing, which is what makes the request side testable without a network:

Operation<User> getUser(String id) => Operation(
  method: HttpMethod.get,
  path: "/users/${Uri.encodeComponent(id)}",
  decode: (response) => User.fromJson(readJson(response)),
);

ApiClient.request joins path onto the base URL (a base of https://api.example.com/v1 keeps its /v1), appends query, layers the client's headers first, then the operation's, then the call's, sends the request once, and hands a 2xx response to decode.

Adding an endpoint

Copy lib/src/resources/example.dart. Each resource file holds the model classes for one part of the API and one top-level function per endpoint. The functions return operations and perform no I/O, so their tests assert on values.

  • Request parameters are Dart named parameters, mapped to the API's wire names in query or the body (perPage becomes per_page). A null query value is left out, so optional filters need no if.
  • Response models are final classes with a fromJson factory that matches the payload with a map pattern. A missing field or a wrong type falls through to throw FormatException, and the client reports it as a DecodeException carrying the raw body. Fields are renamed to lowerCamelCase, because fromJson is a mapping you are writing anyway.
  • Use readJson(response), not jsonDecode(response.body). For any content type other than application/json without a charset, response.body decodes as Latin-1 and garbles every non-ASCII character; readJson decodes the bytes as UTF-8, which RFC 8259 requires of JSON.
  • A JSON body is jsonEncode(...) plus headers: {"content-type": "application/json"}. A Map<String, String> body is sent as form fields, a List<int> as raw bytes.
  • An endpoint with no response body is an Operation<void> with decode: (_) {}.

With dozens of models, json_serializable can generate the fromJson factories. This template has no code generation.

Exceptions

Every failure the client reports is an ApiException. The type is sealed, so a switch over the three subtypes is exhaustive:

Type Thrown when Carries
TransportException The http.Client threw before a complete response arrived: connection refused, DNS failure, TLS error, a body cut off mid-stream, an abort. method, url, cause
HttpStatusException The API answered with a status outside 200 to 299. method, url, statusCode, reasonPhrase, headers, body
DecodeException decode threw on a 2xx response. method, url, statusCode, body, cause

Each wrapping exception is thrown with the stack trace of its cause, so the trace points at where the failure happened.

These are Exceptions, meant to be caught. In Dart an Error means a bug, so two things are not wrapped:

  • An Error thrown by the http.Client (a bug in a client wrapper) passes through unchanged.
  • A malformed operation (a body or query value of an unsupported type) throws ArgumentError, and a base URL with no scheme or host throws ArgumentError from the constructor.

The one exception is decode: a failed cast there throws TypeError, which is how a wrong-shaped payload shows up, so anything decode throws becomes a DecodeException.

Cancellation and timeouts

request takes an abortTrigger; when that future completes, the request is cancelled and a TransportException is thrown with a RequestAbortedException as its cause. A timeout that releases the connection is:

await api.request(op, abortTrigger: Future.delayed(const Duration(seconds: 10)));

Future.timeout stops waiting but leaves the request running.

Where the excluded behaviour goes

ApiClient calls httpClient.send once per request. Retries, caching, logging and the rest go in an http.Client that wraps another one, so they apply to every call. package:http ships a retrying one:

import "package:http/retry.dart";

final api = ApiClient(
  baseUrl: Uri.parse("https://api.example.com/v1"),
  httpClient: RetryClient(http.Client(), retries: 2),
);

RetryClient retries a 503 for every method by default, POST included; pass when if your API's writes are not idempotent. A static key or token goes in the client's headers; a credential that has to be refreshed belongs in an http.BaseClient wrapper that sets the header on each send.

Tooling

lib/darter.dart is the only entry point and exports from lib/src/ with show; anything not shown is private. Lints are package:lints recommended plus the strict modes and rules in analysis_options.yaml. dart format cannot indent with tabs, so the repo uses spaces. Tests use MockClient from package:http/testing.dart and import package:darter/darter.dart, as a consumer does. dart doc output in doc/api/ is published to GitHub Pages by .github/workflows/pages.yml.

The lefthook pre-commit hook checks formatting and runs the analyzer; the commit-msg hook runs tool/check-commit-msg.sh, which accepts the @commitlint/config-conventional types without Node. CI runs formatting, analysis, tests and the example on Linux, macOS and Windows against Dart 3.13.0 and the latest stable, plus the tests in Chrome on Linux.

Releasing your wrapper

For a wrapper going to pub.dev, .pubignore keeps the tooling (.github/, tool/, hooks, release and changelog config) out of the upload. To cut a release, ./release.sh v[X.Y.Z] sets version in pubspec.yaml, regenerates CHANGELOG.md, commits, and creates an annotated tag. Then:

git push && git push --tags
dart pub publish

Known quirks

  • CI skips the publish dry run while version is 0.0.0, because pub rejects a changelog with no entry for the current version, and while publish_to: none is set, because there is nothing to publish.
  • pubspec.lock is not committed, as is usual for a library: CI resolves the newest versions the ranges allow, which is what a consuming app gets.
  • HttpStatusException.body and DecodeException.body are decoded as UTF-8 whatever the response's charset, with malformed bytes replaced. An API that answers errors in Latin-1 will show replacement characters there.
  • MockClient ignores abortTrigger; a test of cancellation has to use MockClient.streaming and throw RequestAbortedException itself, as test/client_test.dart does.

Libraries

darter
Public entry point. Every name exported here is API you have to keep; anything else under lib/src/ is private to the package. The show clauses make adding a name a deliberate edit to this file.