All Projects β†’ CodingAleCR β†’ http_interceptor

CodingAleCR / http_interceptor

Licence: MIT license
A lightweight, simple plugin that allows you to intercept request and response objects and modify them if desired.

Programming Languages

dart
5743 projects

Projects that are alternatives of or similar to http interceptor

validated
Ultimate dart / flutter string validators πŸ’ƒπŸ’ƒ
Stars: ✭ 21 (-71.62%)
Mutual labels:  dart-library
flutter wasm
WebAssembly interpreter for Flutter apps.
Stars: ✭ 22 (-70.27%)
Mutual labels:  dart-library
requester
The package provides a very thin wrapper (no external dependencies) for http.Client allowing the use of layers (middleware).
Stars: ✭ 14 (-81.08%)
Mutual labels:  http-requests
Motion-Tab-Bar
A beautiful animated flutter widget package library. The tab bar will attempt to use your current theme out of the box, however you may want to theme it.
Stars: ✭ 237 (+220.27%)
Mutual labels:  dart-library
relay
Relay lets you write HTTP requests as easy to read, structured YAML and dispatch them easily using a CLI. Similar to tools like Postman
Stars: ✭ 22 (-70.27%)
Mutual labels:  http-requests
gen lang
gen_lang is a dart library for internationalization. Extracts messages to generate dart files required by Intl, inspired by Intl_translation and Flutter i18n
Stars: ✭ 94 (+27.03%)
Mutual labels:  dart-library
1c http
ΠŸΠΎΠ΄ΡΠΈΡΡ‚Π΅ΠΌΠ° 1Π‘ для Ρ€Π°Π±ΠΎΡ‚Ρ‹ с HTTP
Stars: ✭ 48 (-35.14%)
Mutual labels:  http-requests
universal-json-schema
πŸ“œ Universal JSON Schema Form - Currently Support for React - Material UI components for building Web forms from JSON Schema.
Stars: ✭ 102 (+37.84%)
Mutual labels:  interceptors
stash
Key-value store abstraction with plain and cache driven semantics and a pluggable backend architecture.
Stars: ✭ 71 (-4.05%)
Mutual labels:  dart-library
SecurityHeaders GovUK
A scan of all .gov.uk sites for the most common security headers or lack of
Stars: ✭ 14 (-81.08%)
Mutual labels:  http-requests
internet connection checker
A pure Dart library that checks for internet by opening a socket to a list of specified addresses, each with individual port and timeout. Defaults are provided for convenience.
Stars: ✭ 52 (-29.73%)
Mutual labels:  dart-library
FireMock
Mock and stub HTTP requests. Test your apps with fake data and files responses.
Stars: ✭ 25 (-66.22%)
Mutual labels:  http-requests
Flogs
An Advanced Logging Framework develop in flutter that provides quick & simple logging solution.
Stars: ✭ 158 (+113.51%)
Mutual labels:  dart-library
wasm.dart
WebAssembly virtual machine for Dart [work in progress]
Stars: ✭ 43 (-41.89%)
Mutual labels:  dart-library
very good analysis
Lint rules for Dart and Flutter used internally at Very Good Ventures πŸ¦„
Stars: ✭ 194 (+162.16%)
Mutual labels:  dart-library
open route service
An encapsulation made around openrouteservice API for Dart and Flutter projects. Made for easy generation of Routes and Directions on Maps, Isochrones, Time-Distance Matrix, Pelias Geocoding, POIs, Elevation and routing Optimizations using their amazing API.
Stars: ✭ 20 (-72.97%)
Mutual labels:  dart-library
material-color-utilities
Color libraries for Material You
Stars: ✭ 605 (+717.57%)
Mutual labels:  dart-library
node-fetch-har
Generate HAR entries for requests made with node-fetch
Stars: ✭ 23 (-68.92%)
Mutual labels:  http-requests
traindown-dart
Dart (and Flutter) library for the Traindown Markup Language. This is the reference implementation for now. It is first to receive features and fixes.
Stars: ✭ 16 (-78.38%)
Mutual labels:  dart-library
swish
C++ HTTP requests for humans
Stars: ✭ 52 (-29.73%)
Mutual labels:  http-requests

http_interceptor

Pub style: effective dart License: MIT codecov Star on GitHub

All Contributors

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 on ResponseData 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.
  • ⏲ Timeout configuration with duration and timeout functions.

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<BaseRequest> interceptRequest({required BaseRequest request}) async {
    print(request.toString());
    return request;
  }

  @override
  Future<BaseResponse> interceptResponse({required BaseResponse response}) async {
      print(response.toString());
      return response;
  }

}
  • Changing headers with interceptor:
class WeatherApiInterceptor implements InterceptorContract {
  @override
  Future<BaseRequest> interceptRequest({required BaseRequest request}) async {
    try {
      request.url.queryParameters['appid'] = OPEN_WEATHER_API_KEY;
      request.url.queryParameters['units'] = 'metric';
      request.headers[HttpHeaders.contentTypeHeader] = "application/json";
    } catch (e) {
      print(e);
    }
    return request;
  }

  @override
  Future<BaseResponse> interceptResponse({required BaseResponse response}) async => response;
}
  • You can also react to and modify specific types of requests and responses, such as StreamedRequest,StreamedResponse, or MultipartRequest :
class MultipartRequestInterceptor implements InterceptorContract {
  @override
  Future<BaseRequest> interceptRequest({required BaseRequest request}) async {
    if(request is MultipartRequest){
      request.fields['app_version'] = await PackageInfo.fromPlatform().version;
    }
    return request;
  }

  @override
  Future<BaseResponse> interceptResponse({required BaseResponse response}) async {
    if(response is StreamedResponse){
      response.stream.asBroadcastStream().listen((data){
        print(data);
      });
    }
    return response;
  }
}

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(BaseResponse 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 [email protected].

Contributors

Thanks to all the wonderful people contributing to improve this package. Check the Emoji Key for reference on what means what!


Alejandro Ulate Fallas

πŸ’» πŸ“– ⚠️ πŸ€” 🚧

Konstantin Serov

πŸ€”

Virus1908

πŸ€” πŸ’» ⚠️

Wes Ehrlichman

πŸ€” πŸ’» ⚠️

Jan LΓΌbeck

πŸ€” πŸ’» ⚠️

Lucas Alves

πŸ€” πŸ’» ⚠️

IstvΓ‘n Juhos

πŸ€” πŸ’» ⚠️

Scott Hyndman

πŸ€”

Islam Akhrarov

πŸ€” ⚠️ πŸ’»

Meysam

πŸ“–

Martijn

⚠️ πŸ’»

MaciejZuk

πŸ›

Lukas Kurz

⚠️ πŸ€” πŸ’»

Glenn Ruysschaert

πŸ’» ⚠️

Erick

πŸ’» ⚠️

javiermrz

πŸ’»
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].