A middleware library for Dart's http library.

Overview

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.

Comments
  • interceptResponse not modifying the resulting response

    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.

    opened by cdvv7788 2
  • Question: BuildContext inside Middleware

    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?

    opened by MallorcaSoftware 1
  • pubspec file update.

    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.

    opened by CodingAleCR 0
  • http ^0.13.0 Updated dependencies

    http ^0.13.0 Updated dependencies

    Is it possible to update http version to http ^0.13.0.

    Reason: Problems with usage with other libraries:

    Error: The current Dart SDK version is 2.18.0-44.1.beta.

    Because no versions of cached_network_image match >3.2.1 <4.0.0 and cached_network_image 3.2.1 depends on flutter_cache_manager ^3.3.0, cached_network_image ^3.2.1 requires flutter_cache_manager ^3.3.0. And because no versions of flutter_cache_manager match >3.3.0 <4.0.0, cached_network_image ^3.2.1 requires flutter_cache_manager 3.3.0. And because flutter_cache_manager 3.3.0 depends on http ^0.13.0 and http_middleware >=1.0.0 depends on http ^0.11.3+16, cached_network_image ^3.2.1 is incompatible with http_middleware >=1.0.0. And because http_logger >=1.0.0 depends on http_middleware ^1.0.0 and http_logger <1.0.0 requires SDK version >=1.8.0 <2.0.0, cached_network_image ^3.2.1 is incompatible with http_logger. So, because trail_events depends on both cached_network_image ^3.2.1 and http_logger any, version solving failed. pub get failed (1; So, because trail_events depends on both cached_network_image ^3.2.1 and http_logger any, version solving failed.)

    opened by fmatuszewski 0
  • Newer version of http and null safety support

    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

    opened by mithunadhikari40 0
  • PUT request does not copy headers from middleware

    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

    opened by mrdavidrees 1
  • The version 1.0.0 on dart pub still depends on old version of http 0.11.3+16

    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.
    
    opened by shunia 5
Owner
TED Consulting
TED Consulting
App HTTP Client is a wrapper around the HTTP library Dio to make network requests and error handling simpler, more predictable, and less verbose.

App HTTP Client App HTTP Client is a wrapper around the HTTP library Dio to make network requests and error handling simpler, more predictable, and le

Joanna May 44 Nov 1, 2022
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

Betterment 14 Nov 28, 2022
An easy-to-use flutter http network requests handler with more functionality than http but more simpler than dio.

network_requests An easy-to-use flutter http network requests handler with more functionality than http but more simpler than dio. Platform Supported

Coder_Manuel 3 Dec 15, 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

null 46 Dec 19, 2021
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

Jibran Ahmed SiddiQui 9 Oct 29, 2022
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

Abd al-Rahman al-Ktefane 5 Dec 25, 2022
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

Flutter中国开源项目 11.2k Jan 3, 2023
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

Hau Tran 8 Dec 14, 2022
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

Antonello Galipò 5 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

Liu YuanYuan 4 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

Dart 888 Dec 26, 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

Behruz Hurramov 0 Dec 27, 2021
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

Flutter Samples 80 Nov 10, 2022
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

Mohammad Rahmani 110 Dec 23, 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

T. Milian 3 May 20, 2022
Generates a new Flutter app with http client, theme, routing and localization features.

Starter Template Generates a new Flutter app with http client, theme, routing and localization features. Brick Uses: dio as http client pretty_dio_log

Cem Avcı 12 Nov 3, 2022
Flutter Rest API using Http and Provider State.

Getting Started This project is a starting point for a Flutter application. A few resources to get you started if this is your first Flutter project:

Joshua Jeremia 2 Aug 31, 2022
This example handles HTTP GET requests by responding with 'Hello, World!'

Hello world example This example handles HTTP GET requests by responding with 'Hello, World!'. // lib/functions.dart import 'package:functions_framewo

TryIt (김동현) 0 May 25, 2022
A ready-made structure that holds HTTP requests.

A ready-made structure that holds HTTP requests. Usage import 'package:flutter/material.dart'; import 'package:uigitdev_request_holder/src/http_reques

Uigitdev 2 Oct 21, 2022