Sequelize-restful: Build a REST API in seconds

On my previous tutorial I give you some instructions to build an API using Node.js and Express. However, if you really want a RESTful API with the standard methods and routes, you can forget to configure manually Express. The magic cames from here: sequelize-restful.

Sequelize-restful is an incredibly awesome module that allows you to create the API routing from the scratch in just SECONDS. Let me show you how it works.

  1. In my previous tutorial I only had a “users” table in the database. However, now I’m gonna add a “projects” table to show you the truly potential of this module. These two tables, as you can imagine, are related with a foreign key. Use this SQL script to create the table:
    SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
    SET time_zone = "+00:00";
    
    CREATE DATABASE `test` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;
    USE `test`;
    
    
    CREATE TABLE IF NOT EXISTS `projects` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `name` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
      `user_id` int(11) NOT NULL,
      PRIMARY KEY (`id`),
      KEY `id` (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
    
    
    CREATE TABLE IF NOT EXISTS `users` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `name` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
      `password` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
      PRIMARY KEY (`id`),
      UNIQUE KEY `id` (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
  2. Database ready. Now it’s time to create the package.json file:
    {
      "name": "node-api",
      "main": "server.js",
      "dependencies": {
        "body-parser": "^1.6.3",
        "express": "^4.8.3",
        "mysql": "*",
        "sequelize": "*",
        "sequelize-restful": "*"
      }
    }

    And now execute the line:

    npm install
  3. Finally (yes, finally in three steps), we create the server.js file. At first, we start with the initial definitions and requires of Node.js:
    var express   = require('express')
      , bodyParser = require('body-parser')
      , Sequelize = require('sequelize')
      , http      = require('http')
      , restful   = require('sequelize-restful')
      , sequelize = new Sequelize('test', 'DB_USERNAME', 'DB_PASSWORD', {
                logging: console.log,
                define: {
                    timestamps: false
                }
            })
      , app       = express();
    
    var port = process.env.PORT || 3000;
    app.use(bodyParser());

    Then, we define our models. We only have two of them: Users and Projects. Let’s go!

    var User = sequelize.define('users', {
            name: Sequelize.STRING,
            password: Sequelize.STRING
        }
    );
    
    var Project = sequelize.define('projects', {
            name: Sequelize.STRING
        }
    );

    So simple, right?. Do we have a relationship between models? No problem. Just one line courtesy of Sequelize:

    User.hasMany(Project, {foreignKey: 'user_id' });

    Now, it’s time to configure all the routes for Express… oh wait, no, we won’t do that. Just one simple line of code, this time courtesy of Sequelize-restful:

    app.use(restful(sequelize));

    Routes created! Piece of cake, isn’t it? Now one more line to launch the server:

    app.listen(port);

And that’s all! If you follow the steps, at this point you have a fully functional API RESTful. You can test the following paths:

http://[your IP address]:3000/api/users/
http://[your IP address]:3000/api/users/1
http://[your IP address]:3000/api/projects/
http://[your IP address]:3000/api/projects/1

Or even a more complex path to show the projects of a single user:

http://[your IP address]:3000/api/users/1/projects/

As always, feel free of checking out my code on GitHub.

Good coding!

Leave a Reply

Your email address will not be published. Required fields are marked *