http_interceptor 0.0.3

http_interceptor #

A middleware library that lets you modify requests and responses if desired. Based of on (http_middleware)[https://github.com/TEDConsulting/http_middleware]

Getting Started #

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.

Installing #

Include the package with the latest version available in your pubspec.yaml.

    http_interceptor: any

Importing #

import 'package:http_interceptor/http_interceptor.dart';

Using http_interceptor

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 LogginInterceptor implements InterceptorContract {
  @override
  Future<RequestData> interceptRequest({RequestData data}) async {
    print(data);
    return data;
  }

  @override
  Future<ResponseData> interceptResponse({ResponseData data}) async {
      print(data);
      return data;
  }

}
  • Changing headers with interceptor:
class WeatherApiInterceptor implements InterceptorContract {
  @override
  Future<RequestData> interceptRequest({RequestData data}) async {
    try {
      data.url = "${data.url}&appid=$OPEN_WEATHER_API_KEY";
      data.url = "${data.url}&units=metric";
      data.headers["Content-Type"] = "application/json";
    } catch (e) {
      print(e);
    }
    return data;
  }

  @override
  Future<ResponseData> interceptResponse({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 HttpWithInterceptor to do separate connections for different requests or using a HttpClientWithInterceptor 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 HttpClientWithInterceptor class.

class WeatherRepository {
  Client client = HttpClientWithInterceptor.build(interceptors: [
      WeatherApiInterceptor(),
  ]);

  Future<Map<String, dynamic>> fetchCityWeather(int id) async {
    var parsedWeather;
    try {
      final response = await client.get("$baseUrl/weather?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 HttpWithInterceptor class.

class WeatherRepository {


  Future<Map<String, dynamic>> fetchCityWeather(int id) async {
    HttpWithInterceptor http = HttpWithInterceptor.build(
              interceptors: [WeatherApiInterceptor()]);

    var parsedWeather;
    try {
      var response = await http.get("$baseUrl/weather?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;
  }

}

Need help? #

Open an issue and tell me, I will be happy to help you out as soon as I can.

0.0.3 #

  • Added: Documentation for the example.

0.0.2 #

  • Fixed: All the warnings regarding plugin publication.

0.0.1 #

  • Added: Initial plugin implementation.
  • Added: Example of usage for the plugin.
  • Added: README.md and LICENSE files.

example/README.md

OpenWeatherApp #

http_interceptor example

Demonstrates how to use the http_interceptor plugin.

Getting Started #

This app implements the usage of the http_interceptor plugin. It uses the OpenWeatherAPI and intercepts the requests done to add the App Id Key and the unit system desired for the response. Notice that this example is for show purposes only, it is not intended as a full testable implementation.

Running the example #

In order to run this example locally you will need to replace the API Key in the credentials.dart. You can get your own at https://openweathermap.org/

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  http_interceptor: ^0.0.3

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:http_interceptor/http_interceptor.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
77
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
90
Overall:
Weighted score of the above. [more]
86
Learn more about scoring.

We analyzed this package on Jul 17, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.4.0
  • pana: 0.12.19
  • Flutter: 1.7.8+hotfix.3

Platforms

Detected platforms: Flutter

References Flutter, and has no conflicting libraries.

Health suggestions

Format lib/models/models.dart.

Run flutter format to format lib/models/models.dart.

Maintenance suggestions

Package is pre-v0.1 release. (-10 points)

While nothing is inherently wrong with versions of 0.0.*, it might mean that the author is still experimenting with the general direction of the API.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.1.0 <3.0.0
flutter 0.0.0
http ^0.12.0 0.12.0+2
Transitive dependencies
async 2.3.0
charcode 1.1.2
collection 1.14.11
http_parser 3.1.3
meta 1.1.6 1.1.7
path 1.6.2
pedantic 1.8.0+1
sky_engine 0.0.99
source_span 1.5.5
string_scanner 1.0.4
term_glyph 1.1.0
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
flutter_test

Admin