How to create CRUD REST API using Node.Js?
Create a Project
c:\> npx express --view=ejs crud_api
Initialise and Configure Our Project
File Name :
c:\crud_api> npm init -y
npm install
Install express and other dependencies
File Name :
c:\crud_api> npm install express --save
install Body Parser :-
File Name :
c:\crud_api> npm install body-parser --save
MySql Install
File Name :
c:\crud_api> npm install mysql --save
Nodemon Install
File Name :
c:\crud_api> npm install --save-dev nodemon
Create server.js
File Name : server.js
const express = require('express');
const bodyParser = require('body-parser');
// create express app
const app = express();
// Setup server port
const port = process.env.PORT || 3000;
// parse requests of content-type - application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }))
// parse requests of content-type - application/json
app.use(bodyParser.json())
// define a root route
app.get('/', (req, res) => {
res.send("Hello World");
});
// Require employee routes
const employeeRoutes = require('./routes/employee_routes')
// using as middleware
app.use('/api/v1/employees', employeeRoutes)
// listen for requests
app.listen(port, () => {
console.log(`Server is listening on port ${port}`);
});
Employee Table
File Name :
CREATE TABLE IF NOT EXISTS `employees` (
`id` BIGINT UNSIGNED AUTO_INCREMENT,
`first_name` VARCHAR(255) NOT NULL,
`last_name` VARCHAR(255) NOT NULL,
`email` VARCHAR(255) NOT NULL,
`phone` VARCHAR(50) NOT NULL,
`organization` VARCHAR(255) NOT NULL,
`designation` VARCHAR(100) NOT NULL,
`salary` DECIMAL(11,2) UNSIGNED DEFAULT 0.00,
`status` TINYINT UNSIGNED DEFAULT 0,
`is_deleted` TINYINT UNSIGNED DEFAULT 0,
`created_at` DATETIME NOT NULL,
`updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
INSERT INTO employees (`first_name`, `last_name`, `email`, `phone`, `organization`, `designation`, `salary`, `status`, `is_deleted`, `created_at`) VALUES ('John', 'Doe', 'johndoe@gmail.com', '1234567890', 'BR Softech Pvt Ltd', 'Full Stack Developer', '500.00', '1', '0', '2019-11-19 03:30:30');
INSERT INTO employees (`first_name`, `last_name`, `email`, `phone`, `organization`, `designation`, `salary`, `status`, `is_deleted`, `created_at`) VALUES ('Jane', 'Doe', 'janedoe@gmail.com', '9876543210', 'RG Infotech Jaipur', 'PHP Developer', '450.00', '1', '0', '2019-11-19 03:35:30');
create Database connection
File Name : config/db.js
'use strict';
const mysql = require('mysql');
//local mysql db connection
const dbConn = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'root',
database : 'nodedb'
});
dbConn.connect(function(err) {
if (err) throw err;
console.log("Database Connected!");
});
module.exports = dbConn;
Create controller
File Name : src/controller/employee_controller.js
'use strict';
const Employee = require('../models/employee_model');
exports.findAll = function(req, res) {
Employee.findAll(function(err, employee) {
console.log('controller')
if (err)
res.send(err);
console.log('res', employee);
res.send(employee);
});
};
exports.create = function(req, res) {
const new_employee = new Employee(req.body);
//handles null error
if(req.body.constructor === Object && Object.keys(req.body).length === 0){
res.status(400).send({ error:true, message: 'Please provide all required field' });
}else{
Employee.create(new_employee, function(err, employee) {
if (err)
res.send(err);
res.json({error:false,message:"Employee added successfully!",data:employee});
});
}
};
exports.findById = function(req, res) {
Employee.findById(req.params.id, function(err, employee) {
if (err)
res.send(err);
res.json(employee);
});
};
exports.update = function(req, res) {
if(req.body.constructor === Object && Object.keys(req.body).length === 0){
res.status(400).send({ error:true, message: 'Please provide all required field' });
}else{
Employee.update(req.params.id, new Employee(req.body), function(err, employee) {
if (err)
res.send(err);
res.json({ error:false, message: 'Employee successfully updated' });
});
}
};
exports.delete = function(req, res) {
Employee.delete( req.params.id, function(err, employee) {
if (err)
res.send(err);
res.json({ error:false, message: 'Employee successfully deleted' });
});
};
create model
File Name : src/model/employee_model.js/
'use strict';
var dbConn = require('./../../config/db');
//Employee object create
var Employee = function(employee){
this.first_name = employee.first_name;
this.last_name = employee.last_name;
this.email = employee.email;
this.phone = employee.phone;
this.organization = employee.organization;
this.designation = employee.designation;
this.salary = employee.salary;
this.status = employee.status ? employee.status : 1;
this.created_at = new Date();
this.updated_at = new Date();
};
Employee.create = function (newEmp, result) {
dbConn.query("INSERT INTO employees set ?", newEmp, function (err, res) {
if(err) {
console.log("error: ", err);
result(err, null);
}
else{
console.log(res.insertId);
result(null, res.insertId);
}
});
};
Employee.findById = function (id, result) {
dbConn.query("Select * from employees where id = ? ", id, function (err, res) {
if(err) {
console.log("error: ", err);
result(err, null);
}
else{
result(null, res);
}
});
};
Employee.findAll = function (result) {
dbConn.query("Select * from employees", function (err, res) {
if(err) {
console.log("error: ", err);
result(null, err);
}
else{
console.log('employees : ', res);
result(null, res);
}
});
};
Employee.update = function(id, employee, result){
dbConn.query("UPDATE employees SET first_name=?,last_name=?,email=?,phone=?,organization=?,designation=?,salary=? WHERE id = ?", [employee.first_name,employee.last_name,employee.email,employee.phone,employee.organization,employee.designation,employee.salary, id], function (err, res) {
if(err) {
console.log("error: ", err);
result(null, err);
}else{
result(null, res);
}
});
};
Employee.delete = function(id, result){
dbConn.query("DELETE FROM employees WHERE id = ?", [id], function (err, res) {
if(err) {
console.log("error: ", err);
result(null, err);
}
else{
result(null, res);
}
});
};
module.exports= Employee;
create Routes
File Name : routes/employee_routes.js
const express = require('express')
const router = express.Router()
const employeeController = require('../src/controllers/employee_controller');
// Retrieve all employees
router.get('/', employeeController.findAll);
// Create a new employee
router.post('/', employeeController.create);
// Retrieve a single employee with id
router.get('/:id', employeeController.findById);
// Update a employee with id
router.put('/:id', employeeController.update);
// Delete a employee with id
router.delete('/:id', employeeController.delete);
module.exports = router
API Test Using Postman
File Name : Postman
open postman and choose get method :-
http://localhost:3000/api/v1/employees
http://localhost:3000/api/v1/employees/1
API Test Using Postman
File Name : Postman
GET /api/v1/employees: will give all employees stored in database
GET /api/v1/employees/<employee_id>: will give a specific employee with employee_id.
POST /api/v1/employees : create a employee
PATCH /api/v1/employees/<employee_id>: update a employee partially
DELETE /api/v1/employees/<employee_id>: delete a employee
PUT /api/v1/employees/<employee_id>: update a employee completely
Previous
Next