Create RESTful API in less than 5 minutes with sailsjs


I will assume that you already install nodejs on your machine since sailsjs build on it, otherwise you should see this link and go to how to install nodejs section.

Install Sailsjs
  1. npm -g install sails, for some cases maybe you will need to use sudo npm -g install sails
  2. Go to your dev folder and type:
    sails new awesomeAPI
  3. and now you already can run test on your api server
    cd awesomeAPI
    sails lift
    since it's still on development you will be asking something like this: choose 1 for this tutorial, then you can access it from your browser using port 1337 (http://localhost:1337)
Create the API

For this tutorial we will create Restful API for access table user and profile which has one to one association.

  1. create controller and model for user and profile
    sails generate api user
    sails generate api profile
    it will automatically create a controller and model for you.
  2. now, we declare what are attributes/columns inside those models, open user model inside api/models/User.jsmodule.exports = { attributes: { username:{ type: 'string' }, email:{ type: 'string' }, password:{ type: 'string' } } }; then, we also add attributes on profile model, since it will one-to-one association so we add userid attribute as a foreignKey of user model
    module.exports = { attributes: { userid:{ model: 'user' }, firstname:{ type: 'string' }, lastname:{ type: 'string' }, gender:{ type: 'string' }, dob:{ type: 'date' }, address:{ type: 'text' } } };
  3. And now we can use our Restful API, run sails lift
    add data user using
    you should json output like so: { username: "cendekiapp", password: "12345", email: "", createdAt: "2015-03-30T13:10:12.300Z", updatedAt: "2015-03-30T13:10:12.300Z", id: 1 } next, we add profile on that data which has id=1
  4. Now you can see your data
    and if you want fetch single data, you can do like so:
  5. if you want to update one of the field in profile table, do it like so:
    this one is for delete

And our restful API is ready to use for developing either web or mobile application.

Next: Add API authentication in SailsJS

Happy Coding...

Cendekia P Putra

< Software Developer /> | @cendekiapp |

Jakarta, Indonesia