fnx_rest 2.1.1

fnx_rest #

Set of REST tools which work nicely with Dart 2 / Angular.

This is a plain old REST client, if you are looking for something more sophisticated, try streamy for instance.

fnx_rest is oriented to be developer and Angular friendly and is particularly useful when creating boring CRUD applications with many similar API calls.

Example #

    import 'package:fnx_rest/fnx_rest_browser.dart';
//     import 'package:fnx_rest/fnx_rest_io.dart'; (when not in a browser)       

    RestClient root = BrowserRestClient.root("/api/v1");        
    RestResult response = await root.child("/users").get();
    List users = response.data;

Angular support #

You can define root REST client, add your API keys and other additional headers to it and inject this root client with Angular's dependency injection to your elements and/or services.

    RestClient root = BrowserRestClient.root("/api/v1");            
    // your component
    class MyApp {
        RestClient restRoot;
    // add custom headers, for example after user's signing in
    restRoot.setHeader("Authorization", authKey);       

(see Angular docs for DI details)

RestClient is hierarchical:

    RestClient root = BrowseRestClient.root("/api/v1");   //  /api/v1
    RestClient users = root.child("/users");            //  /api/v1/users            
    RestClient john = users.child("/123");              //  /api/v1/users/123

All children inherit configuration of their parents, but are allowed to override it.

RestClient supports query parameters:

    RestClient limitedUsers = users.setParam('limit', '1000');  //  /api/v1/users?limit=1000            

Typically you would create a child of the root rest client in your component like this:

    class UserManagement {
        RestClient users;
        UserManagement(RestClient root) {
            users = root.child("/users"); // endpoint /api/v1/users

Every instance of RestClient has bool working property, which indicates whether this client is currently processing a request/response or not. You can use it to indicate "working" state to the user:

<p *ngIf="users.working">Sending user data to server ...</p>

This property is recursively propagated to client's parents so you can indicate this "working" state on any level. Locally (for a form), or globally (for the whole app).

// update user     

Until the request is processed, john.working == true, users.working == true and root.working == true.

// read users
users.get( ... )

In this case john.working == false but users.working == true and root.working == true.

You can easily use this behaviour to disable a form and all it's buttons after submitting edited user data, but in the same time you can have universal global indicator of any HTTP communication (in your app status bar, for example).

HTTP methods #

RestClient has following methods:

    Future<RestResult> get({dynamic data, Map<String, String> headers}) ...
    Future<RestResult> post(dynamic data, {Map<String, String> headers}) ...
    Future<RestResult> put(dynamic data, {Map<String, String> headers}) ...
    Future<RestResult> delete({dynamic data, Map<String, String> headers}) ...
    Future<RestResult> head({Map<String, String> headers}) ...

Use optional parameter headers to specify custom ad-hoc headers you need in this call only. Headers will be merged with your RestClient default headers, it's parent's headers etc. up to the root RestClient.

Don't use this parameter to specify Content-Type or Accept headers, see below.

RestResult #

Each call returns Future<RestResult>. RestResult contains status (HTTP status, int) and data which are already converted to your desired type (see below) - Dart Map or Dart List by default.

Request/response serialization #

By default, the root client is configured to produce and consume JSON and Dart Maps and Lists. You can easily customize this behaviour to accept or produce any binary data:

    RestClient img = root.child("/images");        //  /api/v1/images     

Such data will be sent and received as List<int> or inject any custom text based serialization or deserialization you need:

    typedef dynamic Serializer(dynamic payload);
    typedef dynamic Deserializer(String payload);

    client.accepts("text/csv", myCsvDeserializeFunction);
    client.produces("text/csv", myCsvSerializeFunction);

This configuration is inherited by client's children.

Work in progress #

Suggestions, pull requests and bugreports are more than welcome.

Changelog #

2.2.0 #

Newer version of http client. Example.

2.1.0 #

Added support for streaming requests.

0.0.1 #

  • Initial version


import 'package:fnx_rest/fnx_rest_io.dart';

void main() async {
  // Init your Rest API client
  RestClient apiRoot = new IoRestClient.root(
      "https://jsonplaceholder.typicode.com"); // Use BrowserRestClient in browser ..

  // configure global headers
  apiRoot.setHeader("Authorization", "FacelessMan");

  // follow serverside endpoints structure ...
  var apiUsers = apiRoot.child("/users");
  RestResult rr = await apiUsers.get();
  if (!rr.success) rr.throwError();

  // follow serverside endpoints structure ...
  var myApiUser = apiUsers.child("/1");
  rr = await myApiUser.get();
  if (!rr.success) rr.throwError();

  // customize payload handling
  // var myApiUserPhoto = myApiUser.child("/photo");
  // myApiUserPhoto.acceptsBinary("image/png");

Use this package as a library

1. Depend on it

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

  fnx_rest: ^2.1.1

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:fnx_rest/fnx_rest.dart';
Describes how popular the package is relative to other packages. [more]
Code health derived from static analysis. [more]
Reflects how tidy and up-to-date the package is. [more]
Weighted score of the above. [more]
Learn more about scoring.

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

  • Dart: 2.4.0
  • pana: 0.12.19


Detected platforms: Flutter, web, other

No platform restriction found in primary library package:fnx_rest/fnx_rest.dart.

Health suggestions

Fix lib/src/rest_client.dart. (-1 points)

Analysis of lib/src/rest_client.dart reported 2 hints:

line 150 col 22: This function has a return type of 'RestResult', but doesn't end with a return statement.

line 181 col 9: DO use curly braces for all flow control structures.

Fix lib/fnx_rest_browser.dart. (-0.50 points)

Analysis of lib/fnx_rest_browser.dart reported 1 hint:

line 79 col 33: Future results in async function bodies must be awaited or marked unawaited using package:pedantic.

Fix lib/fnx_rest_io.dart. (-0.50 points)

Analysis of lib/fnx_rest_io.dart reported 1 hint:

line 65 col 33: Future results in async function bodies must be awaited or marked unawaited using package:pedantic.


Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0-dev.61.0 <3.0.0
http >=0.12.0 <1.0.0 0.12.0+2
logging >=0.11.0 <1.0.0 0.11.3+2
Transitive dependencies
async 2.3.0
charcode 1.1.2
collection 1.14.11
http_parser 3.1.3
meta 1.1.7
path 1.6.2
pedantic 1.8.0+1
source_span 1.5.5
string_scanner 1.0.4
term_glyph 1.1.0
typed_data 1.1.6
Dev dependencies
mockito ^3.0.0
test ^1.6.0