Sub topic 9
Structuring an API Client Class
This chapter assumes you know Dart classes, null safety, named parameters, Future, and async/await. You should also know how to add the http package to pubspec.yaml.
A networking layer keeps HTTP details out of widgets. An API client is a class that knows how to build requests, attach headers, decode responses, and report failures. The UI calls methods such as getPost instead of handling URLs and status codes directly.
Keep responsibilities in one place
A small API client usually owns:
- A reusable
http.Client. - The API base URL.
- Common headers, such as
AcceptandAuthorization. - Request methods for application resources.
- Response validation and JSON decoding.
- Conversion from JSON maps to typed Dart models.
The class should not update widgets or show dialogs. Those jobs belong to the presentation layer.
Inject dependencies
Dependency injection means passing an object into a class instead of creating it inside the class. Injecting http.Client makes the API client easier to test because a test can provide a fake client.
The following example also injects an optional token. The client does not know where the token came from. A session manager, secure storage service, or test can provide it.
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
class Post {
const Post({required this.id, required this.title});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
id: json['id'] as int,
title: json['title'] as String,
);
}
final int id;
final String title;
}
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 httpClient,
required Uri baseUrl,
String? accessToken,
}) : _httpClient = httpClient,
_baseUrl = baseUrl,
_accessToken = accessToken;
final http.Client _httpClient;
final Uri _baseUrl;
final String? _accessToken;
Future<Post> getPost(int id) async {
final uri = _baseUrl.resolve('posts/$id');
try {
final response = await _httpClient.get(
uri,
headers: {
'Accept': 'application/json',
if (_accessToken != null)
'Authorization': 'Bearer $_accessToken',
},
).timeout(const Duration(seconds: 10));
if (response.statusCode < 200 || response.statusCode >= 300) {
throw ApiException(
'The server rejected the request',
statusCode: response.statusCode,
);
}
final json = jsonDecode(response.body) as Map<String, dynamic>;
return Post.fromJson(json);
} on TimeoutException {
throw const ApiException('The request timed out');
} on http.ClientException catch (error) {
throw ApiException('Connection failed: ${error.message}');
}
}
}_baseUrl.resolve joins the base URL with a relative path. Keeping this logic in the client prevents screens from creating slightly different URLs.
Choose an ownership rule
The example receives an http.Client, so the caller owns it. The caller should close it when the application no longer needs it. This rule avoids accidentally closing a client that another service still uses.
For a larger application, separate the client into smaller resource classes, such as PostsApi and UsersApi, while sharing one configured HTTP client. Keep model conversion close to the resource method that uses it.
Exercise
Exercise
Why should an ApiClient receive an http.Client through its constructor instead of creating one inside getPost?
Show answer
Constructor injection lets production code use a real client and tests use a MockClient without making network calls.