A middleware library for Dart's http library.

Last update: Oct 23, 2021

http_middleware

A middleware library for Dart http library.

Getting Started

http_middleware is a module that lets you build middleware for Dart's http package.

Installing

Include this library in your package.

http_middleware: any

Importing

import 'package:http_middleware/http_middleware.dart';

Using http_middleware

Create an object of HttpWithMiddleware by using the build factory constructor.

The build constructor takes in a list of middlewares that are built for http_middleware. One very nice middleware you can use is the http_logger package. We will use that here for demonstration.

(You can also build your own middleware for http_middleware. Check out Build your own middleware)
HttpWithMiddleware http = HttpWithMiddleware.build(middlewares: [
    HttpLogger(logLevel: LogLevel.BODY),
]);

That is it! Now go ahead and use this http object as you would normally do.

//Simple POST request
var response = await http.post('https://jsonplaceholder.typicode.com/posts/',
    body: {"testing", "1234"});

//Simple GET request
var response = await http.get('https://jsonplaceholder.typicode.com/posts/');

Request Timout

With http_middleware you can also specify the timeout of requests. So if you want a request to be timeout in 30 seconds:

HttpWithMiddleware http = HttpWithMiddleware.build(
  requestTimeout: Duration(seconds: 30),
  middlewares: [
    HttpLogger(logLevel: LogLevel.BODY),
]);

You need to catch the exception thrown to know if connection timed out.

try {
 var response = await http.get('https://jsonplaceholder.typicode.com/posts/');
} catch(e) {
 if (e is TimeoutException) {
   //Timed out
 }
}

HttpWithMiddleware supports all the functions that http provides.

http.get(...);
http.post(...);
http.put(...);
http.delete(...);
http.head(...);
http.patch(...);
http.read(...);
http.readBytes(...);

Using a Client

If you want to use a http.Client in order to keep the connection alive with the server, use HttpClientWithMiddleware.

HttpClientWithMiddleware httpClient = HttpClientWithMiddleware.build(middlewares: [
    HttpLogger(logLevel: LogLevel.BODY),
]);

var response = await httpClient.post('https://jsonplaceholder.typicode.com/posts/',
    body: {"testing", "1234"});

var response = await httpClient.get('https://jsonplaceholder.typicode.com/posts/');

//Don't forget to close the client once done.
httpClient.close();

Building your own middleware

Building your own middleware with http_middleware is very easy, whether you want to create a package for http_middleware or you want to build a middleware solely for your own project.

Once you have the necessary imports, all you have to do is extend the MiddlewareContract class which will give you access to 2 functions.

interceptRequest(RequestData) is the method called before any request is made. interceptResponse(ResponseData) is the method called after the response from request is received.

You can then @override all the required functions you need to add middleware to.

Example (A simple logger that logs data in all requests):

class Logger extends MiddlewareContract {
  @override
  interceptRequest({RequestData data}) {
    print("Method: ${data.method}");
    print("Url: ${data.url}");
    print("Body: ${data.body}");
  }

  @override
  interceptResponse({ResponseData data}) {
    print("Status Code: ${data.statusCode}");
    print("Method: ${data.method}");
    print("Url: ${data.url}");
    print("Body: ${data.body}");
    print("Headers: ${data.headers}");
  }
}

You can also modify the RequestData before the request is made and every ResponseData after every response is received. For Example, if you want to wrap your data in a particular structure before sending, or you want every request header to have Content-Type set to application/json.

class Logger extends MiddlewareContract {
  @override
  interceptRequest({RequestData data}) {
    //Adding content type to every request
    data.headers["Content-Type"] = "application/json";
    
    data.body = jsonEncode({
      uniqueId: "some unique id",
      data: data.body,
    });
  }

  @override
  interceptResponse({ResponseData data}) {
    //Unwrapping response from a structure
    data.body = jsonDecode(data.body)["data"];
  }
}

Packages built on http_middleware

If your package uses http_middleware, open an issue and tell me, i will be happy to add it to the list.

GitHub

https://github.com/TEDConsulting/http_middleware
Comments
  • 1. interceptResponse not modifying the resulting response

    I am trying a middleware with: image

    The response is always the original. It is being called at https://github.com/gurleensethi/http_middleware/blob/master/lib/http_with_middleware.dart#L126 but it seems that the response object is not being modified. I don't have enough experience in dart to know if that is a reference and if the changes should modify the object outside of the function.

    Reviewed by cdvv7788 at 2018-07-24 02:59
  • 2. Question: BuildContext inside Middleware

    I want to use the http_middleware to show a dialog if some error occurs.

    grafik

    Is there any way to get the current BuildContext (i need it to show a dialog) in the interceptor? Any other ideas?

    Reviewed by MallorcaSoftware at 2018-11-13 10:08
  • 3. pubspec file update.

    The issue is that the pubspec.lock holds the actual value that the plugin is using, so in order for the issue #8 to be fixed you needed just to do a flutter packages get and then update master branch with that generated pubspec.lock. I also updated the file lib/http_client_with_middleware.dart so it now uses the IOClient from the http plugin, I think it was moved in the newer versions.

    Reviewed by CodingAleCR at 2019-04-08 18:43
  • 4. Newer version of http and null safety support

    Thank you very much for this package. It looks like you are not able to maintain this package since I see the last commit made 3 years ago, I have created a new package using this package and published it under the pub. Anyone who needs a newer version of this can use this: https://pub.dev/packages/pretty_http_logger

    Reviewed by mithunadhikari40 at 2021-12-25 18:11
  • 5. PUT request does not copy headers from middleware

    The bug is on line 67/68 of http_with_middleware.dart

    Can you please update return _withClient((client) => client.post(data.url, headers: headers, body: data.body, encoding: data.encoding));

    to

    return _withClient((client) => client.post(data.url, headers: data.headers, body: data.body, encoding: data.encoding));

    i'm not sure if line 48 also has this issue

    Reviewed by mrdavidrees at 2019-04-30 02:34
  • 6. The version 1.0.0 on dart pub still depends on old version of http 0.11.3+16

    Please update the pub package to the newest version, for now, If depends on http: ^0.12.0 and http_middleware: ^1.0.0, flutter packages get won't pass:

    Because pqdd depends on http_middleware ^1.0.0 which depends on http ^0.11.3+16, http ^0.11.3+16 is required.
    So, because pqdd depends on http ^0.12.0+1, version solving failed.
    
    Reviewed by shunia at 2019-02-28 06:26

