A Dart package to handle HTTP services

Overview

http_services

A package to support the creation of Http services in a Dart application.

Features

  • convenient methods to perform HTTP requests
  • disposing a service will cleanup any pending requests, in order to avoid unwanted resources waste!
  • convenient models to have a standard for request and response objects

RequestBase

Every request should extend RequestBase and implement its overrides:

  • endpoint: Specify the path of the request
  • toJson: This method is used for the request's serialization
  • toData: This is an optional override in case you need to post a non JSON body. It returns an object of type T.

By default toData returns null

ResponseBase

Every response should extend ResponseBase

Exceptions

All the exceptions of this package extend HttpServiceException

ApiException:

This is thrown when something is wrong with the request (e.g. missing internet, resource not found, etc).

  • networkError signals if there was an outage in connection
  • httpCode is the received HTTP status code
  • httpMessage is the received HTTP status message

UnexpectedStatusCodeException:

This is thrown when expected HTTP code doesn't match the received one.

  • expected is the expected status code
  • actual is the received status code

ResponseMappingException:

This is thrown when an error occurs while mapping the response.

RequestCanceledException:

This is thrown when a request is canceled.

HttpServiceBase

Every service should extend this.

To make a request within you service, you can use one of the following:

  • getQuery: perform a GET request
  • postData: perform a POST request
  • postJson: perform a POST request with a JSON body
  • putData: perform a PUT request
  • putJson: perform a PUT request with a JSON body
  • deleteData: perform a DELETE request
  • deleteJson: perform a DELETE request with a JSON body
  • patchData: perform a PATCH request
  • patchJson: perform a PATCH request with a JSON body
  • download: downloads a file
  • getBytes: gets bytes from an endpoint

Example

import 'package:dio/dio.dart';
import 'package:http_services/http_services.dart';

import 'todos_service.dart';


class TodosRequest extends RequestBase {
  final int page;

  TodosRequest(this.page) : assert(page != null && page > 0);
  @override
  String get endpoint => '/todos/$page';

  @override
  Map<String, dynamic> toJson() {
    return {};
  }
}


class TodosResponse extends ResponseBase {
  final int userId;
  final int id;
  final String title;
  final bool completed;

  TodosResponse({
    this.userId,
    this.id,
    this.title,
    this.completed,
  });

  factory TodosResponse.fromJson(Map<String, dynamic> json) => TodosResponse(
        userId: json['userId'],
        id: json['id'],
        title: json['title'],
        completed: json['completed'],
      );
}


class TodosService extends HttpServiceBase {
  TodosService(Dio dioInstance) : super(dioInstance);

  Future<TodosResponse> getTodo(int page) {
    final request = TodosRequest(page);

    return getQuery(
      request: request,
      mapper: (json, _) => TodosResponse.fromJson(json),
    );
  }
}

void main() async {
  final dio = Dio(
    BaseOptions(
      baseUrl: 'https://jsonplaceholder.typicode.com/',
    ),
  );

  final service = TodosService(dio);

  try {
    print("Requesting data...");
    final response1 = await service.getTodo(1);
    print(
      "user id: ${response1.userId}\n"
      "id: ${response1.id}\n"
      "title: ${response1.title}\n"
      "completed: ${response1.completed}",
    );
  } on HttpServiceException catch (e) {
    print('Service exception: ${e.runtimeType}');
  }
}

Notes

There might be some cases where the JSON response is not like this:

{
  "data": [{"name": "Bob"},{"name":"Alice"}],
}

This will not be treated as a JSON since it's not a Map<String,dynamic> but it's a List<Map<String,dynamic>>. A solution might be to use the orElse parameter when performing the HTTP request. Remember that orElse is executed to map any response body that's not Map<String,dynamic>.

Similarly, if you ever find yourself in need of sending a JSON like the one above, a solution might be to override the onData method of RequestBase in your request object and then using the *data version of the request. For example:

class User{
  final String name;
  User(this.name);

  Map<String,dynamic> toJson() => {'name': name};
}

class UsersToSend extends RequestBase{
  final List<User> users;
  UsersToSend(this.users);

  @override
  Map<String,dynamic> toJson() => {};

  @override
  List<User> toData() => users;
}

and then use postData instead of using postJson in your service.

Contributors 🚀

You might also like...

The deta-dart library is the simple way to interact with the services of the free clud on the Deta plataform.

Deta A Dart package to interact with the HTTP API of the free services of the Deta plataform. 🚨 WARNING 🚨 This client should only be used on the ser

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

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

Jan 3, 2023

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

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

Dec 27, 2021

A middleware library for Dart's http library.

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

Oct 23, 2021

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

Check the availability of Google Play services on the current device

Flutter Google Api Availability Plugin A Flutter plugin to check the availability of Google Play services on the current device. Features Check the av

Dec 28, 2022

Flutter Home Rent Services App UI

flutter_home_rental_app Flutter Home Rental App UI Getting Started This project is a starting point for a Flutter application. A few resources to get

Dec 4, 2022
Comments
  • Added unit tests

    Added unit tests

    I've added some tests for the base functionalities of the package. base_test.dart tests all the methods of HttpServiceBase errors_test.dart tests all the exceptions thrown by HttpServiceBase

    opened by deb-95 1
  • Fixed missing response parameter in README example

    Fixed missing response parameter in README example

    The mapper function in TodosService was missing the second parameter causing a compile error if put in a .dart file because T Function(Map<String, dynamic>) did not match the mapper signature of T Function(Map<String, dynamic>, Response response)

    Fixed by adding a _ placeholder for the Response parameter.

    opened by deb-95 0
Owner
Antonello Galipò
Flutter and Android developer with an enormous love for Yoga and hipster habits.
Antonello Galipò
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 package help you to make api call and handle error faster, also you can check for internet before call api.

http_solver ##not for production use, only for learning purpose. A package help you to make api call and handle error faster, also you can check for i

Abdelrahman Saed 1 Jun 18, 2020
A library to easily handle sequential queueing of futures in dart.

queue Easily queue futures and await their values. This library allows you to send a future to central queue. The queue will execute the futures in th

Ryan Knell 38 Jan 4, 2023
A package containing different kinds of services and utilities.

TODO: Put a short description of the package here that helps potential users know whether this package might be useful for them. Features TODO: List w

Daniel 0 Nov 26, 2021
Telnyx flutter - A Flutter package for both android and iOS which helps developers with Telnyx API services

Telnyx Flutter A Flutter package for both android and iOS which helps developers

Kfir Matityahu 0 Jan 23, 2022
SearchBar widget to handle most of search cases

flappy_search_bar A SearchBar widget handling most of search cases. Usage To use this plugin, add flappy_search_bar as a dependency in your pubspec.ya

Smart&Soft 171 Dec 2, 2022
⚡ Cache Manager A tidy utility to handle cache of your flutter app like a Boss.

⚡ Cache Manager A tidy utility to handle cache of your flutter app like a Boss. It provides support for both iOS and Android platforms (offcourse). ??

Abhishek Chavhan 10 Oct 25, 2022
A beautiful, secure and simple authenticator app that supports multiple protocols and services. Free and open source. Written in Flutter and Dart.

OpenAuth A beautiful, secure and simple authenticator app that supports multiple protocols and services. Free and open source. Written in Flutter and

Isaiah Collins Abetong 31 Oct 5, 2022
A cross-platform Fediverse client for micro-blogging services written in Flutter/Dart.

Kaiteki A 快適 (kaiteki) Fediverse client for microblogging instances, made with Flutter and Dart. Currently, Kaiteki is still in a proof-of-concept/alp

Kaiteki 141 Jan 5, 2023