yasiru nilan
Jan 5 · 8 min read

I have been creating a NodeJS application recently and I spent a lot of time finding how to create a back-end REST API application. So I thought like it’s better if I could document my findings so that it will be useful for some other people as well.

For my project, I used the ExpressJS framework as the NodeJS framework and used MySQL as the database type. Also, I have used Sequelize as the ORM. So I will discuss the Following in this article.

  1. Creating NodeJS app skeleton using ExpressJS
  2. Using Sequelize to create database and Model Classes
  3. Creating the REST API

Setting up the Project

First, you need to have NodeJs installed on your computer. This article shows how to install NodeJS on Ubuntu Environment.

Then after installing NodeJS, we have to install Express application generator in our machine. You can do that by using the following command.

npm install -g express-generator

This will install express-generator package globally. After installing the package we are ready to generate the app skeleton. To verify the express-generator installation you can run the following command in the terminal.

express -h

it will display something like the following.

Usage: express [options] [dir]Options:--version        output the version number
-e, --ejs add ejs engine support
--pug add pug engine support
--hbs add handlebars engine support
-H, --hogan add hogan.js engine support
-v, --view <engine> add view <engine> support (dust|ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade)
--no-view use static html instead of view engine
-c, --css <engine> add stylesheet <engine> support (less|stylus|compass|sass) (defaults to plain css)
--git add .gitignore
-f, --force force on non-empty directory
-h, --help output usage information

Okay, so express-generator has been installed successfully. Let’s create the app. You can create a new app using the following command.

express --view=pug myapp

Since I’m creating REST API’s I don’t need to worry about view engines. So I have kept it as default(--view=pug). “myapp” is the name of the application.

Now we have to install the dependencies. Go into the project folder and install the dependencies.

cd myapp
npm install

You will have a folder structure like the following.

Folder Structure of the Application

You can start the application using the following command

DEBUG=myapp:* npm start

By default, the express-generator comes with sample models and routes. So the following routes are already defined.

/
/users

If you go to http://127.0.0.1:3000/ or http://127.0.0.1:3000/users from the browser, you can see the responses.

So congratulations. Your App skeleton is ready now. Let’s go ahead and add the ORM and use it to create and connect with Databases.


Using Sequelize and Setting up Database

So what is Sequelize??

Sequelize is an ORM. According to Sequelize documentation,

“Sequelize is a promise-based ORM for Node.js v4 and up. It supports the dialects PostgreSQL, MySQL, SQLite and MSSQL and features solid transaction support, relations, read replication and more.”

Since Sequelize is an ORM for NodeJS and as it supports many dialects, I have used Sequlized for this app. To start using Sequlize we have to first install it.

npm install --save sequelize
npm install --save mysql2

There is a CLI tool for Sequelize names “Sequelize-CLI” which comes really handy. So we will install it as well.

npm i sequelize-cli --save

To initialize, you need to run following command in the terminal

node_modules/.bin/sequelize init

This will create following folders

  • config, contains config file, which tells CLI how to connect with database
  • models, contains all models for your project
  • migrations, contains all migration files
  • seeders, contains all seed files
New directive structure

Before continuing further we will need to tell CLI how to connect to database. To do that let’s open default config file config/config.json. It looks something like this

{
"development": {
"username": "root",
"password": null,
"database": "database_development",
"host": "127.0.0.1",
"dialect": "mysql"
},
"test": {
"username": "root",
"password": null,
"database": "database_test",
"host": "127.0.0.1",
"dialect": "mysql"
},
"production": {
"username": "root",
"password": null,
"database": "database_test",
"host": "127.0.0.1",
"dialect": "mysql"
}
}

After configuring the config.json file we are ready to create the models classes. One important thing is that models are created along with migrations files. If you don’t know much about migrations you can read it from here. Simply just think of it as versioning of changes to the database.

Let’s suppose in the application that we are developing there are two models namely Category and SubCategory where SubCategory is a part of a Category. So Let’s create the models for them. We can generate models using Sequelize-CLI. Following is a sample command to create two models.

node_modules/.bin/sequelize model:generate --name Category --attributes name:string,description:stringnode_modules/.bin/sequelize model:generate --name SubCategory --attributes name:string,description:string,categoryId:INTEGER

