Generating REST API With Sails JS - Part 2

Jul 26, 2014


Hi ,

This is the second part of building a realtime web application with Sails and Angular. The concept of REST API is important here. You can read more about REST API and RESTFUL web services here.

UPDATE (25-OCT-2015) : I’ve updated the article including the testing of Sails CRUD APIs (GET,POST,PUT,DELETE methods).

How to generate a REST API with Sails JS ?

As i said earlier Sails is a rapid prototyping platform , API generation is faster and easier in Sails .

sails generate api employee

SailsAngularTutorialPart2-1

This generate an API which can search, paginate, sort, filter, create, destroy, update, and associate employees. API is available at http://localhost:1337/employee .

Let us to look into the details of what is happened here when we execute this command. Sails actually generates a new Model “Employee” (file located in app/api/models/Employee.js) and a Controller file “EmployeeContoller” ( located in app/api/controllers/EmployeeController.js). File structure is shown below.

SailsAngularTutorialPart2-2

The contents of Model file generated is shown below .

/**
* Employee.js
*
* @description :: TODO: You might write a short summary of how this model works and what it represents here.
* @docs        :: http://sailsjs.org/#!documentation/models
*/

module.exports = {

  attributes: {

  }
};

Models may be accessed from our controllers, policies, services, responses, tests, and in custom model methods. There are many built-in methods available on models, the most important of which are the query methods: find, create, update, and destroy.

The data-type in Sailscan any one of the following listed below. It can a string,text, int, float, date, datetime, boolean, binary, array, json.The available validations are empty, required, notEmpty, undefined, string, alpha, numeric, alphanumeric, email, url, urlish, ip, ipv4, ipv6, creditcard, uuid, uuidv3, uuidv4, int, integer, number, finite, decimal, float, falsey, truthy, null, notNull, boolean, array, date, hexadecimal, hexColor, lowercase, uppercase, after, before, is, regex, not, notRegex, equals, contains, notContains, len, in, notIn, max, min, minLength, maxLength

So we will now create a simple Model Employee which contains three attibutes , name : STRING , empnum : INTEGER , emailid : EMAIL.

/**
* Employee.js
*
* @description :: TODO: You might write a short summary of how this model works and what it represents here.
* @docs        :: http://sailsjs.org/#!documentation/models
*/

module.exports = {

  attributes: {
      
      name:{
        type:"string", 
        required:true,
        minLength: 2
      },
      empnum:{
        type:"string",
        required:true,
        unique: true
      },
      email:{
        type:"email",
        required:true,
        unique: true
      }
      
  }
};

This defines an employee Model . Let us start inserting values into it . In development mode, Sails gives us flexibility to have auto-generated APIs. You can insert values as

http://localhost:1337/employee/create?name=Pranav&empnum=123&email=pranavrajs@gmail.com

You will get a screen like this.

SailsAngularTutorialPart2-3

You may try adding more employees here.

Testing REST API

Sails gives you standard REST API (GET, POST, PUT, DELETE) functions while you execute generate command. These APIs are autogenerated and you may not worry about the code for these APIs. We can test these APIs now.

I’m using POSTMAN - a Chrome extension to test/document the APIs.

GET: GET request gives you all previous records. If specified with an id, it gives you an id specific record.

SailsAngularTutorialPart2-11

POST: POST request creates an new record with given parameters.

SailsAngularTutorialPart2-12

PUT: PUT request updates the record with given id. Here we’ve given an id 2. This updates the record with id 2 replacing old name with new name.

SailsAngularTutorialPart2-13

DELETE: DELETE request delete the record with given id.

SailsAngularTutorialPart2-14

The above APIs are generated during the sails generate api command. We don’t need to worry about the CRUD operations as Sails would take care of that. We will now try to create an new API which returns an employee by providing the employee number. Let us look into EmployeeController.js file now.

/**
 * EmployeeController
 *
 * @description :: Server-side logic for managing employees
 * @help        :: See http://links.sailsjs.org/docs/controllers
 */

module.exports = {
  
};

File will be as shown as above. If we want to write an API say employee/findEmployeebyempnum , we just have to write a function inside Employee Controller namely findEmployeebyempnum. We will try one example.

/**
 * EmployeeCont findEmployeebyEmpnum as above . req corresponds to request and res corresponds to response. req.param gives the parameters passed in request here we take id as parameter(This is to be noted since iroller
 *
 * @description :: Server-side logic for managing employees
 * @help        :: See http://links.sailsjs.org/docs/controllers
 */

module.exports = {

    findEmployeebyEmpnum: function(req, res) {
        var id = req.param('id');
        Employee.findOne({ empnum: id })
            .exec(function(err, user) {
                if (err) {
                    return res.json({
                        error: err
                    });
                }
                if (user === undefined) {
                    return res.notFound();
                } else
                    return res.json({
                        notFound: false,
                        userData: user
                    });
            });
    }
};

Write a function findEmployeebyEmpnum as above . req corresponds to request and res corresponds to response. req.param gives the parameters passed in request here we take id as parameter (This is to be noted since it is the default name during api calls). findOne is a function available by default . One important thing to note is that you can access a model with its name in any controller. Here we check if any error is occured and then API returns error data,otherwise it checks whether the data obtained during querying contains user. This is achieved by checking user with undefined.If no user is found, API returns a JSON with notFound set to true, otherwise it returns a JSON with notFound set to false and defined userData

Let us try the first API we wrote :)

Check with the employee num 123

SailsAngularTutorialPart2-5

Check with some other value

SailsAngularTutorialPart2-4

Hey !!! It works :) . We will try using these APIs with Angular JS in front-end to build a reatime app in next tutorials . See you there , bye :)