Building a Simple RESTful API with Node, SailsJS, and MongoDB

Representational State Transfer (REST) can be thought of as a system design approach that allows for a standardized communication across the Internet. It’s the way we represent and identify resources over the Internet.

There are several things that qualify a system as RESTful:

  • Statelessness – every request is treated as independent and new. The server has no session or knowledge of context between request. For example, it doesn’t care that you were previously logged in or authenticated.
  • Constant and Standard URL for requesting a resource – simply put, we always use one endpoint to get a resource. For example, a GET request to /product/1 should be used to always get a product 1.

Requirements

Before getting on with creating the API, we need the following:

  • NodeJS
  • MongoDB
  • SailsJS – Web framework that helps you develop an API rapidly. It is particularly formidable because of its Waterline ORM which offers abstraction from the databases allowing you to write queries without any vendor-specific integration code.

Getting Started

At this point, we need to install the sails package and sails-mongo extension.

Create a new folder and navigate to the folder.

npm install sails -g

npm install sails-mongo --save
sails new test-api

Sails will offer you a chance to choose a Web App or an empty project as a template. For the purpose of this project, we a sticking with an empty project.

Once the installation is complete, the project folder structure should look like this:

Next up we are going to design a simple product API that returns products attributes from a database via a specified URL pattern. To do that we generate a model and a controller for the products.

sails generate model product

sails generate controller product

You see api/models/Product.js and api/controllers/ProductController.js in your project.

Specify the attributes below in api/models/Product.js

...
  name: {
    type: 'string'
  },
  productCode: {
    type: 'string'
  },
  description: {
    type: 'string'
  },
  color: {
    type: 'string'
  }
...

Add function to handle incoming request from the browser in api/models/ProductController.js

module.exports = {
    getProduct: async (req, res) => {
        if(req.params.productCode){
            let products = await Product.find({productCode: req.params.productCode});
            if(products.length > 0 ){
                return res.send(products[0]);
            }
        }
        return res.badRequest(`product ${req.params.productCode} not found`);
    }
};

Next, we specify the route in config/routes.js

'/product/:productCode': { controller: 'ProductController', action: 'getProduct' }

We have a bit of configuration to do.

  • Open config/datastores.js and set the adapter to sails-mongo and the url attribute to your connection URL. It could look like mongodb://<user>@<password>:<host>:27017/simpleapi. For other connection configurations go to salis-config-datastores.
  • Open config/models.js and set migrate to alter. This enables Auto-migration allowing the database structure to be updated automatically while we are in development (see migration for more).

Let’s add some data to the database so we have something to display via the terminal.

    mongo
    use simpleapi
    db.Product.insert({ createdAt: 1557664059284, updatedAt: 1557664059284,  name: 'Earth, wind and fire', productCode: '123456', description: 'Ethereal and wonderful', color: 'cherry' })	

Execute NODE_ENV=development node app.js to start the application.

  • Visit the URL http://localhost:1337/product/123456. It should returns:
{
    "productCode": "123456",
    "createdAt": 1557664059284,
    "updatedAt": 1557664059284,
    "id": ".....",
    "name": "Earth, wind and fire",
    "description": "Ethereal and wonderful",
    "color": "cherry"
}    
  • Visit the URL http://localhost:1337/product/anything. It should returns:
"product anything not found

This is a simple example but hopefully it provides a starting point, so carry on exploring . With SailsJS, it’s pretty easy to build APIs.
If you find other design APIs feel free to share it in the comments section. All feedback is welcome!

1
0

Related Posts