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.
- Creating NodeJS app skeleton using ExpressJS
- Using Sequelize to create database and Model Classes
- 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.
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.
You will have a folder structure like the following.
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.
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 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
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
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
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.
It will create the table structures.
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).
- GET — To List all Categories
- POST — Add new Category
- PUT — Update existing Category
- 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
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 !!