Sub topic 9
Structuring an API client class
This chapter assumes you can make a GET request with the http package and decode JSON into a Dart model. It also assumes you have seen ApiException from the error-handling chapter and are comfortable with async/await. Here you move the request code out of widgets and into one class that every screen shares.
Why a client class
Calling http.get from a widget works, but the same details end up repeated in each place:
- the base URL and the
Acceptheader - the
Authorizationheader - the status check
- the timeout
- the translation of low-level failures into your own exception type
Change any of them and you edit every call site. A widget that builds URLs also cannot be tested without the network.
The fix is to split the code into layers, each with one job.
| Layer | Knows about | Does not know about |
|---|---|---|
| Widget | Repository methods, loading and error states | URLs, headers, JSON |
| Repository | Resource paths, model classes | Status codes, timeouts, tokens |
| ApiClient | Base URL, headers, status codes, timeouts | Which models exist |
| `http.Client` | Sockets and bytes | Everything above |
The ApiClient deals only in decoded JSON (Map, List, String, or null). The repository turns that JSON into models. Because of this split, the client can be reused for every resource in the app.
The ApiClient class
The class receives its dependencies through the constructor. It never creates an http.Client itself, which is what makes substitution in tests possible.
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
class ApiException implements Exception {
const ApiException(this.message, {this.statusCode});
final String message;
final int? statusCode;
@override
String toString() => 'ApiException($statusCode): $message';
}
class ApiClient {
ApiClient({
required http.Client client,
required this.baseUri,
this.tokenProvider,
this.timeout = const Duration(seconds: 10),
}) : _client = client;
final http.Client _client;
final Uri baseUri;
final Future<String?> Function()? tokenProvider;
final Duration timeout;
Future<dynamic> get(String path, {Map<String, String>? query}) =>
_send('GET', path, query: query);
Future<dynamic> post(String path, {Object? body}) =>
_send('POST', path, body: body);
Future<dynamic> put(String path, {Object? body}) =>
_send('PUT', path, body: body);
Future<dynamic> patch(String path, {Object? body}) =>
_send('PATCH', path, body: body);
Future<dynamic> delete(String path) => _send('DELETE', path);
Uri _uri(String path, Map<String, String>? query) {
return baseUri.replace(
path: '${baseUri.path}$path',
queryParameters: query,
);
}
Future<dynamic> _send(
String method,
String path, {
Map<String, String>? query,
Object? body,
}) async {
final request = http.Request(method, _uri(path, query));
request.headers['Accept'] = 'application/json';
final token = await tokenProvider?.call();
if (token != null) {
request.headers['Authorization'] = 'Bearer $token';
}
if (body != null) {
request.headers['Content-Type'] = 'application/json; charset=UTF-8';
request.body = jsonEncode(body);
}
try {
final response = await _client
.send(request)
.then(http.Response.fromStream)
.timeout(timeout);
if (response.statusCode < 200 || response.statusCode >= 300) {
throw ApiException(
'Request failed',
statusCode: response.statusCode,
);
}
if (response.bodyBytes.isEmpty) {
return null;
}
return jsonDecode(utf8.decode(response.bodyBytes));
} on TimeoutException {
throw const ApiException('The request timed out');
} on http.ClientException catch (e) {
throw ApiException('Connection problem: ${e.message}');
} on FormatException {
throw const ApiException('The server sent invalid JSON');
}
}
}What each decision buys you
- A single
_sendmethod. Every verb passes through one place. Headers, timeout and error translation are written once. tokenProvideris a function, not a string. The client lives as long as the app, but a token can expire or be refreshed. Calling the function on each request means the client always sends the current value. If the user is logged out, the function returnsnulland noAuthorizationheader is sent.Uri.replacefor query parameters. It percent-encodes values for you, so a search term such asa&bcannot corrupt the URL. IfbaseUrihas a path prefix such as/api/v1, write it without a trailing slash. Paths passed to the client then start with/.utf8.decode(response.bodyBytes). This avoids relying on theContent-Typecharset, which some servers omit.- An empty body returns
null. A204 No Contentreply to a DELETE has nothing to decode, and callingjsonDecode('')would throw aFormatException. - Catching
FormatException. A proxy or captive portal can return an HTML page with status 200. Without this clause the raw exception would escape yourApiExceptiontype.
The http.Request and send pair gives you one code path for all methods. The convenience methods such as client.post build the same kind of request internally.
A repository on top of the client
The repository maps paths and JSON to models. It is the only place that knows /posts exists.
class Post {
const Post({required this.id, required this.title});
factory Post.fromJson(Map<String, dynamic> json) =>
Post(id: json['id'] as int, title: json['title'] as String);
final int id;
final String title;
}
class PostRepository {
const PostRepository(this._api);
final ApiClient _api;
Future<Post> fetch(int id) async {
final json = await _api.get('/posts/$id');
return Post.fromJson(json as Map<String, dynamic>);
}
Future<List<Post>> fetchByUser(int userId) async {
final json = await _api.get(
'/posts',
query: {'userId': '$userId'},
);
return (json as List<dynamic>)
.map((item) => Post.fromJson(item as Map<String, dynamic>))
.toList();
}
Future<Post> create(String title) async {
final json = await _api.post('/posts', body: {'title': title});
return Post.fromJson(json as Map<String, dynamic>);
}
Future<void> delete(int id) => _api.delete('/posts/$id');
}A widget now receives a PostRepository and calls fetch(1). It never imports package:http.
Wiring it together
One http.Client is created at startup and shared. Whoever creates the client is responsible for closing it.
Future<void> main() async {
final httpClient = http.Client();
try {
final api = ApiClient(
client: httpClient,
baseUri: Uri.https('jsonplaceholder.typicode.com'),
tokenProvider: () async => null,
);
final posts = PostRepository(api);
final post = await posts.fetch(1);
print(post.title);
} on ApiException catch (e) {
print('Could not load post: $e');
} finally {
httpClient.close();
}
}In a Flutter app you would create these objects once near the top of the widget tree and pass them down, using constructor parameters, InheritedWidget, or a dependency-injection package. The chapter on FutureBuilder shows a screen that receives its client this way.
Checking that the structure pays off
Because the client is injected, a test can pass in a MockClient and still exercise the full ApiClient path, including headers and error translation. A short example:
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
void main() {
test('adds the bearer token and maps 404 to ApiException', () async {
final mock = MockClient((request) async {
expect(request.headers['Authorization'], 'Bearer abc');
return http.Response('{}', 404);
});
final api = ApiClient(
client: mock,
baseUri: Uri.https('example.com'),
tokenProvider: () async => 'abc',
);
expect(
() => api.get('/missing'),
throwsA(isA<ApiException>().having((e) => e.statusCode, 'status', 404)),
);
});
}The testing chapter covers this in more depth.
Common errors and trade-offs
- Returning
dynamicfrom the client. This is deliberate, because the client cannot know the shape of the response. Contain it: cast toMap<String, dynamic>orList<dynamic>in the repository, and never passdynamicto widgets. A bad cast throws aTypeError, not anApiException. If you want to surface schema mismatches as API errors, catchTypeErrorin the repository. - Creating
http.Client()insideApiClient. It works, but you lose the ability to substitute a mock, so tests would hit the real network. - Putting resource paths in the client. A method such as
ApiClient.getPostcouples the client to one resource. After ten resources the class is hard to maintain. Keep the client generic and put resource knowledge in repositories. - Reading the token once at construction. The client keeps sending an expired token. Use the provider function.
- Reading the error body. The client above reports only the status code. Many APIs return a JSON message explaining the failure. If yours does, decode the body inside the non-2xx branch and put its message into
ApiException, guarded so that a non-JSON body does not hide the real status. - Retrying inside
_sendfor every method. Retrying a GET is normally safe. Retrying a POST can create duplicates. Add retries only for idempotent methods, as the retries chapter explains. - One giant file. The split above, with
ApiExceptionandApiClientin one file and each repository in its own file, keeps imports honest. Only the files that needpackage:httpimport it.
Exercise
The ApiClient takes Future<String?> Function()? tokenProvider instead of String? token. Describe one situation where passing a plain string would cause a bug, and say what ApiClient does when the provider returns null.
Show answer
The ApiClient is created once and lives for the whole app. If the user logs in after it was created, or the token is refreshed, a string captured in the constructor would stay at its old value, so requests would go out with no token or an expired one. The provider function is called for each request, so it returns the current token. When it returns null, _send skips the Authorization header and the request goes out unauthenticated.
Exercise
A DELETE request to /posts/1 returns status 200 with an empty body. What does ApiClient.delete return, and which line of _send prevents an exception?
Show answer
It returns null. The check if (response.bodyBytes.isEmpty) { return null; } runs before jsonDecode, which would otherwise throw a FormatException on an empty string.