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.
Upgrading from 2.x? See the 3.0.0 migration guide.
Include the package with the latest version available in your pubspec.yaml.
http_interceptor:<latest>- 🚦 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).
- 👓
GETrequests with separated parameters. - ⚡️ Standard
Response.bodyBytesfor encoding or decoding as needed. - 📦 Convenience helpers to decode JSON responses and map them into your own models.
- 🙌🏼 Array parameters on requests.
- 🖋 Supports self-signed certificates (except on Flutter Web).
- 🍦 Compatible with vanilla Dart projects or Flutter projects.
- 🎉 Null-safety.
- ⏲ Timeout configuration with duration and timeout functions.
- ⏳ Configure the delay for each retry attempt.
import'package:http_interceptor/http_interceptor.dart';Implement HttpInterceptor to add logging, headers, error handling, and more. The interface has four methods:
- interceptRequest – runs before the request is sent. Return the (possibly modified) request.
- interceptResponse – runs after the response is received. Return the (possibly modified) response.
- shouldInterceptRequest / shouldInterceptResponse – return
falseto skip interception for that request/response (defaulttrue).
All methods support FutureOr so you can use sync or async. Modify the request/response in place and return it, or return a new instance.
- Logging interceptor:
classLoggerInterceptorimplementsHttpInterceptor {
@overrideBaseRequestinterceptRequest({requiredBaseRequest request}) {
print('----- Request -----');
print(request.toString());
return request;
}
@overrideBaseResponseinterceptResponse({requiredBaseResponse response}) {
print('----- Response -----');
print('Code: ${response.statusCode}');
if (response isResponse) {
print(response.body);
}
return response;
}
}- Adding headers / query params (in-place mutation):
classWeatherApiInterceptorimplementsHttpInterceptor {
@overrideBaseRequestinterceptRequest({requiredBaseRequest request}) {
final url = request.url.replace(
queryParameters: {
...request.url.queryParameters,
'appid': apiKey,
'units':'metric',
},
);
returnRequest(request.method, url)
..headers.addAll(request.headers)
..headers[HttpHeaders.contentTypeHeader] ='application/json';
}
@overrideBaseResponseinterceptResponse({requiredBaseResponse response}) => response;
}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. 😉
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.
classWeatherRepository {
final client =InterceptedClient.build(
interceptors: [WeatherApiInterceptor()],
);
Future<Map<String, dynamic>> fetchCityWeather(int id) async {
final response =await client.get(
'$baseUrl/weather'.toUri(),
params: {'id':'$id'},
);
if (response.statusCode ==200) {
// Built-in Response JSON helpers:return response.jsonMap;
}
throwException('Error while fetching.\\n${response.body}');
}
}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.
classWeatherRepository {
Future<Map<String, dynamic>> fetchCityWeather(int id) async {
final http =InterceptedHttp.build(interceptors: [WeatherApiInterceptor()]);
final response =await http.get(
'$baseUrl/weather'.toUri(),
params: {'id':'$id'},
);
if (response.statusCode ==200) {
// Built-in Response JSON helpers:return response.jsonMap;
}
returnFuture.error(
'Error while fetching.',
StackTrace.fromString(response.body),
);
}
}The ResponseBodyDecoding extension adds a few lightweight helpers on Response for common JSON use cases:
final response =await client.get(
'$baseUrl/weather'.toUri(),
params: {'id':'$id'},
);
// Dynamically-typed JSON value (Map/List/primitive or null on empty body).finalObject? json = response.jsonBody;
// JSON object as a map (throws if body is empty or not a JSON object).finalMap<String, dynamic> data = response.jsonMap;
// JSON array as a list (throws if body is empty or not a JSON array).finalList<dynamic> items = response.jsonList;The ResponseBodyDecoding extension provides helpers to turn JSON responses into strongly-typed models with minimal boilerplate.
classWeather {
finalString description;
finaldouble temperature;
constWeather({
requiredthis.description,
requiredthis.temperature,
});
factoryWeather.fromJson(Map<String, dynamic> json) {
returnWeather(
description: (json['weather'] asList).first['description'] asString,
temperature: (json['main']['temp'] asnum).toDouble(),
);
}
}
Future<Weather> fetchCityWeather(int id) async {
final client =InterceptedClient.build(
interceptors: [WeatherApiInterceptor()],
);
final response =await client.get(
'$baseUrl/weather'.toUri(),
params: {'id':'$id'},
);
if (response.statusCode ==200) {
// Use the built-in JSON mapper:return response.decodeJson(
(json) =>Weather.fromJson(json asMap<String, dynamic>),
);
}
throwException('Error while fetching.\n${response.body}');
}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.
classExpiredTokenRetryPolicyextendsRetryPolicy {
@overrideintget maxRetryAttempts =>2;
@overrideboolshouldAttemptRetryOnException(Exception reason, BaseRequest request) {
// Log the exception for debuggingprint('Request failed: ${reason.toString()}');
print('Request URL: ${request.url}');
// Retry on network exceptions, but not on client errorsreturn reason isSocketException|| reason isTimeoutException;
}
@overrideFuture<bool> shouldAttemptRetryOnResponse(BaseResponse response) async {
if (response.statusCode ==401) {
// Perform your token refresh here.print('Token expired, refreshing...');
returntrue;
}
returnfalse;
}
}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.
The RetryPolicy abstract class provides the following methods that you can override:
shouldAttemptRetryOnException(Exception reason, BaseRequest request): Called when an exception occurs during the request. Returntrueto retry,falseto fail immediately.shouldAttemptRetryOnResponse(BaseResponse response): Called after receiving a response. Returntrueto retry,falseto accept the response.maxRetryAttempts: The maximum number of retry attempts (default: 1).delayRetryAttemptOnException({required int retryAttempt}): Delay before retrying after an exception (default: no delay).delayRetryAttemptOnResponse({required int retryAttempt}): Delay before retrying after a response (default: no delay).
To use a retry policy, pass it to the InterceptedClient or InterceptedHttp:
final client =InterceptedClient.build(
interceptors: [WeatherApiInterceptor()],
retryPolicy:ExpiredTokenRetryPolicy(),
);Sometimes it is helpful to have a cool-down phase between multiple requests. This delay could for example also differ between the first and the second retry attempt as shown in the following example.
classExpiredTokenRetryPolicyextendsRetryPolicy {
@overrideintget maxRetryAttempts =>3;
@overrideboolshouldAttemptRetryOnException(Exception reason, BaseRequest request) {
// Only retry on network-related exceptionsreturn reason isSocketException|| reason isTimeoutException;
}
@overrideFuture<bool> shouldAttemptRetryOnResponse(BaseResponse response) async {
// Retry on server errors (5xx) and authentication errors (401)return response.statusCode >=500|| response.statusCode ==401;
}
@overrideDurationdelayRetryAttemptOnException({requiredint retryAttempt}) {
// Exponential backoff for exceptionsreturnDuration(milliseconds: (250* math.pow(2.0, retryAttempt -1)).round());
}
@overrideDurationdelayRetryAttemptOnResponse({requiredint retryAttempt}) {
// Exponential backoff for response-based retriesreturnDuration(milliseconds: (250* math.pow(2.0, retryAttempt -1)).round());
}
}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:
Client client =InterceptedClient.build(
interceptors: [
WeatherApiInterceptor(),
],
client:IOClient(
HttpClient()
..badCertificateCallback = badCertificateCallback
..findProxy = findProxy,
);
);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).
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.
Open an issue and tell me, I will be happy to help you out as soon as I can.
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.
Thanks to all the wonderful people contributing to improve this package. Check the Emoji Key for reference on what means what!