DartIntermediate 2 min read

Dart HTTP requests: status, JSON, timeout and client ownership

Call a service through an owned client and verify its response contract before parsing.

On this page

An HTTP success is more than receiving bytes. Check the status, decode the expected representation and validate its shape. Keep the client owned by an application service so tests can replace transport without calling a public API.

Create a local client package

Run dart create -t console http_lab, enter that directory and add http with dart pub add http. The fragment below belongs in a service library; it is not a complete entry point.

import 'dart:convert';
import 'package:http/http.dart' as http;

Future<List<Object?>> loadTasks(http.Client client, Uri base) async {
  final response = await client.get(base.resolve('/tasks'))
      .timeout(const Duration(seconds: 5));
  if (response.statusCode != 200) {
    throw StateError('Task request failed with ${response.statusCode}.');
  }
  final payload = jsonDecode(utf8.decode(response.bodyBytes));
  if (payload case {'items': List<Object?> items}) return items;
  throw const FormatException('Expected an items list.');
}

The owner creates one client and closes it in a finally block or service disposal. A request helper should not close a caller-owned client after every method call. Use the task API project as a local endpoint instead of depending on an unrelated public demo service.

Follow the failure boundary

Transport errors, timeouts, non-success status codes and invalid JSON are different failures. Convert them into a stable application result at the layer that decides recovery. Do not show raw server bodies or credentials in a user-facing error.

A timeout does not necessarily stop a request. Retrying a POST after a timeout can duplicate a server action; use a documented idempotency contract when needed. Bounded retries with backoff belong only on operations and failures that are safe to retry.

Test without a remote service

The package’s MockClient can return a response from a request callback. Verify a valid list, a 500 response and malformed JSON. Then run one loopback integration check against your own service. CORS applies to browser clients and is configured by the server; changing this Dart parser does not grant cross-origin access.

Exercise

Add a typed task parser and verify each item. Test that malformed data produces a deliberate error instead of an empty successful list. Record who closes the client and how the user can retry a recoverable failure.

How this topic connects

Apply it next

Lesson progressMark complete after checking the example and exercise.

Find your next idea

Search lessons, code examples and projects.

Type a few words to start exploring.