Auto generate REST API using SailsJS

Sails is a lightweight framework that sits on top of Express. Its ensemble of small modules work together to provide simplicity, maintainability, and structural conventions to NodeJS apps.

What is SailsJS?

Features

  • Compatible with MySQL, MongoDB, PostgreSQL, Redis etc.
  • Auto-generate REST API
  • Support Web sockets
  • Follows convention over configuration policy

and much more.

We can create REST API using simple commands in few minutes. Let see how it can be done.

Installation

You can then install stable version of Sails using following command:

npm install sails -g

Creating API

sails new test_app

You should see following message in your console after the app is created successfully:

info: Created a new Sails app `test_app`!

Now move to the app directory.

cd test_app/

and start Sails server with following command

sails lift

If everything goes right you will see following screen.

Sails app logs snapshot!

It uses port no 1337 as the default port.

Visit http://localhost:1337 in your browser to see the home page of your sails app.

Now, lets create simple REST API for User model with attributes name and email.

Run the following command in your console

sails generate api users name email

This will create API with REST actions. Now when you start the server, you will have three options to choose(see attached).

Choose 2 (i.e the alter option) and press enter. Now the REST API is ready to use! So easy!

Following are the routes which we can use. It deals with JSON data.

  • GET /users
  • GET /users/:id
  • POST /users
  • PUT /users/:id
  • DELETE /users/:id

I would recommend to use Postman to test the API. Following screenshot shows how to send request to create a user by using the API.

Now you can use this API anywhere you want!

You can find an introduction to SailsJS and some features in the following video.

That’s it! Thanks for reading!

References

Ruby On Rails Developer, JavaScript Lead, Quick Learner, Reader, Writer, Always in Mood !!