http_api 0.4.2

  • Readme
  • Changelog
  • Example
  • Installing
  • 74

http_api #

Codemagic build status Pub Version License: MIT

Simple yet powerful wrapper around http package inspired by apollo graphql links. This package provides you a simple way of adding middlewares to your app http requests.

IMPORTANT #

This library is under development, breaking API changes might still happen. If you would like to make use of this library please make sure to provide which version you want to use e.g:

dependencies:
  http_api: 0.4.0

Getting Started #

1. First create your Api class by extending BaseApi class #

// define your api class
class Api extends BaseApi {

  Api({
    @required Uri url,
    ApiLink link,
    Map<String, String> defaultHeaders,
  }) : super(
          url: url,
          defaultHeaders: defaultHeaders,
          link: link,
        );

  /// Implement api request methods 
  Future<ExamplePhotoModel> getRandomPhoto() async {

    /// Use [send] method to make api request
    final response = await send(ApiRequest(
      endpoint: "/id/${Random().nextInt(50)}/info",
      method: HttpMethod.get,
    ));

    /// Parse http response
    return ExamplePhotoModel.fromJson(json.decode(response.body));
  }
}

TIP: You can provide your Api instance down the widget tree using provider package.

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    return Provider(
        create: (_) => Api(
          /// Provide base url for your api
          url: Uri.parse("https://picsum.photos"),
          /// Assign middleware by providing ApiLinks (to provide more than one middleware, chain them)
          link: HeadersMapperLink(["authorization"])
              .chain(DebugLink(responseBody: true)),
              .chain(HttpLink()),
        ),
        /// Your app
        child: MaterialApp(
          title: 'my_app',
          onGenerateRoute: _generateRoute,
        ),
      );
  }
}

2. Make api request #

class _ApiExampleScreenState extends State<ApiExampleScreen> {

  void _fetchPhoto() async {
    final api = Provider.of<Api>(context, listen: false);
    ExamplePhotoModel photo = await api.getRandomPhoto();
    // Do sth with response
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: RaisedButton(
          child: const Text("Fetch photo"),
          onPressed: _fetchPhoto,
        ),
      ),
    );
  }

}

TODO: #

  • Unit tests
  • Caching based on [ApiRequest]
  • Improve readme (provide more examples)
  • Simple graphQL client (without subscriptions support)

[0.4.2] - 03 June 2020. #

  • Added ok property to ApiResponse
  • Added redirect property to ApiResponse

[0.4.1] - 27 April 2020. #

  • Added FileField.fromStream constructor.

[0.4.0] - 19 April 2020. #

  • BaseApi now uses Uri path from url argument (not only host) also port and queryParameters are coppied.
  • Added unit tests

[0.3.0] - 19 April 2020. #

Breaking changes #

  • Renamed ApiBase to BaseApi
  • Replaced BaseApi call method with send method which accepts the argument ApiRequest.

[0.2.0] - 18 April 2020. #

  • Add example
  • Fixed request duration bug (DebugLink)

[0.1.0+3] - 18 April 2020. #

  • Initial release.

example/lib/main.dart

import 'dart:convert';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:http_api/http_api.dart';
import 'package:provider/provider.dart';

import 'models/example_photo_model.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Provider(
      create: (_) => Api(
        /// Provide base url for your api
        url: Uri.parse("https://picsum.photos"),

        /// Assign middleware by providing ApiLinks (to provide more than one middleware, chain them)
        link: DebugLink(responseDuration: true, url: true).chain(HttpLink()),
      ),
      child: MaterialApp(
        title: 'http_api example',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: MyHomePage(),
      ),
    );
  }
}

// define your api class
class Api extends BaseApi {
  Api({
    @required Uri url,
    ApiLink link,
    Map<String, String> defaultHeaders,
  }) : super(
          url: url,
          defaultHeaders: defaultHeaders,
          link: link,
        );

  /// Implement api request methods
  Future<ExamplePhotoModel> getRandomPhoto() async {
    /// Use [send] method to make api request
    final response = await send(ApiRequest(
      endpoint: "/id/${Random().nextInt(50)}/info",
      method: HttpMethod.get,
    ));

    /// Parse http response
    return ExamplePhotoModel.fromJson(json.decode(response.body));
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  ExamplePhotoModel _currentPhoto;

  void _fetchPhoto() async {
    final api = Provider.of<Api>(context, listen: false);
    ExamplePhotoModel photo = await api.getRandomPhoto();

    setState(() {
      _currentPhoto = photo;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Container(
              width: 300,
              height: 300,
              color: Colors.black12,
              child: _currentPhoto != null
                  ? Image.network(
                      _currentPhoto.downloadUrl,
                      fit: BoxFit.cover,
                    )
                  : null,
            ),
            const SizedBox(height: 15),
            RaisedButton(
              child: const Text("Fetch photo"),
              onPressed: _fetchPhoto,
            ),
          ],
        ),
      ),
    );
  }
}

Use this package as a library

1. Depend on it

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


dependencies:
  http_api: ^0.4.2

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support 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_api/http_api.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
49
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]
74
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.14
  • Flutter: 1.17.5

Analysis suggestions

Package not compatible with SDK dart

Because:

  • http_api that is a package requiring null.

Package not compatible with runtime flutter-web on web

Because:

  • package:http_api/http_api.dart that imports:
  • dart:io

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.1.0 <3.0.0
flutter 0.0.0
http ^0.12.1 0.12.1
http_parser ^3.1.4 3.1.4
meta ^1.1.8 1.1.8 1.2.2
Transitive dependencies
charcode 1.1.3
collection 1.14.12 1.14.13
path 1.7.0
pedantic 1.9.0 1.9.2
sky_engine 0.0.99
source_span 1.7.0
string_scanner 1.0.5
term_glyph 1.1.0
typed_data 1.1.6 1.2.0
vector_math 2.0.8 2.1.0-nullsafety
Dev dependencies
flutter_test
mockito 4.1.1
test any