Creating REST API Application with NodeJS



  1. Using Sequelize to create database and Model Classes
  2. 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.


npm install -g express-generator
express -h
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
express --view=pug myapp
cd myapp
npm install

DEBUG=myapp:* npm start
/
/users

Using Sequelize and Setting up Database

So what is Sequelize??



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

npm i sequelize-cli --save
node_modules/.bin/sequelize init
  • models, contains all models for your project
  • migrations, contains all migration files
  • seeders, contains all seed files


{
"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"
}
}
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



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


Building the REST API

Express-generator comes with two default API endpoints. Namely

/ and /users
  1. POST — Add new Category
  2. PUT — Update existing Category
  3. DELETE — Delete a Category



Sample code as follows.


npm start

Comments