This will generate two model classes in “models” directory and as well as two migrations files in “migrations” directory. Created files are as follows.

As you can see I have used less number of attributes for each model for the simplicity of this article. You can do whatever the changes to your model (removing attributes, adding new attributes, renaming attributes, adding new constraints, making attributes primary etc.)and what you need to keep in mind are that whatever the changes that you do, you need to do the changes to the migrations files.

Still, we haven’t created the database. We have just created the models and migrations files. Also, you should have noticed something that I have missed until now. In the beginning, I mentioned like SubCategory is a part of Category. So SubCategory should have a relationship with the Category model. but I haven’t specified that yet. Now let’s go ahead and do that. For that, I need to change the SubCategory Model and need to add the association in the Model.

Following shows the SubCategory model after adding the association.

Since we did changes to the SubCategory Model. We need to do changes to migrations files as well. So we will update the migration file to keep track of our latest change(making “categoryId” column to a foreign key).

You can also do this in a new migration file. To create a new migration file you need to run following command and it will create a new migration file with the timestamp in the file name.

node_modules/.bin/sequelize migration:generate --name subcategory_associations

In this file, we can specify the changes that we need to do. Namely making “categoryId” column with the foreign key relationship. So after adding the changes, the file would look like this.

Since we added the relationship to SubCategory we need to refer it from the Category side also. For that, we need to change the association in our Category model. So after the changes, it will look like this.

So we have created our models as well as migrations along with association. Now it’s time to create the database and to connect with the database. Since we are using Sequelize it’s very easy to connect with the database and create the database with all the required tables. For that what we need to do is to create the database with the name of the database that you gave in the config.json file. Creating the database with that name is enough. Creating the tables and the rest will be done by Sequelize.

After creating the database run the following in the terminal and it will create all the tables with relevant associations and constraints.

node_modules/.bin/sequelize db:migrate

It will create the table structures.

Table Structure

So we have created the Models and Database Structure. We are one step away from building the REST APIs.


Building the REST API

Express-generator comes with two default API endpoints. Namely

/ and /users

So we will try creating endpoints for Categories and SubCategories. For that go to “routes” directive and create new route file “categories.js”. I have added Categories endpoint with support to four main HTTP requests (GET, POST, PUT, DELETE).

  1. GET — To List all Categories
  2. POST — Add new Category
  3. PUT — Update existing Category
  4. DELETE — Delete a Category

Sample code as follows.

Is that all?? Not yet. We have to do one more thing.

We have to add the newly created “categories.js” routes file into our app.js file. After adding the file will look like following.

Voila!! That’s it.

Now start the application by running

npm start

Go to any API testing tool like Postman or anything like that and call the new API. http://127.0.0.1:3000/categories.

You will be able to see the response coming from the backend. If you add some data to your tables you will be able to see some nice output with the proper data. Try all HTTP methods GET, PUT, POST and DELETE and see whether they are working.

Route file for SubCategories can be created as follows. Also, note that there are different ways to fetch data and sent it to the frontend. If the frontend application doesn’t need to know all the information of SubCategory but need to know only “name” and “categoryId” we can create the API to send only the required data. You can read about different available options from here.

So that’s it. Note that this is only a basic guide on creating REST API NodeJS Applications using ExpressJS and Sequelize. There are different things to consider when going into production.

My Sample Codebase can be found from here: https://github.com/yasirunilan/myapp_nodejs_example

Happy Reading !!

PulseQue

PulseQue IT Solutions is an emerging IT solution provider in the IT domain. As an emerging IT solution provider, we have provided many IT solutions in different IT domains covering Education, Health, E-Commerce and many more. We undertake all sorts of Web Application Development,

yasiru nilan

Written by

Passionate Lover of New Tech ❤ Software Engineer at OrangeHRM (https://www.orangehrm.com/)

PulseQue

PulseQue

PulseQue IT Solutions is an emerging IT solution provider in the IT domain. As an emerging IT solution provider, we have provided many IT solutions in different IT domains covering Education, Health, E-Commerce and many more. We undertake all sorts of Web Application Development,

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade