rest-api

Fast & lightweight RESTful API framework in Node.js

node-rest-api

Fast & lightweight RESTful API framework in Node.js. It's built on top of connect.

Do not use it for production, yet! Its still under heavy development!

Put all your routes and controller logics somewhere and let the framework do the rest.

controllers/user.js

module.exports = {
  
  'GET /user/:id':
  function($id) {
    // return user with id 
    $.render({id: id, name: 'fake user'});
  },
  
  'POST /user':
  function($) {
    // create a new user with data from $.params 
    $.error(501, 'oh, that went wrong?!');
  }
 
  // ... all your other awesome stuff 
}

index.js

var API = require('rest-api'); 
var api = new API();
api.start();

Terminal

curl -X GET http://127.0.0.1:8080/user/123 -> {id: 123, name: 'fake user'}
curl -X POST http://127.0.0.1:8080/user -> http status 501

@TODO

@TODO

You can easily extend the API flow with hooks. Need authorization?

api.beforeFunctionCall('AUTH', function(apireqresnext){
  if(req.api.params.user == 'fake.user' && req.api.params.password == 'random password') {
    next(); // cool, you are logged in! 
  } else {
    throw new ClientError({status: 403, message: 'invalid login'}); // :-( 
  }
});

Add the AUTH flag to your route in controllers/user.js

module.exports = {
  'GET AUTH /user/:id':
  function($id) {
    // i am safe 
    $.render({id: id, name: 'fake user'});
  }
}

Possible hooks include: beforeFunctionCall([flag,] func), beforeRender([flag,] func) and beforeResponse([flag,] func). Calling without a flag will trigger the hook for every route. You can use as many flags in your route as you want.

@TODO

@TODO

@TODO

The framework never crashes as long as you throw errors correctly.

like controllers/user.js from above

  • return $.error(404, 'i cant find it');
  • return $.internalError('note for internal error logs');
  • return $.internalError(new Error('pass errors directly'));
  • prepend return to stop execution in your controller!
  • you can crash the app intentionally with something like this in your controller throw new Error('crash')
  • throw new ClientError({status: 404, message: 'i cant find it'});
  • throw new Error('note for internal error logs');

Valid http status codes can be found here http://www.iana.org/assignments/http-status-codes/http-status-codes.xml

The framework will through 500 http codes and 404s if no route was found during routing process. Anything else is up to your own controllers.

@TODO

@TODO

@TODO

  • http-console (https://github.com/cloudhead/http-console)

MIT License