http_services 1.2.0

  • Readme
  • Changelog
  • Example
  • Installing
  • 69

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.

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

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}');
  }
}

1.2.0 #

  • Added methods to perform PUT, DELETE and PATCHrequests.

1.1.1 #

  • ApiException toString method now returns the httpMessage.

1.1.0 #

  • Separated DisposableObject dependency.
  • Updated README

1.0.0+1 #

Formatting and description updated

1.0.0 #

Initial release

example/main.dart

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

import 'todos_service.dart';

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}');
  }
}

Use this package as a library

1. Depend on it

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


dependencies:
  http_services: ^1.2.0

2. Install it

You can install packages from the command line:

with pub:


$ pub get

with Flutter:


$ flutter pub get

Alternatively, your editor might support pub get or 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_services/http_services.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
37
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
69
Learn more about scoring.

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

  • Dart: 2.8.4
  • pana: 0.13.15

Analysis suggestions

Package not compatible with runtime flutter-web on Web

Because:

  • package:http_services/http_services.dart that imports:
  • package:http_services/src/models/exceptions/api_exception.dart that imports:
  • dart:io

Package not compatible with runtime js

Because:

  • package:http_services/http_services.dart that imports:
  • package:http_services/src/models/exceptions/api_exception.dart that imports:
  • dart:io

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.7.0 <3.0.0
dio ^3.0.9 3.0.9
disposable_object ^1.0.0 1.0.0+1
meta ^1.1.8 1.2.2 1.3.0-nullsafety
Transitive dependencies
charcode 1.1.3
collection 1.14.13 1.15.0-nullsafety
http_parser 3.1.4
path 1.7.0
source_span 1.7.0
string_scanner 1.0.5
term_glyph 1.1.0
typed_data 1.2.0 1.3.0-nullsafety
Dev dependencies
pedantic ^1.8.0