rest-sugar

0.6.3 • Public • Published

rest-sugar - Makes it easy to write yummy REST APIs

The whole point of this library is to make it easy to implement simple yet powerful REST APIs. There are a few extension points you can hook into. mongoose-sugar complements this particular library very well. It is possible to implement similar solutions for other backends too as long as you stick to the sugar-spec.

Even though the library has been designed based on Express, it might be possible to make it work with other similar libraries too given they use Express conventions. This might take some kind of an adapter.

Basic Schema

The following urls contain a prefix given at init.

  • GET /? (ie. /api/v1) -> API metadata (ie. schema and help)
  • GET /<api> -> Get all
  • GET /<api>?name=foobar -> Get all with the matching name
  • GET /<api>?limit=25&offset=50 -> Get with pagination
  • GET /<api>/count -> Get count
  • GET /<api>?fields=name,color -> Get name and color fields only
  • POST /<api>?name=foobar -> Create new item with the given name
  • PUT /<api> -> Disallowed, gives 403 error
  • DELETE /<api> -> Disallowed, gives 403 error

Note that it is possible to mix and match various GETs above. The following urls operate on a specific resource (ie. /<api>/<id>).

  • GET /<api>/<id> -> Get resource matching to the id
  • POST /<api>/<id> -> Disallowed, gives 403 error
  • PUT /<api>/<id>?name=joe -> Updates the content of the given resource with the given field data
  • DELETE /<api>/<id> -> Deletes the given resource. Returns an empty structure if successful.

Middleware

In case you want to use some authentication method (preferable!) or customize the behavior further, consider using middlewares. You may attach both pre and post middleware handlers. pre ones are performed before an actual database query performed whereas post ones are after. The basic syntax resembles Express. See the example below:

...
 
var api = rest(app, '/api/v1', {
    authors: models.Author
}, sugar);
 
api.pre(function() {
    api.use(rest.only('GET'));
    api.use(rest.keyAuth({name: 'apikey', value: 'secret'}));
    api.use(function(req, res, next) {
        // do your magic now
 
        next(); // call or else...
    });
});
 
// api.post is identical except the functions get an extra parameter containing
// the data fetched from the database. You may then use that data to trigger
// further actions for instance

Examine the tests included with the project for more complete examples.

Acknowledgments

Inspired by RESTful API Design - Second Edition and django-tastypie.

License

rest-sugar is available under MIT. See LICENSE for more details.

Readme

Keywords

none

Package Sidebar

Install

npm i rest-sugar

Weekly Downloads

11

Version

0.6.3

License

none

Last publish

Collaborators

  • bebraw