app http client
app http client is a wrapper around the http library dio to make network requests and error handling simpler, more predictable, and less verbose.
tutorial
note: this tutorial is the first of a multipart series where we craft an auth-enabled app that provides both anonymous and authenticated user flows while storing data in the cloud. the author makes her best attempt to provide insight into best practices whenever and wherever possible.
ever wondered how to build a simple http client for your flutter application? in this tutorial, we’ll create a wrapper around the multi-platform http library dio, which supports interceptors, global configuration, form data, request cancellation, file downloading, and timeouts—just about everything you’ll ever need.
why?
why create an http client wrapper? the answer is essentially “to make error handling easy and predictable.” a typical state-driven application benefits from a clearly defined, finite set of errors.
as part of this app development series, we will leverage this client in a later tutorial to build our application service layer, domain layer, and state management—all of which will benefit from the error resolution this wrapper will provide.
by carefully catching dio errors and transforming them into simple errors that our application cares about, we can drastically simplify error handling in our application state—and, as you know, simple code is easier to test. since we use bloc for our state management, we will construct our wrapper in such a way that makes error handling inside our blocs painless.
even if you’re taking a different approach, we hope you will find the organizational techniques presented here useful for your application, regardless of the http library and state management framework you are using.
create a dart package
we plan on reusing this http client wrapper, so let’s make it a package. all we need to do is create a dart package (not a flutter one). we’ll call it app_http_client
so we can use it in our apps, but you can call yours whatever you want. ![wink](https://github.githubassets.com/images/icons/emoji/unicode/1f609.png =20×20)
creating a package with dart is fairly straightforward (once you know the required command line flags):
dart create --template package-simple app_http_client
cd app_http_client
git init
# open vs code from the terminal, if you've installed the vs code shell extensions:
code .
to run tests with coverage, you will need to add the following to the .gitignore
file:
# code coverage
coverage/
test/.test_coverage.dart
dependencies
before we start coding, let’s setup our dependencies.
production dependencies
- dio—since we’re creating a wrapper for dio, we’ll need to include it.
development dependencies
- test_coverage—allows us to easily gather test coverage.
- very good analysis—we’ll use these linter rules as a development dependency to keep our codebase clean and consistent looking.
- mocktail—provides null-safe mocking capabilities, inspired by mockito.
let’s add the dependencies to the pubspec.yaml:
dependencies:
dio: ^4.0.0
dev_dependencies:
test: ^1.16.0
test_coverage: ^0.5.0
mocktail: ^0.1.4
very_good_analysis: ^2.1.2
make sure you’ve removed the pedantic
development dependency from pubspec.yaml
that dart automatically adds when you create a new project.
replace the contents of analysis_options
with the following:
include: package:very_good_analysis/analysis_options.yaml
finally, you may want to create a .vscode
folder in the root of the project with a launch.json
file so that you can run tests:
{
"version": "0.2.0",
"configurations": [
{
"name": "run tests",
"type": "dart",
"request": "launch",
"program": "./test/"
},
]
}
run the following and you’ve got yourself a new project:
flutter pub get
git add . # add all files
git commit -m "initial commit"
to run tests with test coverage, you can use the following:
dart run test_coverage && genhtml -o coverage coverage/lcov.info
open coverage/index.html
the problem
imagine you have a very simple service class which fetches data from your team’s backend servers, perhaps something like this:
import 'package:dio/dio.dart';
class userservice {
userservice({required this.client});
final dio client;
future<map<string, dynamic>?> createuser({
required string email,
required string password,
}) async {
final response = await client.post<map<string, dynamic>>('/users', data: {
'email': email,
'password': password,
});
return response.data;
}
}
while this code is simple and friendly looking, it is lacking a few critical details. notably, there is no easy way to handle errors it throws. catching errors inside each of the service’s methods would likely result in duplicate code, and catching the errors above the service would force the abstraction layers above the service layer to handle dio-specific errors.
currently, any errors thrown by the http library—in this case, dio—will propagate upwards to the function where the userservice
is being called. such error propagation is often intended—but what if your server produces validation errors that you want to catch? where do you intercept those?
to complicate matters further, how do you go distinguish between expected validation errors from your server which might contain certain failing http status codes on purpose, and other failing requests—such as network errors or other runtime errors—thrown by your http client library?
because backend error responses are often consistent across multiple api routes, the practice of always handling errors on a case-by-case basis can result in redundant code that is painful to test.
what follows is what each service method might look like if we put a try
/catch
clause in it. for the sake of brevity, we’ve omitted any custom error handling that might be necessary and left a comment and a rethrow
statement where you might otherwise find more error handling in a real application.
future<map<string, dynamic>?> createuser({
required string email,
required string password,
}) async {
try {
final response = await client.post<map<string, dynamic>>('/users', data: {
'email': email,
'password': password,
});
return response.data;
} catch (e) {
// check which type of error e is, unwrap error response data,
// throw custom exceptions, etc
rethrow;
}
}
programmers often avoid this problem—like any other architecture problem—by introducing another abstraction layer. you may recognize this as the classic adapter or decorator pattern.
in this case, we avoid most redundant error handling clauses in a rather elementary way by simply creating a class that wraps the http library of choice.
while it is a bit tedious, it can make error handling code much simpler and more concise. additionally, the developers creating services which use the wrapper to make network requests don’t need to remember the details of backend services which utilize common response schemas.
if we make it easy for the wrapper to handle errors with enough flexibility, we can drastically reduce the complexity of error handling for a given app. if needed, each service can utilize a different http client wrapper to provide custom error handling for groups of api requests which may have similar backend response schemas.
hopefully, the code presented here will prevent you from having to suffer through much of the required monotony, as you may copy and paste to your liking freely under the mit license.
considering errors
to catch an error, one must understand the kinds of errors which can be caught. let’s pause for a moment and describe the errors a network application might be interested in.
at its core, our applications are interested in 3 basic kinds of errors:
- network errors
- sometimes well-formed requests fail through no fault of their own, due to extraneous network conditions, dropped packets, poor signals, busy servers, etc.
- response errors
- the request was received by the server, but the server returned a bad response—presumably with an http status code indicative of the problem. validation errors, redirects, poorly formed requests, requests without proper authorization, etc, can all be responsible for rejection from the server.
- as far as application state logic is concerned, these errors are most likely to have a practical use. perhaps your backend form validation system relies on certain error schemas to be returned from your servers to describe invalid fields that were submitted.
- other / runtime errors
- other errors in the http library or service layer code can cause problems—tracking these is important for developers, but as far as users are concerned, these are largely equivalent to a network error if it doesn’t completely break the application.
we want errors generated by our http library to be transformed into one of these 3 types of errors. to facilitate this, we need to create 3 error classes.
for the sake of convenient error handling in our application, we consider a response error a subtype of a network error. placing errors into the following class hierarchy should allow for greatly simplified state management:
┌──────────────────────────┐
│ apphttpclientexception │
└──────────────────────────┘
▲
│
┌──────────────────────────┐
│ appnetworkexception │
└──────────────────────────┘
▲
│
┌───────────────────────────────┐
│ appnetworkresponseexception │
└───────────────────────────────┘
apphttpclientexception
is the base class. for any error generated by our wrapper, the expression (error is apphttpclientexception)
should always be true
.
let’s take a look at the implementation:
class apphttpclientexception<originalexception extends exception>
implements exception {
apphttpclientexception({required this.exception});
final originalexception exception;
}
pretty straightforward—we require the original exception in the constructor of apphttpclientexception
so that developers are able to easily debug errors specific to the http library being used.
additionally, developers writing app-specific subclasses of apphttpclientexception
can pass other exceptions in which further represent the type of error, if needed.
we can describe the network exception just as simply:
enum appnetworkexceptionreason {
canceled,
timedout,
responseerror
}
class appnetworkexception<originalexception extends exception>
extends apphttpclientexception<originalexception> {
/// create a network exception.
appnetworkexception({
required this.reason,
required originalexception exception,
}) : super(exception: exception);
/// the reason the network exception ocurred.
final appnetworkexceptionreason reason;
}
finally, we can create a class for network response errors:
class appnetworkresponseexception<originalexception extends exception, datatype>
extends appnetworkexception<originalexception> {
appnetworkresponseexception({
required originalexception exception,
this.statuscode,
this.data,
}) : super(
reason: appnetworkexceptionreason.responseerror,
exception: exception,
);
final datatype? data;
final int? statuscode;
bool get hasdata => data != null;
/// if the status code is null, returns false. otherwise, allows the
/// given closure [evaluator] to validate the given http integer status code.
///
/// usage:
/// ```
/// final isvalid = responseexception.validatestatuscode(
/// (statuscode) => statuscode >= 200 && statuscode < 300,
/// );
/// ```
bool validatestatuscode(bool function(int statuscode) evaluator) {
final statuscode = this.statuscode;
if (statuscode == null) return false;
return evaluator(statuscode);
}
}
developers are encouraged to subclass appnetworkresponseexception
for app-specific response errors. more on that later.
now that our basic error hierarchy is in place, it’s time to create the http client wrapper class.
creating the http client wrapper
we want our wrapper to receive a pre-configured dio instance so that the code instantiating the wrapper has full control over network requests. by injecting a dio instance into our wrapper, it encourages developers to take advantage of everything dio has to offer—like request interceptors.
our wrapper should provide a method for each http request method like get
, post
, put
, patch
, etc. these methods should pass their parameters through to the dio instance and perform relevant error handling by catching errors in a uniform way.
note: dio exposes a lot of methods, but we are only interested in wrapping the methods that use a string
path as opposed to a uri
, which seems overly complex in this scenario.
let’s make a class that meets our criteria:
/// a callback that returns a dio response, presumably from a dio method
/// it has called which performs an http request, such as `dio.get()`,
/// `dio.post()`, etc.
typedef httplibrarymethod<t> = future<response<t>> function();
/// function which takes a dio response object and optionally maps it to an
/// instance of [apphttpclientexception].
typedef responseexceptionmapper = appnetworkresponseexception? function<t>(
response<t>,
exception,
);
class apphttpclient {
apphttpclient({required dio client, this.exceptionmapper}) : _client = client;
final dio _client;
final responseexceptionmapper? exceptionmapper;
/// http get request.
future<response<t>> get<t>(
string path, {
map<string, dynamic>? queryparameters,
options? options,
canceltoken? canceltoken,
progresscallback? onreceiveprogress,
}) {
return _mapexception(
() => _client.get(
path,
queryparameters: queryparameters,
options: options,
canceltoken: canceltoken,
onreceiveprogress: onreceiveprogress,
),
);
}
// ...
//
// see repository for full implementation
//
// ...
future<response<t>> _mapexception<t>(httplibrarymethod<t> method) async {
try {
return await method();
} on dioerror catch (exception) {
switch (exception.type) {
case dioerrortype.cancel:
throw appnetworkexception(
reason: appnetworkexceptionreason.canceled,
exception: exception,
);
case dioerrortype.connecttimeout:
case dioerrortype.receivetimeout:
case dioerrortype.sendtimeout:
throw appnetworkexception(
reason: appnetworkexceptionreason.timedout,
exception: exception,
);
case dioerrortype.response:
// for dioerrortype.response, we are guaranteed to have a
// response object present on the exception.
final response = exception.response;
if (response == null || response is! response<t>) {
// this should never happen, judging by the current source code
// for dio.
throw appnetworkresponseexception(exception: exception);
}
throw exceptionmapper?.call(response, exception) ??
appnetworkresponseexception(
exception: exception,
statuscode: response.statuscode,
data: response.data,
);
case dioerrortype.other:
default:
throw apphttpclientexception(exception: exception);
}
} catch (e) {
throw apphttpclientexception(
exception: e is exception ? e : exception('unknown exception ocurred'),
);
}
}
}
the error handling mechanism
the real meat-and-potatoes of our wrapper is hiding in the private method _mapexception()
. it takes one parameter named method
which is a callback (that should call a dio method).
the _mapexception
proceeds to return the awaited callback’s result via return await method();
, catching any errors in the process. if no errors occur, it just returns whatever the callback returned (which in this case will be the response object returned by the dio method that the callback called).
if an error occurs, things get much more interesting. the error handling that takes place inside the wrapper is dependent on your http library of choice. since we’re using dio, we know that dio already wraps all of its errors into dioerror
objects.
dio’s errors are perfectly decent, but we don’t want the error handling our app’s codebase to be directly tied to any particular http library. if you need to change the http library you’re using, it’s much easier to write another wrapper class which satisfies a similar interface than it is to hunt for http-library-specific error handling throughout the app’s code.
note: there is one caveat—because our methods directly wrap dio’s methods, the parameters have types which are only found inside the dio library, such as options
, canceltoken
, progresscallback
, etc. our app’s service code which calls our wrapper will still be tied to dio when it passes in these objects, but changing such details strictly within the service layer should be fairly straightforward in the event of swapping over to another wrapper and http library.
we could have stopped and written a platform-agnostic http request interface library, but the payoff for doing so would be minimal compared to the enormous effort required. while it would spare you from having to touch any service code at all if you suddenly switched http libraries, swapping dependencies like that just doesn’t seem like a frequent enough occurrence to merit an entire library of carefully constructed interfaces. you’d also have to create and maintain the mappings from the platform-agnostic classes to the platform specific ones for every http library you intended to support…
the rest of _mapexception
proceeds to map each type of dio error into one of the 3 types of errors we care about. everything is fairly straightforward, with the exception of response errors.
our wrapper would not be very useful if that was all it did. the main reason we created the wrapper is to allow the code using the wrapper to provide custom response error handling. the _mapexception
method uses some optional chaining and null coalescing operators to delegate any dio response error containing a valid response object (with the expected response type) to an optional mapping function—if such a callback is provided in the wrapper’s constructor: responseexceptionmapper? exceptionmapper
.
the exceptionmapper
function receives two arguments: the first is the dio response object of type response<t>
(where t
is the type of data passed into the wrapper, usually map<string, dynamic>
for json) and the second is the original exception which was caught.
in case you weren’t sure, you can specify the type of the type of the data you expect dio to return by passing in the expected type when you call our wrapper’s generic delegate methods:
// perform a get request with a json return type: map<string, dynamic>
final response = apphttpclient.get<map<string, dynamic>>('url');
the following are some of the response types dio supports:
client.get<map<string, dynamic>>() // json data
client.get<string>() // plain text data
client.get<responsebody>() // response stream
client.get<list<int>>() // raw binary data (as list of bytes)
you can implement the exceptionmapper
function however you like. if you don’t know what to do with the dio response, simply return null
to let apphttpclient
wrap the response error using the default error handling logic. if your exceptionmapper
function is able to recognize a certain kind of response, it is welcome to return an instance or subclass of appnetworkresponseexception
which better represents the error.
in the next section, we will construct an example exceptionmapper
which unwraps a certain kind of backend error it receives.
handling the errors
imagine you’ve defined the following service which calls your internet-of-things-enabled teapot and tells it to brew coffee
erroneously:
import 'package:dio/dio.dart';
class teaservice {
teaservice({required this.client});
final apphttpclient client;
future<map<string, dynamic>?> brewtea() async {
final response = await client.post<map<string, dynamic>>(
'/tea',
data: {
'brew': 'coffee',
},
);
return response.data;
}
}
because you’ve made the wrong request, the teapot should respond back with a 418 i’m a teapot error. perhaps it even replies with json data in its response body:
{
"message": "i can't brew 'coffee'"
}
let’s pretend, while we’re at it, that you want to catch these specific errors and wrap them in an error class, preserving the server’s error message so that you can show it to the user of your remote tea-brewing app.
this is all you have to do:
class teapotresponseexception extends appnetworkresponseexception {
teapotresponseexception({
required string message,
}) : super(exception: exception(message));
}
final client = apphttpclient(
client: dio(),
exceptionmapper: <t>(response<t> response) {
final data = response.data;
if (data != null && data is map<string, dynamic>) {
// we only map responses containing data with a status code of 418:
return teapotresponseexception(
message: data['message'] ?? 'i'm a teapot',
);
}
return null;
},
);
note: because dart generic types are reified, you can check the type of the response data inside the exceptionmapper
function.
to use your service and consume teapot errors, this is all you need to do:
final teaservice = teaservice(client: client);
try {
await teaservice.brewtea();
} on teapotresponseexception catch (teapot) {
print(teapot.exception.tostring());
} catch (e) {
print('some other error');
}
note that you can access the error’s data since you created a custom teapotresponseexception
class. on top of that, it integrates seamlessly with dart’s try/catch clauses. the try
/catch
clauses dart provides out of the box are incredibly useful for catching specific types of errors—exactly what our wrapper helps us with!
so that’s pretty much it—i like to think it’s worth the hassle of creating a custom http client wrapper. ![stuck_out_tongue_winking_eye](https://github.githubassets.com/images/icons/emoji/unicode/1f61c.png =20×20)
testing
a wrapper whose sole job is to wrap errors would be completely useless if there were mistakes in its code which caused it to throw errors that didn’t get wrapped. whew, that was a mouthful. we can prevent just such a catastrophe by keeping the wrapper code as simple as possible and testing all of its functionality.
to prevent such a catastrophe, i have tried to reduce the wrapper’s code as much as possible and have tested it to the best of my ability. because of the code’s simplicity, you can check the tests here to ensure that you are satisfied with its functionality.
Comments are closed.