• This repository has been archived on 04/May/2019
  • Stars
    star
    969
  • Rank 47,201 (Top 1.0 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 10 years ago
  • Updated over 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A pure JS client for interacting with server-side RESTful resources. Think Restangular without Angular.
archived Archived Repository
This code is no longer maintained. Feel free to fork it, but use it at your own risks.

restful.js Build Status

A pure JS client for interacting with server-side RESTful resources. Think Restangular without Angular.

Note: All examples written in this README use the ES6 specification.

Installation

It is available with bower or npm:

bower install restful.js
npm install restful.js

The dist folder contains two built versions which you can use to include either restful.js or a standalone version. Standalone version already embeds fetch.

Alternately, you can use a module loader like webpack.

import restful from 'restful.js';

Usage

Create a resource targeting your API

Restful.js needs an HTTP backend in order to perform queries. Two http backend are currently available:

  • fetch: For using restful.js in a browser.
  • request: For using restful.js in Node.js. There are defined as optional dependencies and therefore you must install them either with npm or bower depending your package manager.

Start by defining the base endpoint for an API, for instance http://api.example.com with the good http backend.

For a browser build :

import whatwg-fetch;
import restful, { fetchBackend } from 'restful.js';

const api = restful('http://api.example.com', fetchBackend(fetch));

For a node build :

import request from 'request';
import restful, { requestBackend } from 'restful.js';

const api = restful('http://api.example.com', requestBackend(request));

For those who prefers a ready-to-go version, pre built version of restful.js with fetch are available into the dist folder.

Collections and Members endpoints

A collection is an API endpoint for a list of entities, for instance http://api.example.com/articles. Create it using the all(name) syntax:

const articlesCollection = api.all('articles');  // http://api.example.com/articles

articlesCollection is just the description of the collection, the API wasn't fetched yet.

A member is an API endpoint for a single entity, for instance http://api.example.com/articles/1. Create it using the one(name, id) syntax:

const articleMember = api.one('articles', 1);  // http://api.example.com/articles/1

Just like above, articleMember is a description, not an entity.

You can chain one() and all() to target the required collection or member:

const articleMember = api.one('articles', 1);  // http://api.example.com/articles/1
const commentsCollection = articleMember.all('comments');  // http://api.example.com/articles/1/comments

Custom endpoint URL

In case you need to set a custom endpoint URL, you can use custom methods.

const articleCustom = api.custom('articles/beta');  // http://api.example.com/articles/beta

// you can add an absolute url
const articleCustom = api.custom('http://custom.url/articles/beta', false);  // http://custom.url/articles/beta

A custom endpoint acts like a member, and therefore you can use one and all to chain other endpoint with it.

Entities

Once you have collections and members endpoints, fetch them to get entities. Restful.js exposes get() and getAll() methods for fetching endpoints. Since these methods are asynchronous, they return a native Promise for response.

If your application does not support native Promise, you can use a polyfill.

const articleMember = api.one('articles', 1);  // http://api.example.com/articles/1
articleMember.get().then((response) => {
    const articleEntity = response.body();

    const article = articleEntity.data();
    console.log(article.title); // hello, world!
});

const commentsCollection = articleMember.all('comments');  // http://api.example.com/articles/1/comments
commentsCollection.getAll().then((response) => {
    const commentEntities = response.body();

    commentEntities.forEach((commentEntity) => {
        const comment = commentEntity.data();
        console.log(comment.body);
    })
});

Tip: You can describe a member based on a collection and trigger the API fetch at the same time by calling get(id):

// fetch http://api.example.com/articles/1/comments/4
const articleMember = api.one('articles', 1);
const commentMember = articleMember.one('comments', 4);
commentMember.get().then((response) => {
    //
});
// equivalent to
const commentsCollection = articleMember.all('comments');
commentsCollection.get(4).then((response) => {
    //
});

Response

A response is made from the HTTP response fetched from the endpoint. It exposes statusCode(), headers(), and body() methods. For a GET request, the body method will return one or an array of entities. Therefore you can disable this hydration by calling body(false).

Headers

For most of cases, headers in a response will be a plain object with headers data, but for some browsers, that don't support iteration over Headers object, it will simply be returned as a Headers object, so you can use get method from it to get required headers.

Entity Data

An entity is made from the HTTP response data fetched from the endpoint. It exposes a data() method:

const articleCollection = api.all('articles');  // http://api.example.com/articles

// http://api.example.com/articles/1
api.one('articles', 1).get().then((response) => {
    const articleEntity = response.body();

    // if the server response was { id: 1, title: 'test', body: 'hello' }
    const article = articleEntity.data();
    article.title; // returns `test`
    article.body; // returns `hello`
    // You can also edit it
    article.title = 'test2';
    // Finally you can easily update it or delete it
    articleEntity.save(); // will perform a PUT request
    articleEntity.delete(); // will perform a DELETE request
}, (response) => {
    // The reponse code is not >= 200 and < 400
    throw new Error('Invalid response');
});

You can also use the entity to continue exploring the API. Entities expose several other methods to chain calls:

  • entity.one ( name, id ): Query a member child of the entity.
  • entity.all ( name ): Query a collection child of the entity.
  • entity.url (): Get the entity url.
  • entity.save ( [, data [, params [, headers ]]] ): Save the entity modifications by performing a POST request.
  • entity.delete ( [, data [, params [, headers ]]] ): Remove the entity by performing a DELETE request.
  • entity.id (): Get the id of the entity.
const articleMember = api.one('articles', 1);  // http://api.example.com/articles/1
const commentMember = articleMember.one('comments', 3);  // http://api.example.com/articles/1/comments/3
commentMember.get()
    .then((response) => {
        const commentEntity = response.body();

        // You can also call `all` and `one` on an entity
        return comment.all('authors').getAll(); // http://api.example.com/articles/1/comments/3/authors
    }).then((response) => {
        const authorEntities = response.body();

        authorEntities.forEach((authorEntity) => {
            const author = authorEntity.data();
            console.log(author.name);
        });
    });

entity.id() will get the id from its data regarding of the identifier of its endpoint. If you are using another name than id you can modify it by calling identifier() on the endpoint.

const articleCollection = api.all('articles');  // http://api.example.com/articles
articleCollection.identifier('_id'); // We use _id as id field

const articleMember = api.one('articles', 1);  // http://api.example.com/articles/1
articleMember.identifier('_id'); // We use _id as id field

Restful.js uses an inheritance pattern when collections or members are chained. That means that when you configure a collection or a member, it will configure all the collection on members chained afterwards.

// configure the api
api.header('AuthToken', 'test');
api.identifier('_id');

const articlesCollection = api.all('articles');
articlesCollection.get(1); // will send the `AuthToken` header
// You can configure articlesCollection, too
articlesCollection.header('foo', 'bar');
articlesCollection.one('comments', 1).get(); // will send both the AuthToken and foo headers

API Reference

Restful.js exposes similar methods on collections, members and entities. The name are consistent, and the arguments depend on the context.

Collection methods

  • addErrorInterceptor ( interceptor ): Add an error interceptor. You can alter the whole error.
  • addRequestInterceptor ( interceptor ): Add a request interceptor. You can alter the whole request.
  • addResponseInterceptor ( interceptor ): Add a response interceptor. You can alter the whole response.
  • custom ( name [, isRelative = true ] ): Target a child member with a custom url.
  • delete ( id [, data [, params [, headers ]]] ): Delete a member in a collection. Returns a promise with the response.
  • getAll ( [ params [, headers ]] ): Get a full collection. Returns a promise with an array of entities.
  • get ( id [, params [, headers ]] ): Get a member in a collection. Returns a promise with an entity.
  • head ( id [, params [, headers ]] ): Perform a HEAD request on a member in a collection. Returns a promise with the response.
  • header ( name, value ): Add a header.
  • headers (): Get all headers added to the collection.
  • on ( event, listener ): Add an event listener on the collection.
  • once ( event, listener ): Add an event listener on the collection which will be triggered only once.
  • patch ( id [, data [, params [, headers ]]] ): Patch a member in a collection. Returns a promise with the response.
  • post ( [ data [, params [, headers ]]] ): Create a member in a collection. Returns a promise with the response.
  • put ( id [, data [, params [, headers ]]] ): Update a member in a collection. Returns a promise with the response.
  • url (): Get the collection url.
// http://api.example.com/articles/1/comments/2/authors
const authorsCollection = api.one('articles', 1).one('comments', 2).all('authors');
authorsCollection.getAll().then((authorEntities) => { /*  */ });
authorsCollection.get(1).then((authorEntity) => { /*  */ });

Member methods

  • addErrorInterceptor ( interceptor ): Add an error interceptor. You can alter the whole error.
  • addRequestInterceptor ( interceptor ): Add a request interceptor. You can alter the whole request.
  • addResponseInterceptor ( interceptor ): Add a response interceptor. You can alter the whole response.
  • all ( name ): Target a child collection name.
  • custom ( name [, isRelative = true ] ): Target a child member with a custom url.
  • delete ( [ data [, params [, headers ]]] ): Delete a member. Returns a promise with the response.
  • get ( [ params [, headers ]] ): Get a member. Returns a promise with an entity.
  • head ( [ params [, headers ]] ): Perform a HEAD request on a member. Returns a promise with the response.
  • header ( name, value ): Add a header.
  • headers (): Get all headers added to the member.
  • on ( event, listener ): Add an event listener on the member.
  • once ( event, listener ): Add an event listener on the member which will be triggered only once.
  • one ( name, id ): Target a child member in a collection name.
  • patch ( [ data [, params [, headers ]]] ): Patch a member. Returns a promise with the response.
  • post ( [ data [, params [, headers ]]] ): Create a member. Returns a promise with the response.
  • put ( [ data [, params [, headers ]]] ): Update a member. Returns a promise with the response.
  • url (): Get the member url.
// http://api.example.com/articles/1/comments/2
const commentMember = api.one('articles', 1).one('comments', 2);
commentMember.get().then((commentEntity) => { /*  */ });
commentMember.delete().then((data) => { /* */ });

Interceptors

An error, response or request interceptor is a callback which looks like this:

resource.addRequestInterceptor((config) => {
    const { data, headers, method, params, url } = config;
    // all args had been modified
    return {
        data,
        params,
        headers,
        method,
        url,
    };

    // just return modified arguments
    return {
        data,
        headers,
    };
});

resource.addResponseInterceptor((response, config) => {
    const { data, headers, statusCode } = response;
    // all args had been modified
    return {
        data,
        headers,
        statusCode
    };

    // just return modified arguments
    return {
        data,
        headers,
    };
});

resource.addErrorInterceptor((error, config) => {
    const { message, response } = error;
    // all args had been modified
    return {
        message,
        response,
    };

    // just return modified arguments
    return {
        message,
    };
});

Response methods

  • body (): Get the HTTP body of the response. If it is a GET request, it will hydrate some entities. To get the raw body call it with false as argument.
  • headers (): Get the HTTP headers of the response.
  • statusCode (): Get the HTTP status code of the response.

Entity methods

  • all ( name ): Query a collection child of the entity.
  • custom ( name [, isRelative = true ] ): Target a child member with a custom url.
  • data () : Get the JS object unserialized from the response body (which must be in JSON)
  • id (): Get the id of the entity.
  • one ( name, id ): Query a member child of the entity.
  • delete ( [, data [, params [, headers ]]] ): Delete the member link to the entity. Returns a promise with the response.
  • save ( [, data [, params [, headers ]]] ): Update the member link to the entity. Returns a promise with the response.
  • url (): Get the entity url.
// http://api.example.com/articles/1/comments/2
const commentMember = api.one('articles', 1).one('comments', 2);
commentMember.get().then((commentEntity) => {
    commentEntity.save();
    commentEntity.remove();
});

Error Handling

To deal with errors, you can either use error interceptors, error callbacks on promise or error events.

const commentMember = resource.one('articles', 1).one('comments', 2);
commentMember
    .get()
    .then((commentEntity) => { /*  */ })
    .catch((err) => {
        // deal with the error
    });

commentMember.on('error', (error, config) => {
    // deal with the error
});

Events

Any endpoint (collection or member) is an event emitter. It emits request, response and error events. When it emits an event, it is propagated to all its parents. This way you can listen to all errors, requests and response on your restful instance by listening on your root endpoint.

api.on('error', (error, config) => {
    // deal with the error
});

api.on('request', (config) => {
    // deal with the request
});

api.on('response', (config) => {
    // deal with the response
});

When you use interceptors, endpoints will also emit request:interceptor:pre, request:interceptor:post, response:interceptor:pre, response:interceptor:post, error:interceptor:pre and error:interceptor:post:

api.on('error:interceptor:pre', (error, config, interceptorName) => {
    // deal with the error
});

api.on('error:interceptor:post', (error, config, interceptorName) => {
    // deal with the error
});

api.on('request:interceptor:pre', (config, interceptorName) => {
    // deal with the request
});

api.on('request:interceptor:post', (config, interceptorName) => {
    // deal with the request
});

api.on('response:interceptor:pre', (response, config, interceptorName) => {
    // deal with the response
});

api.on('response:interceptor:post', (response, config, interceptorName) => {
    // deal with the response
});

You can also use once method to add a one shot event listener.

Development

Install dependencies:

make install

Development Build

To rebuild the JavaScript you must run: make build-dev.

During development you can run make watch to trigger a build at each change.

Production build

To build for production (minified files) you must run: make build.

ES5 build

To build the ES5 files you must run: make es5.

Tests

make test

Contributing

All contributions are welcome and must pass the tests. If you add a new feature, please write tests for it.

License

This application is available under the MIT License, courtesy of marmelab.

More Repositories

1

react-admin

A frontend Framework for building B2B applications running in the browser on top of REST/GraphQL APIs, using ES6, React and Material Design
TypeScript
22,823
star
2

gremlins.js

Monkey testing library for web apps and Node.js
JavaScript
8,971
star
3

ng-admin

Add an AngularJS admin GUI to any RESTful API
JavaScript
3,968
star
4

awesome-rest

A collaborative list of great resources about RESTful API architecture, development, test, and performance
3,457
star
5

json-graphql-server

Get a full fake GraphQL API with zero coding in less than 30 seconds.
JavaScript
1,930
star
6

universal.css

The only CSS you will ever need
CSS
1,260
star
7

EventDrops

A time based / event series interactive visualization using d3.js
JavaScript
1,236
star
8

gaudi

Gaudi allows to share multi-component applications, based on Docker, Go, and YAML.
Go
566
star
9

ng-admin-react

Add a ReactJS admin GUI to any RESTful API. Deprecated: see admin-on-rest for a full rewrite
JavaScript
544
star
10

FakeRest

Patch fetch/XMLHttpRequest to fake a REST API server in the browser, based on JSON data.
JavaScript
407
star
11

admin-on-rest

A frontend framework for building admin SPAs on top of REST services, using React and Material Design.
JavaScript
400
star
12

admin-on-rest-demo

Source of the admin-on-rest react.js demo, using a dummy REST service powered by FakeRest
JavaScript
329
star
13

ng-admin-demo

Source of the ng-admin angular.js demo, using a dummy REST service powered by FakeRest
JavaScript
305
star
14

sedy

A GitHub bot bringing the sed command to code reviews
JavaScript
266
star
15

javascript-boilerplate

Node.js+Koa.js+PostgreSQL+React.js+Webpack+Mocha+Makefile, a starter kit for new apps
JavaScript
253
star
16

ArchitectureTree

Draw and share your software architecture without diagramming software. Uses d3.js and Angular.js.
JavaScript
218
star
17

comfygure

Encrypted and versioned configuration store built with collaboration in mind
JavaScript
192
star
18

microrest.php

A micro web application providing a REST API on top of any relational database, using Silex and Doctrine DBAL
PHP
186
star
19

graphql-schema-from-json

Guess a GraphQL schema from json data
JavaScript
183
star
20

tree.js

Tree.js is a JavaScript library to build and manipulate hookable trees.
JavaScript
148
star
21

ra-supabase

Supabase adapter for react-admin, the frontend framework for building admin applications on top of REST/GraphQL services.
TypeScript
144
star
22

greenframe-cli

Estimate the carbon footprint of a user scenario on a web application
TypeScript
137
star
23

atomic-crm

A full-featured CRM built with React, react-admin, and Supabase.
TypeScript
113
star
24

ng-admin-postgrest

Demo of an integration between ng-admin and PostgREST
JavaScript
111
star
25

phpcr-browser

Web interface for browsing PHPCR repositories, using Silex and AngularJS
CSS
103
star
26

sketch-by-phone

A proof-of-concept of Augmented Reality with HTML5
JavaScript
96
star
27

ArcheoloGit

Where should you focus the maintenance efforts? ArcheoloGit is a visualization of age and dev activity for software, powered by d3.js.
JavaScript
95
star
28

phpunit-d3-report

Visualize the slowest parts of a PHPUnit testsuite using d3.js
JavaScript
93
star
29

GraphQL-example

An example code structure for a GraphQL-powered mobile app. Contains client and server code.
JavaScript
86
star
30

make-docker-command

Seamlessly execute commands (composer, bower, compass) in isolation using docker and make.
Makefile
83
star
31

aor-graphql

Packages related to using GraphQL with Admin-on-rest
JavaScript
81
star
32

react-admin-demo

Source of the react-admin react.js demo, using a dummy REST service powered by FakeRest
67
star
33

ra-auth-acl

Access Control List authProvider and helpers for React Admin
TypeScript
64
star
34

aor-dependent-input

A component for displaying input depending on other inputs values in Admin-on-rest
JavaScript
60
star
35

argos

docker monitoring experiment
58
star
36

react-md-motion

Material design motions with react
JavaScript
54
star
37

Raphael.InlineTextEditing

Raphael Plugin allowing inline edition of SVG text elements
JavaScript
54
star
38

ra-example-oauth

An example of OpenID Connect implementation on React Admin
TypeScript
53
star
39

aor-simple-graphql-client

A simple GraphQL client for admin-on-rest
JavaScript
48
star
40

ZeroDollarHomePage

A decentralized ad server running on the blockchain
JavaScript
45
star
41

SonataElasticaBundle

Power the Sonata Admin list view and filters by an ElasticSearch index to speed up navigation.
PHP
43
star
42

aor-permissions

A component for Admin-on-rest allowing to switch views depending on user permissions. Eg: having different PostEdit components for different users
JavaScript
42
star
43

react-admin-crm

A CRM build with react-admin, used as a demo for the capabilities of the framework
HTML
40
star
44

ra-in-memory-jwt

Manage React-admin authentication with jwt in memory, not in local storage
JavaScript
39
star
45

koa-multifetch

A Koa.js middleware for performing internal batch requests
JavaScript
36
star
46

gollabedit

Experimental collaborative editor written in Go
Go
33
star
47

admin-config

Configuration API to describe an administration interface. Used by ng-admin and react-admin.
JavaScript
31
star
48

ocaml-invader

Ocaml Space-Invader implementation using OpenGL
OCaml
29
star
49

admin-on-rest-graphql-demo

JavaScript
29
star
50

ra-data-google-sheets

A data provider for react-admin, based on Google Sheets
JavaScript
26
star
51

ra-datagrid

Integration of Material-ui's <Datagrid> into react-admin
TypeScript
26
star
52

battery-friendly-timer

Mobile applications using setInterval to poll a server are a battery hogs. Save battery life by fetching data at the right moment.
JavaScript
25
star
53

MobileInsight

A Mobile web app to browse PHP code analyses made by SensioLabsInsight, built with Angular.js and Ionic.
JavaScript
25
star
54

yolo

Typo-tolerant runtime object proxy for fast JavaScritp typers
JavaScript
24
star
55

aor-rich-text-input

<RichTextInput> component for admin-on-rest, useful for editing HTML code in admin GUIs
CSS
23
star
56

timeline-react-admin

Support for a tutorial about custom List views with react-admin
JavaScript
23
star
57

strapi-beerdex

StrapiJS Example Application For Beer Management
JavaScript
23
star
58

chrome-bug-report-wizard

Chrome plugin automating Bug Tracker issue creation with screenshot and browser details
JavaScript
23
star
59

highlight-search-term

Highlight search term in a page. Vanilla JS, compatible with frontend frameworks (React, Vite, Angular, etc).
JavaScript
22
star
60

ra-enterprise-demo

TypeScript
20
star
61

solid-admin

TypeScript
20
star
62

argos-cli

19
star
63

aor-realtime

JavaScript
17
star
64

svelte-sse-chat

Chat Example Application Using SvelteJS and Chat
Svelte
15
star
65

uptime

A prototype of website monitoring tool, written in Go and React.js, modeled after fzaninotto/uptime
JavaScript
15
star
66

reactive-beers

Reactive Beers is an example application using CouchDB and PouchDB
JavaScript
15
star
67

reversi-reason

🐪 ReasonML implementation of Reversi Game
OCaml
13
star
68

MobileAudience

Mobile Webapp mixing D3.js with a touch UI ; shows TV audiences and market shares for 8 fictive TV channels across several days.
JavaScript
13
star
69

curator-ai

An AI-powered news curator. It reads a list of articles, selects the best ones depending on a list of interests, and summarizes them into an easy-to-read news feed. Powered by the OpenAI API.
TypeScript
13
star
70

ng-tree

An Angular.js module for using tree.js
JavaScript
12
star
71

docker-parallel-phpunit-demo

How to use Docker to run PHPUnit tests in parallel
PHP
12
star
72

skelt

{ } Skelt is a simple templating engine for object literals.
JavaScript
12
star
73

redux-form-inspector

An HOC for computing dynamic props from values inside an existing redux-form component.
JavaScript
12
star
74

virothello

💫 Othello Game Using Augmented Reality And Viro
JavaScript
12
star
75

coPostgresQuery

Query builder for PostgreSQL in Node.js, built for async
JavaScript
11
star
76

phpcr-api

PHP
11
star
77

ra-keycloak

TypeScript
11
star
78

svg_to_png

Convert an SVG file to a PNG image. Uses headless Chrome for rendering.
JavaScript
11
star
79

aor-json-rest-client

A local REST client for admin-on-rest
JavaScript
10
star
80

docker-compass

Dockerfile
10
star
81

dobble

Generate a valid deck of cards for Dobble in ECMAScript6
JavaScript
10
star
82

ra-sqlite-dataprovider

POC of a dataprovider using a sqlite database hosted on a static server
JavaScript
9
star
83

checkoid

Experimental validator library allowing to combine validator like you would lego piece.
TypeScript
9
star
84

gql-profiler

A standalone performance profiler for GraphQL resolvers
JavaScript
9
star
85

liMonade

A Monad library to make Monad simple.
TypeScript
9
star
86

dedale

A wood labyrinth game in the browser
JavaScript
9
star
87

silex-multifetch

A Silex provider for performing internal batch requests
PHP
9
star
88

treedu

Graphical Disk Usage command for the terminal, using Node.js, d3.js, blessed, and Drawille
JavaScript
9
star
89

ra-shadcn-demo

An example showing how to use react-admin in headless mode with shadcn
TypeScript
9
star
90

ra-auth-cognito

An auth provider for react-admin which handles authentication with AWS Cognito.
TypeScript
9
star
91

ra-richtext-tiptap

TypeScript
8
star
92

ra-strapi-demo

JavaScript
8
star
93

ra-example-kanban

Example of a Kanban board built with React Admin
TypeScript
8
star
94

docker-composer-hhvm

8
star
95

Asteroids.js

A one day experiment to bringing the Asteroids game to the browser, using a mobile device as controller, Node.js, Raphaël, and socket.io.
JavaScript
8
star
96

docker-bower

Dockerfile
8
star
97

ra-tailwind-demo

An example showing how to use react-admin in headless mode with tailwind
TypeScript
8
star
98

web-myna

Record then emulate your api.s for testing and development
JavaScript
7
star
99

puppeteer-accessibility

JavaScript
7
star
100

ninja-coder

Code with your entire body like a Ninja
JavaScript
7
star