Skip to content
Tutorials Center
My learning

Topics

Lesson 56 of 61 ยท Projects

Project: Typed REST Client

Build a typed REST client in Dart: JSON models with fromJson, sealed API errors, a retry helper with backoff and a client class, with runnable TypeScript stand-ins.

Almost every Dart app talks to a server. A careless client scatters jsonDecode calls and if (response.statusCode == 200) checks everywhere, and the rest of the program has to guess what a Map<String, dynamic> contains. In this project you will build the opposite: a small typed REST client. The rest of the program sees only User objects and a handful of well-named errors, never raw maps or status codes.

The client grows in four stages: models that parse JSON safely, a family of errors, a retry helper with exponential backoff, and finally a UserApi class that ties everything together. The real Dart code is read-only because the site cannot run Dart or open network connections. Each stage has a TypeScript stand-in that you can run, built around a fake transport that returns scripted responses. That fake is exactly how you would test the client in a real project, as Testing with package:test explains.

The plan

Piece Job
User An immutable model with fromJson and toJson. Rejects malformed JSON with a clear message.
ApiException A sealed family of errors: network, HTTP status, bad payload.
retry Runs an async action again when the error is worth retrying, waiting longer each time.
Transport A tiny interface that performs one GET and returns status and body. The real one wraps package:http; tests use a fake.
UserApi The public face: fetchUser(id) returns a User or throws an ApiException.
flowchart LR
    A["App code"] --> B["UserApi"]
    B --> C["retry"]
    C --> D["Transport"]
    D --> E["Server or fake"]
    B --> F["User.fromJson"]

The app only talks to UserApi. Retrying, transport and parsing are hidden details.

Stage 1: models that parse safely

A response body is just text until you decode it. After jsonDecode you hold Object?, which could be a map, a list, a number or null. The model's fromJson factory is the one place that checks the shape. Dart 3 patterns make that check short:

DART
class User {
  const User({required this.id, required this.name, this.email});

  final int id;
  final String name;
  final String? email;

  factory User.fromJson(Object? json) {
    if (json is Map<String, Object?> &&
        json case {'id': int id, 'name': String name}) {
      return User(id: id, name: name, email: json['email'] as String?);
    }
    throw FormatException('Not a valid user', json);
  }

  Map<String, Object?> toJson() => {
        'id': id,
        'name': name,
        if (email != null) 'email': email,
      };

  @override
  String toString() => 'User($id, $name, ${email ?? "no email"})';
}

The map pattern {'id': int id, 'name': String name} succeeds only when both keys exist and hold the right types. email is optional, so it is read separately with a nullable cast. If anything is wrong the factory throws a FormatException, which carries the offending value for debugging. The TypeScript stand-in does the same job with explicit typeof checks, because TypeScript has no map patterns:

