Building REST API using Node/Express and Sequelize
Tags: showdev, webdev, tutorial, beginners
Published: 2019-08-30 18:49:53

---
title: Building REST API using Node/Express and Sequelize
published: true
description: Building REST API using Node/Express and Sequelize
tags: showdev,webdev,tutorial,beginners
canonical_url : https://cloudnweb.dev/2019/08/building-rest-api-using-node-express-and-sequelize/
---
<!-- wp:paragraph -->
<p>In this article, we will see how to build a REST API using Node/Express and Sequelize. Building REST API using Node/Express and Sequelize.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Recent Article on Node.js</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><a href="https://cloudnweb.dev/2019/08/understanding-eventemitter-in-node-js-with-a-usecase/">Understanding Event Emitter in Node.js</a></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><a href="https://cloudnweb.dev/2019/08/apache-kafka-for-node-js-developers/">Apache Kafka for Node.js Developers</a></p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Setup</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>we will be using Postgres database for this tutorial along with Sequelize. Sequelize is an ORM for Node.js and Relational databases such as MySQL,MSSQL,Postgres and SQLite.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Firstly, postgres and Node.js needs to be installed in your machine. Follow this instruction to install <a href="https://www.postgresql.org/download/">postgres</a>  and <a href="https://nodejs.org/en/download/">node.js</a> on your machine.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Once postgres is installed, Start postgres server and you will see a dashboard like following</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":1291} -->
<figure class="wp-block-image"><img src="https://cloudnweb.dev/wp-content/uploads/2019/08/Screenshot-2019-08-30-at-10.44.10-PM-1024x346.png" alt="" class="wp-image-1291"/></figure>
<!-- /wp:image -->

<!-- wp:heading {"level":3} -->
<h3>Sequelize Setup</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>create a folder called <strong>node-sequelize</strong> and install <strong>express</strong> with the following command.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>npm init --yes
npm install express body-parser </code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>After that, Install <strong>Sequelize</strong> and <strong>postgres</strong> with the following command.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>npm install sequelize sequelize-cli pg pg-hstore</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p><strong>sequelize-cli</strong> can be installed in two ways. one is globally and another one is locally to the project. Here, we install locally to the project.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Initialize the Sequelize using the following command</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>node_modules/.bin/sequelize init</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Since, we installed sequelize locally to the project, we need to refer by using <strong>node_modules/.bin/sequelize</strong></p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":1294} -->
<figure class="wp-block-image"><img src="https://cloudnweb.dev/wp-content/uploads/2019/08/Screenshot-2019-08-29-at-9.28.30-PM.png" alt="" class="wp-image-1294"/></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>Above command will create a bunch of folders such as <strong>config</strong>,<strong>migrations</strong> and <strong>models</strong></p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":1290} -->
<figure class="wp-block-image"><img src="https://cloudnweb.dev/wp-content/uploads/2019/08/Screenshot-2019-08-29-at-11.27.43-PM.png" alt="" class="wp-image-1290"/></figure>
<!-- /wp:image -->

<!-- wp:list -->
<ul><li><strong>config</strong> - config contains the <strong>config.json</strong> which is a database configuration.</li><li><strong>migrations</strong> - it contains the migrations file which create tables in the database.</li><li><strong>models</strong> -  models are Schema which maps with the DB Table.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3>Setting up Postgres in Sequelize</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>config.json will contain three environments such as <strong>development</strong>,<strong>test</strong> and <strong>production</strong>. Change the <strong>config.json</strong> to postgres database in development environment</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>"development": {
    "username": "postgres",
    "password": null
    "database": "testdb",
    "host": "127.0.0.1",
    "port" : 5432,
    "dialect": "postgres"
  }</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>In models folder, create files such as <strong>post.js</strong> and <strong>user.js</strong> and add the following code.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>//POST Schema
module.exports = (sequelize,DataTypes) => {
    let Post = sequelize.define('Post',{
        title : DataTypes.STRING
    });

    Post.associate = function (models) {
        Post.belongsTo(models.User,{
            onDelete : "CASCADE",
            foreignKey : 'userId'
        });
    };

    return Post;
}</code></pre>
<!-- /wp:code -->

<!-- wp:code -->
<pre class="wp-block-code"><code>//USER Schema
module.exports = (sequelize,DataTypes) => {
    let User = sequelize.define('User',{
        email : DataTypes.STRING
    });

    User.associate = function(models) {
        User.hasMany(models.Post,{
            foreignKey : 'userId',
            as : 'posts'
        });
    };
    return User;
}</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>import this files in the <strong>model</strong> <strong>index.js</strong></p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Sequelize Postgres Association</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>consider a scenario , where user will have lots of posts and a post will belongs to user. In technical terms of database design, it is called as relationships. there are three types of relationship between two entities.they are,</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li><strong>One to One Relationship</strong>  -  For Example, User and Address are one to one relationships. User will have one address and an adress belongs to an user.</li><li><strong>One to Many Relationship</strong> - For Example, customer will have many orders, an order belongs to a customer </li><li><strong>Many to Many Relationship</strong> - Example : Author will publish many books, a book can have multiple authors.</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>To implement this concepts, we have Assocation in postgres sequelize. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Once you create a <strong>models</strong>, create files in <strong>migrations</strong> to  create tables in database.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>//auser-migration.js
module.exports = {
    up: (queryInterface, Sequelize) =>
      queryInterface.createTable('Users', {
        id: {
          allowNull: false,
          autoIncrement: true,
          primaryKey: true,
          type: Sequelize.INTEGER,
        },
        email: {
          type: Sequelize.STRING,
          allowNull: false,
        },
        createdAt: {
          allowNull: false,
          type: Sequelize.DATE,
        },
        updatedAt: {
          allowNull: false,
          type: Sequelize.DATE,
        },
      }),
    down: (queryInterface /* , Sequelize */) => queryInterface.dropTable('Users'),
  };</code></pre>
<!-- /wp:code -->

<!-- wp:code -->
<pre class="wp-block-code"><code>//create-post.js
module.exports = {
    up: (queryInterface, Sequelize) =>
      queryInterface.createTable('Posts', {
        id: {
          allowNull: false,
          autoIncrement: true,
          primaryKey: true,
          type: Sequelize.INTEGER,
        },
        title: {
          type: Sequelize.STRING,
          allowNull: false,
        },
        userId : {
            type : Sequelize.INTEGER,
            onDelete : 'CASCADE',
            references : {
                model : 'Users',
                key : 'id',
                as : 'userId'
            },
        },
        createdAt: {
          allowNull: false,
          type: Sequelize.DATE,
        },
        updatedAt: {
          allowNull: false,
          type: Sequelize.DATE,
        },
      }),
    down: (queryInterface /* , Sequelize */) => queryInterface.dropTable('Posts'),
  };</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Run the following command to migrate the tables to database</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>node_modules/.bin/sequelize db:migrate</code></pre>
<!-- /wp:code -->

<!-- wp:image {"id":1293} -->
<figure class="wp-block-image"><img src="https://cloudnweb.dev/wp-content/uploads/2019/08/Screenshot-2019-08-29-at-11.25.28-PM.png" alt="" class="wp-image-1293"/></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>As a result,it will create tables in postgres database.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>API Design</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Firstly, create a folder called <strong>controller</strong>. In controller, create files <strong>user.js</strong> and <strong>post.js </strong>. basically, we are going to write API to create User and Post.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>//user.js
const User = require('../models').User;
module.exports = {

    async getAllUsers(req,res) {

        try {

            const userCollection = await User.find({});

            res.status(201).send(userCollection);

        }
        catch(e){
            console.log(e);

            res.status(500).send(e);
        }

    },

    async create(req,res) {
        try {
            const userCollection = await User
            .create({
                email : req.body.email,
            });

            res.status(201).send(userCollection);
        }
        catch(e){
            console.log(e);
            res.status(400).send(e);
        }
                    
    },

    async update(req,res) {

        try{
            const userCollection = await User.find({
                id : req.params.userId
            });

            if(userCollection){

                const updatedUser = await User.update({
                    id : req.body.email
                });

                res.status(201).send(updatedUser)

            }
            else{

                res.status(404).send("User Not Found");
            }

        }
        catch(e){
            console.log(e);

            res.status(500).send(e);

        }
    } 
}</code></pre>
<!-- /wp:code -->