Related

Charlatan - A library for configuring and providing fake http responses to your dio HTTP client.

charlatan This package provides the ability to configure and return fake HTTP responses from your Dio HTTP Client. This makes it easy to test the beha

Jun 21, 2022
Sample code for "A Game of Darts" tutorial

These are small Dart samples used by the online Dart tutorials. Each directory in this repo represents a tutorial. The homepage field in each pubspec

May 2, 2022
A powerful Http client for Dart, which supports Interceptors, FormData, Request Cancellation, File Downloading, Timeout etc.

dio_http A powerful Http client for Dart, which supports Interceptors, Global configuration, FormData, Request Cancellation, File downloading, Timeout

Dec 19, 2021
Weather app using Bloc architecture pattern & generic HTTP client with interface implementation and much more for more detail read Readme
Weather app using Bloc architecture pattern & generic HTTP client with interface implementation and much more for more detail read Readme

weather Weather application for current weather, hourly forecast for 48 hours, Daily forecast for 7 days and national weather alerts. How to Run Insta

Jan 28, 2022
Powerful, helpfull, extensible and highly customizable API's that wrap http client to make communication easier with Axelor server with boilerplate code free.
Powerful, helpfull, extensible and highly customizable API's that wrap http client to make communication easier with Axelor server with boilerplate code free.

flutter_axelor_sdk Powerful, helpful, extensible and highly customizable API's that wrap http client to make communication easier with Axelor server w

Nov 12, 2021
A powerful Http client for Dart, which supports Interceptors, FormData, Request Cancellation, File Downloading, Timeout etc.
A powerful Http client for Dart, which supports Interceptors, FormData, Request Cancellation, File Downloading, Timeout etc.

Language: English | 中文简体 dio A powerful Http client for Dart, which supports Interceptors, Global configuration, FormData, Request Cancellation, File

Jun 22, 2022
Http request inspector for Flutter application
Http request inspector for  Flutter application

Alice Alice is an HTTP Inspector tool for Flutter which helps debugging http requests. It catches and stores http requests and responses, which can be

Dec 4, 2021
A Dart package to handle HTTP services

http_services A package to support the creation of Http services in a Dart application. Features convenient methods to perform HTTP requests disposing

Jul 27, 2021
An HTTP file downloader packed with many features -> resumable downloads, multiple connections, buffering, auto-retry, etc.

An HTTP file downloader packed with many features -> resumable downloads, multiple connections, buffering, auto-retry, etc. Features Resumable downloa

Feb 2, 2022
A composable API for making HTTP requests in Dart.

A composable, Future-based library for making HTTP requests. This package contains a set of high-level functions and classes that make it easy to cons

Jun 28, 2022
A simple HTTP server that can serve up any directory, built with Dart

A simple HTTP server that can serve up any directory, built with Dart. Inspired by python -m SimpleHTTPServer. Install Use the dart pub global command

Dec 27, 2021
A shopper Flutter app that use BloC pattern and CRUD operations with different ways(memory/sqlite/http)
A shopper Flutter app that use BloC pattern and CRUD operations with different ways(memory/sqlite/http)

The project is maintained by a non-profit organisation, along with an amazing collections of Flutter samples. We're trying to make continuous commits

Jun 16, 2022
Flutter Github Following Application, Using Flutter Provider and Flutter HTTP to get data from Github API.
Flutter Github Following Application, Using Flutter Provider and Flutter HTTP to get data from Github API.

Flutter Github Following Application Watch it on Youtube Previous Designs Checkout my Youtube channel Installation Please remember, after cloning this

Jun 10, 2022
A lightweight and customizable http client that allows you to create offline-first dart app easily.

Enjoyable & customizable offline-first REST API client Unruffled is lightweight and customizable http client that allows you to create offline-first e

May 20, 2022
Flutter Control is complex library to maintain App and State management. Library merges multiple functionality under one hood. This approach helps to tidily bound separated logic into complex solution.
Flutter Control is complex library to maintain App and State management. Library merges multiple functionality under one hood. This approach helps to tidily bound separated logic into complex solution.

Flutter Control is complex library to maintain App and State management. Library merges multiple functionality under one hood. This approach helps to

Feb 23, 2022
[Flutter Library] Flamingo is a firebase firestore model framework library. 🐤
[Flutter Library] Flamingo is a firebase firestore model framework library. 🐤

Flamingo Flamingo is a firebase firestore model framework library. https://pub.dev/packages/flamingo 日本語ドキュメント Example code See the example directory

Jun 3, 2022
Flutter-Animated-Library-of-Books - Flutter App - Animated Book Library

bookshelf A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if thi

Jan 2, 2022
Flutter book library - Book Library Application with Flutter and Google Book API

Book Library Application Flutter iOS, Android and Web with Google Book API Demo

Jan 25, 2022
Dart client library to interact with Supabase Storage

storage-dart Dart client library to interact with Supabase Storage. Contributing Fork the repo on GitHub Clone the project to your own machine Commit

Jun 14, 2022