TypeScript Stage 1: a model that validates its JSON (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Notice that the last line round-trips: a user without an email serializes without an email key, mirroring Dart's if (email != null) 'email': email collection-if.

Stage 2: a sealed family of errors

Callers do not want to catch SocketException, TimeoutException and FormatException separately and then also inspect status codes. Convert everything into one error type with three flavors. A sealed class lets a switch verify that you handled every flavor:

DART
sealed class ApiException implements Exception {
  const ApiException(this.message);
  final String message;

  bool get isRetryable;

  @override
  String toString() => '$runtimeType: $message';
}

final class NetworkException extends ApiException {
  const NetworkException(super.message);
  @override
  bool get isRetryable => true; // the connection may work next time
}

final class HttpStatusException extends ApiException {
  const HttpStatusException(this.statusCode)
      : super('Server answered with status $statusCode');
  final int statusCode;

  @override
  bool get isRetryable => statusCode >= 500 || statusCode == 429;
}

final class BadPayloadException extends ApiException {
  const BadPayloadException(super.message);
  @override
  bool get isRetryable => false; // asking again returns the same bad data
}

The key design decision is isRetryable. A 503 (service unavailable) or 429 (too many requests) deserves another attempt. A 404 (not found) or a malformed body does not: retrying only wastes time. Keeping that rule inside the error type means the retry helper does not need to know anything about HTTP.

TypeScript Stage 2: classifying errors (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The union type plus the never assignment in describe is the TypeScript counterpart of Dart's exhaustive switch on a sealed class: add a fourth error class to the union and the compiler points at the function you forgot to update.

Stage 3: retry with exponential backoff

A retry loop needs three things: a limit, a rule for what is worth retrying, and a growing pause so that a struggling server is not hammered. Exponential backoff doubles the wait after every failure: 200 ms, 400 ms, 800 ms. The helper below is generic, so it works for any async action:

DART
Future<T> retry<T>(
  Future<T> Function() action, {
  int maxAttempts = 3,
  Duration baseDelay = const Duration(milliseconds: 200),
}) async {
  for (var attempt = 1; ; attempt++) {
    try {
      return await action();
    } on ApiException catch (e) {
      if (!e.isRetryable || attempt >= maxAttempts) rethrow;
      await Future<void>.delayed(baseDelay * (1 << (attempt - 1)));
    }
  }
}

rethrow keeps the original stack trace, which throw e would reset. Only ApiExceptions are caught here: a bug such as a StateError is not something to retry, so it passes straight through. The stand-in injects the pause as a function, so the demo records the delays instead of actually sleeping. That makes the output deterministic:

TypeScript Stage 3: a retry helper with backoff (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Stage 4: the transport and the client

Now put the pieces behind a small interface. The transport does one thing: send a GET and report the status and body. Everything that can go wrong at that level (no connection, timeout) becomes a NetworkException:

DART
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;

abstract interface class Transport {
  Future<({int status, String body})> get(Uri url);
}

class HttpTransport implements Transport {
  HttpTransport([http.Client? client]) : _client = client ?? http.Client();
  final http.Client _client;

  @override
  Future<({int status, String body})> get(Uri url) async {
    try {
      final response =
          await _client.get(url).timeout(const Duration(seconds: 5));
      return (status: response.statusCode, body: response.body);
    } on TimeoutException {
      throw const NetworkException('Request timed out');
    } on SocketException catch (e) {
      throw NetworkException(e.message);
    }
  }
}

The return type is a named record, which avoids writing a class for two values. The client then combines transport, retry and parsing:

DART
class UserApi {
  UserApi(this._transport, this._baseUrl);
  final Transport _transport;
  final Uri _baseUrl;

  Future<User> fetchUser(int id) {
    return retry(() async {
      final response = await _transport.get(_baseUrl.resolve('users/$id'));
      if (response.status != 200) {
        throw HttpStatusException(response.status);
      }
      try {
        return User.fromJson(jsonDecode(response.body));
      } on FormatException catch (e) {
        throw BadPayloadException(e.message);
      }
    });
  }
}

Future<void> main() async {
  final api = UserApi(HttpTransport(), Uri.parse('https://api.example.com/'));
  try {
    print(await api.fetchUser(1));
  } on ApiException catch (e) {
    print('Could not load user: $e');
  }
}

Only the transport knows about package:http, so replacing it with a fake needs no change to UserApi. The final stand-in puts everything together in one self-contained program with a scripted fake server:

TypeScript Stage 4: the complete client with a fake server (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Read the output against the script. User 2 needed two retries; users 3 and 4 failed immediately because those errors are permanent; user 5 hit the attempt limit; user 6 has no scripted response, so the fake behaves like a refused connection and is retried until the limit.

Ideas to extend the client

  • Add createUser with a POST and a JSON body, and decide which failures are safe to retry (a repeated POST can create a duplicate, so usually none without an idempotency key).
  • Add jitter: multiply each delay by a random factor between 0.5 and 1.5 so many clients do not retry in lockstep.
  • Add a fetchUsers method that decodes a JSON list with .map(User.fromJson).toList().
  • Write real tests against a fake Transport, exactly like the stand-in does.
  • Honor the Retry-After header when the server sends it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does ApiException expose an isRetryable property?

    Each error type knows whether asking again could help. The generic retry helper only asks the question, so it stays independent of HTTP status codes.
  2. 2. Which failure should NOT be retried?

    A 404 will answer the same way next time, so retrying wastes time. The other three are usually temporary.
  3. 3. What is the benefit of putting UserApi behind a Transport interface?

    Because UserApi only depends on the interface, a fake with scripted responses can replace the real HTTP client in tests and demos.
  4. 4. What does exponential backoff do?

    Growing delays give a struggling server room to recover instead of hitting it with a steady stream of requests.

Summary

  • Parse JSON in one place (fromJson) and turn malformed data into a clear error, so the rest of the program only sees typed objects.
  • A sealed error family with an isRetryable flag lets callers handle failures with one catch and an exhaustive switch.
  • A generic retry with exponential backoff retries only the errors worth retrying and uses rethrow to keep the stack trace.
  • A small Transport interface keeps package:http in one class and makes the client testable with a fake.
  • Return plain records for small multi-value results such as status and body.

Next, sharpen your skills with the exercises in Practice: Basics and Control Flow.