<!-- wp:code -->
<pre class="wp-block-code"><code>//post.js
const Post = require('../models').Post;
const User = require('../models').User;

module.exports = {

    async getAllPostsOfUser(req,res) {
        try {
            const userCollection = await User.find({
                id : req.params.userId
            });

            if(userCollection){
                const postCollection = await Post.find({
                    userId : req.params.userId
                })

                res.status(201).send(postCollection);
            }
            else{
                re.status(404).send("User Not Found")
            }
        }
        catch(e){
            console.log(e);
            res.status(500).send(e);
        }

    },

    async createPost(req,res) {

        try {
            const post = await Post.create({
                title : req.body.title,
                userId : req.body.userId
            });
            res.status(201).send(post)
        }
        catch(e){
            console.log(e);
            res.status(400).send(e);
        }
    },

    async update(req,res) {
        try{
            const postCollection = await Post.find({
                id : req.params.postId
            });

            if(postCollection){
                const updatedPost = await postCollection.update({
                    title : req.body.title
                })

                res.status(201).send(updatedPost);
            }
            else{
                res.status(404).send("Post Not Found");
            }

        }
        catch(e){
            console.log(e);
            res.status(400).send(e);
        }

    }
}</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>In addition,import <strong>post.js</strong> and <strong>user.js</strong> in the controller <strong>index</strong> file.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>create a folder called <strong>router</strong> and add the following code in <strong>index.js</strong></p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>//index.js
const userController = require('../controller').user;
const postController = require('../controller').post;
module.exports = (app) => {

    app.get('/api',(req,res) => {
        res.status(200).send({
            data : "Welcome Node Sequlize API v1"
        })
    })

    app.get('/api/users',userController.getAllUsers);

    app.post('/api/user/create',userController.create);

    app.put('/api/user/:userId',userController.update);

    app.get('/api/:userId/posts',postController.getAllPostsOfUser);

    app.post('/api/post/create',postController.createPost);

    app.put('/api/:postId',postController.update);

}</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Finally, <strong>index.js</strong> file will look like</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>const express = require('express');
const bodyParser = require('body-parser');
const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended : false}));

require('./server/routes')(app);

const PORT = 3456;
app.listen(PORT,() => {
    console.log(`Server is listening to port ${PORT}`)
})</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Run the Application using the command </p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>node index.js</code></pre>
<!-- /wp:code -->

<!-- wp:image {"id":1299} -->
<figure class="wp-block-image"><img src="https://cloudnweb.dev/wp-content/uploads/2019/08/Screenshot-2019-08-29-at-11.10.00-PM-1024x629.png" alt="" class="wp-image-1299"/></figure>
<!-- /wp:image -->

<!-- wp:image {"id":1300} -->
<figure class="wp-block-image"><img src="https://cloudnweb.dev/wp-content/uploads/2019/08/Screenshot-2019-08-29-at-11.15.09-PM-1024x583.png" alt="" class="wp-image-1300"/></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>Complete Source can be found <a href="https://github.com/ganeshmani/node-sequelize-tutorial">here</a></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>To sum up, we can  Build REST API in  Node/Express Application using Sequelize for Postgres database.</p>
<!-- /wp:paragraph -->