Home

Awesome

rest.js

Note: rest.js is not actively maintained.

Just enough client, as you need it. Make HTTP requests from a browser or Node.js applying only the client features you need. Configure a client once, and share it safely throughout your application. Easily extend with interceptors that wrap the request and/or response, or MIME type converters for rich data formats.

Build Status

<table> <tr><td>Master</td><td><a href="http://travis-ci.org/cujojs/rest" target="_blank"><img src="https://secure.travis-ci.org/cujojs/rest.png?branch=master" /></a></tr> <tr><td>Development</td><td><a href="http://travis-ci.org/cujojs/rest" target="_blank"><img src="https://secure.travis-ci.org/cujojs/rest.png?branch=dev" /></a></tr> </table>

Usage

Using rest.js is easy. The core clients provide limited functionality around the request and response lifecycle. The request and response objects are normalized to support portability between different JavaScript environments.

The return value from a client is a promise that is resolved with the response when the remote request finishes.

The core client behavior can be augmented with interceptors. An interceptor wraps the client and transforms the request and response. For example: an interceptor may authenticate a request, or reject the promise if an error is encountered. Interceptors may be combined to create a client with the desired behavior. A configured interceptor acts just like a client. The core clients are basic, they only know the low level mechanics of making a request and parsing the response. All other behavior is applied and configured with interceptors.

Interceptors are applied to a client by wrapping. To wrap a client with an interceptor, call the wrap method on the client providing the interceptor and optionally a configuration object. A new client is returned containing the interceptor's behavior applied to the parent client. It's important to note that the behavior of the original client is not modified, in order to use the new behavior, you must use the returned client.

Making a basic request:

var rest = require('rest');

rest('/').then(function(response) {
    console.log('response: ', response);
});

In this example, you can see that the request object is very simple, it just a string representing the path. The request may also be a proper object containing other HTTP properties.

The response should look familiar as well, it contains all the fields you would expect, including the response headers (many clients ignore the headers).

Working with JSON:

If you paid attention when executing the previous example, you may have noticed that the response.entity is a string. Often we work with more complex data types. For this, rest.js supports a rich set of MIME type conversions with the MIME Interceptor. The correct converter will automatically be chosen based on the Content-Type response header. Custom converts can be registered for a MIME type, more on that later...

var rest, mime, client;

rest = require('rest'),
mime = require('rest/interceptor/mime');

client = rest.wrap(mime);
client({ path: '/data.json' }).then(function(response) {
    console.log('response: ', response);
});

Before an interceptor can be used, it needs to be configured. In this case, we will accept the default configuration, and obtain a client. Now when we see the response, the entity will be a JS object instead of a String.

Composing Interceptors:

var rest, mime, errorCode, client;

rest = require('rest'),
mime = require('rest/interceptor/mime');
errorCode = require('rest/interceptor/errorCode');

client = rest.wrap(mime)
             .wrap(errorCode, { code: 500 });
client({ path: '/data.json' }).then(
    function(response) {
        console.log('response: ', response);
    },
    function(response) {
        console.error('response error: ', response);
    }
);

In this example, we take the client create by the MIME Interceptor, and wrap it with the Error Code Interceptor. The error code interceptor accepts a configuration object that indicates what status codes should be considered an error. In this case we override the default value of <=400, to only reject with 500 or greater status code.

Since the error code interceptor can reject the response promise, we also add a second handler function to receive the response for requests in error.

Clients can continue to be composed with interceptors as needed. At any point the client as configured can be shared. It is safe to share clients and allow other parts of your application to continue to compose other clients around the shared core. Your client is protected from additional interceptors that other parts of the application may add.

Declarative Interceptor Composition:

First class support is provided for declaratively composing interceptors using wire.js. wire.js is an dependency injection container; you specify how the parts of your application interrelate and wire.js takes care of the dirty work to make it so.

Let's take the previous example and configure the client using a wire.js specification instead of imperative code.

{
	...,
	client: {
		rest: [
			{ module: 'rest/interceptor/mime' },
			{ module: 'rest/interceptor/errorCode', config: { code: 500 } }
		]
	},
	$plugins: [{ module: 'rest/wire' }]
}

There are a couple things to notice. First is the '$plugins' section, by declaring the rest/wire module, the rest factory becomes available within the specification. The second thing to notice is that we no longer need to individually require() interceptor modules; wire.js is smart enough to automatically fetch the modules. The interceptors are then wrapped in the order they are defined and provided with the corresponding config object, if it's defined. The resulting client can then be injected into any other object using standard wire.js facilities.

Custom MIME Converters:

var registry = require('rest/mime/registry');

registry.register('application/vnd.com.example', {
    read: function(str) {
        var obj;
        // do string to object conversions
        return obj;
    },
    write: function(obj) {
        var str;
        // do object to string conversions
        return str;
    }
});

Registering a custom converter is a simple as calling the register function on the mime registry with the type and converter. A converter has just two methods: read and write. Read converts a String to a more complex Object. Write converts an Object back into a String to be sent to the server. HTTP is fundamentally a text based protocol after all.

Built in converters are available under rest/mime/type/{type}, as an example, JSON support is located at rest/mime/type/application/json. You never need to know this as a consumer, but it's a good place to find examples.

Supported Environments

Our goal is to work in every major JavaScript environment; Node.js and major browsers are actively tested and supported.

If your preferred environment is not supported, please let us know. Some features may not be available in all environments.

Tested environments:

Specific browser test are provided by Travis CI and Sauce Labs' Open Sauce Plan. You can see specific browser test results, although odds are they do not reference this specific release/branch/commit.

Getting Started

rest.js can be installed via npm, Bower, jspm, or from source.

To install without source:

$ npm install --save rest

or

$ bower install --save rest

or

$ jspm install rest

From source:

$ npm install

rest.js is designed to run in a browser environment, utilizing a CommonJS Module loader, a transformer such as Browserify or WebPack, or within Node.js. Any module loader capable of loading either CommonJS modules should be able to load rest.js. cujoJS curl.js is actively tested with the cjsm11 loader.

An ECMAScript 5 compatible environment is assumed. Older browsers, ::cough:: IE, that do not support ES5 natively can be shimmed. Any shim should work, although we test with cujoJS poly.js

Documentation

Full project documentation is available in the docs directory.

Running the Tests

The test suite can be run in two different modes: in node, or in a browser. We use npm and Buster.JS as the test driver, buster is installed automatically with other dependencies.

Before running the test suite for the first time:

$ npm install

To run the suite in node:

$ npm test

To run the suite in a browser:

$ npm start
browse to http://localhost:8282/ in the browser(s) you wish to test.  It can take a few seconds to start.

Get in Touch

You can find us on the cujojs mailing list, or the #cujojs IRC channel on freenode.

Please report issues on GitHub. Include a brief description of the error, information about the runtime (including shims) and any error messages.

Feature requests are also welcome.

Contributors

Please see CONTRIBUTING.md for details on how to contribute to this project.

Copyright

Copyright 2012-2016 the original author or authors

rest.js is made available under the MIT license. See LICENSE.txt for details.

Change Log

2.0.0

1.3.2

1.3.1

1.3.0

1.2.0

1.1.1

1.1.0

1.0.3

1.0.2

1.0.1

1.0.0

0.9.4

0.9.3

0.9.2

0.9.1

0.9.0

0.8.4

0.8.3

0.8.2

0.8.1

0.8.0

0.7.5