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?

Sails is one of the most popular MVC framework used to build NodeJS apps. And for those who are from Ruby on Rails background will find SailsJS easy to use because of the directory structure is similar as any Rails app. Sails can be used to create Rest API’s, chat application, multiplayer games. etc. and many more. Just like Rails, it help to reduce boilerplate code.

Features

and much more.

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

Installation

First all you need to install NodeJS on your machine.

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

npm install sails -g

Creating API

Now lets create a Sails application

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.

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 !!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store