http_interceptor
This is a plugin that lets you intercept the different requests and responses from Dart's http package. You can use to add headers, modify query params, or print a log of the response.
Quick Reference
Already using http_interceptor
? Check out the 1.0.0 migration guide for quick reference on the changes made and how to migrate your code.
Installation
Include the package with the latest version available in your pubspec.yaml
.
http_interceptor: ^1.0.1
Features
- π¦ Intercept & change unstreamed requests and responses.
- β¨ Retrying requests when an error occurs or when the response does not match the desired (useful for handling custom error responses).
- π
GET
requests with separated parameters. - β‘οΈ Standard
bodyBytes
onResponseData
to encode or decode in the desired format. - ππΌ Array parameters on requests.
- π Supports self-signed certificates (except on Flutter Web).
- π¦ Compatible with vanilla Dart projects or Flutter projects.
- π Null-safety.
Usage
import 'package:http_interceptor/http_interceptor.dart';
Building your own interceptor
In order to implement http_interceptor
you need to implement the InterceptorContract
and create your own interceptor. This abstract class has two methods: interceptRequest
, which triggers before the http request is called; and interceptResponse
, which triggers after the request is called, it has a response attached to it which the corresponding to said request. You could use this to do logging, adding headers, error handling, or many other cool stuff. It is important to note that after you proccess the request/response objects you need to return them so that http
can continue the execute.
- Logging with interceptor:
class LoggingInterceptor implements InterceptorContract {
@override
Future<RequestData> interceptRequest({required RequestData data}) async {
print(data.toString());
return data;
}
@override
Future<ResponseData> interceptResponse({required ResponseData data}) async {
print(data.toString());
return data;
}
}
- Changing headers with interceptor:
class WeatherApiInterceptor implements InterceptorContract {
@override
Future<RequestData> interceptRequest({required RequestData data}) async {
try {
data.params['appid'] = OPEN_WEATHER_API_KEY;
data.params['units'] = 'metric';
data.headers["Content-Type"] = "application/json";
} catch (e) {
print(e);
}
return data;
}
@override
Future<ResponseData> interceptResponse({required ResponseData data}) async => data;
}
Using your interceptor
Now that you actually have your interceptor implemented, now you need to use it. There are two general ways in which you can use them: by using the InterceptedHttp
to do separate connections for different requests or using a InterceptedClient
for keeping a connection alive while making the different http
calls. The ideal place to use them is in the service/provider class or the repository class (if you are not using services or providers); if you don't know about the repository pattern you can just google it and you'll know what I'm talking about. π
Using interceptors with Client
Normally, this approach is taken because of its ability to be tested and mocked.
Here is an example with a repository using the InterceptedClient
class.
class WeatherRepository {
Client client = InterceptedClient.build(interceptors: [
WeatherApiInterceptor(),
]);
Future<Map<String, dynamic>> fetchCityWeather(int id) async {
var parsedWeather;
try {
final response =
await client.get("$baseUrl/weather".toUri(), params: {'id': "$id"});
if (response.statusCode == 200) {
parsedWeather = json.decode(response.body);
} else {
throw Exception("Error while fetching. \n ${response.body}");
}
} catch (e) {
print(e);
}
return parsedWeather;
}
}
Using interceptors without Client
This is mostly the straight forward approach for a one-and-only call that you might need intercepted.
Here is an example with a repository using the InterceptedHttp
class.
class WeatherRepository {
Future<Map<String, dynamic>> fetchCityWeather(int id) async {
var parsedWeather;
try {
final http = InterceptedHttp.build(interceptors: [
WeatherApiInterceptor(),
]);
final response =
await http.get("$baseUrl/weather".toUri(), params: {'id': "$id"});
if (response.statusCode == 200) {
parsedWeather = json.decode(response.body);
} else {
return Future.error(
"Error while fetching.",
StackTrace.fromString("${response.body}"),
);
}
} on SocketException {
return Future.error('No Internet connection π');
} on FormatException {
return Future.error('Bad response format π');
} on Exception {
return Future.error('Unexpected error π’');
}
return parsedWeather;
}
}
Retrying requests
Sometimes you need to retry a request due to different circumstances, an expired token is a really good example. Here's how you could potentially implement an expired token retry policy with http_interceptor
.
class ExpiredTokenRetryPolicy extends RetryPolicy {
@override
Future<bool> shouldAttemptRetryOnResponse(ResponseData response) async {
if (response.statusCode == 401) {
// Perform your token refresh here.
return true;
}
return false;
}
}
You can also set the maximum amount of retry attempts with maxRetryAttempts
property or override the shouldAttemptRetryOnException
if you want to retry the request after it failed with an exception.
Using self signed certificates
You can achieve support for self-signed certificates by providing InterceptedHttp
or InterceptedClient
with the client
parameter when using the build
method on either of those, it should look something like this:
InterceptedClient
Client client = InterceptedClient.build(
interceptors: [
WeatherApiInterceptor(),
],
client: IOClient(
HttpClient()
..badCertificateCallback = badCertificateCallback
..findProxy = findProxy,
);
);
InterceptedHttp
final http = InterceptedHttp.build(
interceptors: [
WeatherApiInterceptor(),
],
client: IOClient(
HttpClient()
..badCertificateCallback = badCertificateCallback
..findProxy = findProxy,
);
);
Note: It is important to know that since both HttpClient and IOClient are part of dart:io
package, this will not be a feature that you can perform on Flutter Web (due to BrowserClient
and browser limitations).
Roadmap
Check out our roadmap here.
We migrated our roadmap to better suit the needs for development since we use ClickUp as our task management tool.
Troubleshooting
Open an issue and tell me, I will be happy to help you out as soon as I can.
Contributions
Contributions are always welcomed and encouraged, we will always give you credit for your work on this section. If you are interested in maintaining the project on a regular basis drop me a line at me@codingale.dev.
Contributors
Thanks to all the wonderful people contributing to improve this package. Check the Emoji Key for reference on what means what!
Libraries
- extensions/extensions
- extensions/string.extensions
- extensions/uri.extensions
- http/http
- http/http_methods
- http/intercepted_client
- http/intercepted_http
- http/interceptor_contract
- http_interceptor
- models/http_interceptor_exception
- models/models
- models/request_data
- models/response_data
- models/retry_policy
- utils/query_parameters.util
- utils/utils