Node JS — Creating a CRUD API With Node js

Sjlouji
The Startup
Published in
5 min readSep 17, 2020
Cover Image

Hello all. In this blog, let’s build a RESTfull API with Node Js, that performs all the CRUD operations.

What is CRUD?

CRUD stands for Create, Read, Update, and Delete.

Create — To insert any record to the database.

Read — To retrieve records from the database.

Update — To update a record in the database.

Delete — To delete a record in the database.

If you are new to Node and Express JS, do visit my previous blogs on Node JS, which explains the basics of Node and Express JS.

  1. Creating a Node Project

To begin with, let's create a simple Node project named crud.

mkdir crud
cd crud/
npm init -y
touch index.js

package.json

"scripts": {
"start":"node index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},

After creating it, install all the required packages like express, body-parser, and mongoose.

express — To structure our web application to handle multiple different HTTP requests.

body-parser — To read the request body and to parse it into JSON format.

mongoose — To connect with MongoDB.

npm install express
npm i body-parser
npm i mongoose

Once done, create the server file. To do that, copy the below code to your index.js file.

index.js

const express = require('express')
var app = express()
//Route
app.get('/',function(req,res){
res.send('hello world')
})
//MongoDB connection
mongoose.connect('mongodb://localhost/test', {useNewUrlParser: true});
mongoose.connection.once('open',function(){
console.log('Database connected Successfully');
}).on('error',function(err){
console.log('Error', err);
})
//Server
app.listen(8000,function(){
console.log('Server is Up')
})

Just by starting the server, you should see hello world getting displayed on the browser. (http://localhost:8000/)

npm start

Also, create three other folders named Controller, Routes, and Models. My project structure looks like this.

Project Structure

2. Creating an Employee Model

To perform any database operation, the first thing we need is a schema. So let’s create it first.

Below, I have created an Employee schema with attributes empName, empEmail, and empMobile.

Models/emp.js

const mongoose = require('mongoose')const empSchema = new mongoose.Schema({
empName: {
type: String,
required: true
},
empEmail: {
type: String,
required: true
},
empMobile: {
type: String,
required: true
},
})
module.exports = mongoose.model('Emp', empSchema)

3. Create API

Now let’s start creating a restful API. Initially, I am creating a Create API that inserts an employee recorded into our MongoDB database.

So, to do that, I am creating a routes file named emp.js where we write all our routes for the employee Model.

Routes/emp.js

const express = require('express')
var router = express()
const create = require('../controller/emp')
const bodyparser = require('body-parser');
router.use(bodyparser.json())
router.post('/create',create.create)
module.exports = router

The below code gets the request and response from the route and it creates an Emp object. Once created, it saves the object to MongoDB. If any error occurs, it is also handled automatically.

Controller/emp.js

const Emp = require('../models/emp')
const mongoose = require('mongoose')
function create(req,res,next){
let empName = req.body.empName;
let empEmail = req.body.empEmail;
let empMobile = req.body.empMobile;
let emp = new Emp({
empName,
empEmail,
empMobile
})
emp.save().then((data)=>{
res.send(data)
})

}
module.exports.create = create

Once done, call the employee route in the server file with a prefix /emp.

index.js

const router = require('./routes/emp')app.use('/emp',router)

Now make a post request to http://localhost:8000/emp/create with the required parameters. The values entered will be stored in the Database.

Create API

4. Read API

Now let’s retrieve all the data that are stored in the database. To do that, create a new route.

Routes/emp.js

const express = require('express')
var router = express()
const create = require('../controller/emp')
const view = require('../controller/emp')
const bodyparser = require('body-parser');
router.use(bodyparser.json())
router.post('/create',create.create)
router.get('/',view.view)
module.exports = router

After creating the route, create a new function named view in the employee controller. Just by calling the function find, we can retrieve every record from the collection.

Controller/emp.js

const Emp = require('../models/emp')
const mongoose = require('mongoose')
function create(req,res,next){
let empName = req.body.empName;
let empEmail = req.body.empEmail;
let empMobile = req.body.empMobile;
let emp = new Emp({
empName,
empEmail,
empMobile
})
emp.save().then((data)=>{
res.send(data)
})
}
function view(req,res,next){
Emp.find({}).then((data)=>{
res.send(data)
})
}
module.exports.create = create
module.exports.view = view

On visiting the URL http://localhost:8000/emp, you will see all the employee values getting displayed.

Read API

5. Update API

To create an update API, create another route as done above. To update a record, we make a patch or a put request.

Routes/emp.js

const update = require('../controller/emp')router.patch('/:id',update.update)

Now move towards the employee controller and create a new function named update which will update the employee record.

To update a record, we should find if the record exists in the database. This can be done by the findByIdAndUpdate method wherein we have to pass the _id of the record and the values, we want to change.

Controller/emp.js

function update(req,res,next){
Emp.findByIdAndUpdate(req.params.id,req.body, (err,emp)=>{
if (err) {
return res.status(500).send({error: "Problem with Updating the Employee recored "})
};
res.send({success: "Updation successfull"});
})

}
module.exports.update = update

Make a Patch request to http://localhost:8000/emp/<id> with the data to be changed. This will update the employee record.

Update API

6. Delete API

Creating a Delete API view is the most simple one out of all. To delete a record from a database, we make adelete request. As we did earlier, create another route for deleting a record. The route should have a parameter id that tells which record should be deleted.

Routes/emp.js

const remove = require('../controller/emp')router.delete('/delete/:id',remove.remove)

Inside the controller, create a function named remove for deleting employee records from the database. Deleting a record can be done using the findByIdAndDelete method which is similar to the findByIdAndUpdate method. It also requires the same _id.

Controller/emp.js

function remove(req,res,next){
Emp.findByIdAndDelete(req.params.id, (err,emp)=>{
if(err){
return res.status(500).send({error: "Problem with Deleting the
Employee recored "})
}
res.send({success: 'Employee deleted successfully'})
})

}
module.exports.remove = remove

On making a delete request to the URL http://localhost:8000/emp/delete<id>, you can delete any record from that database.

Delete API

Feel free to contact me for any queries.

Email: sjlouji10@gmail.com

Linkedin: https://www.linkedin.com/in/sjlouji/

Complete code on my GitHub:

Happy Coding …

--

--

Sjlouji
The Startup

Software Engineer at @Pando. Developer | Writer. From ABC to the world of code.