Create your First REST API with Node.js, Express and MongoDB

Image for post
Source: freecodecamp.org

An API is an application programming interface. It is a set of rules that allow programs to talk to each other. The developer creates the API on the server and allows the client to talk to it.

REST determines how the API looks like. It stands for “Representational State Transfer”. It is a set of rules that developers follow when they create their API. One of these rules states that you should be able to get a piece of data (called a resource) when you link to a specific URL.

Each URL is called a request while the data sent back to you is called a response.

– smashingmagazine.com

In this article we are going to develop REST API with the help of Node.js, Express and Mongodb. We will complete the CRUD operation for Bio in this article. So, let’s dive into it!

Node Version

We need to verify first that Node is installed to our machine. If not installed, first of all install node to your machine. You can check the version of node using following command.

node -v

Npm Version

Now let’s verify npm installed to the machine. You can check the version of npm using following command and install it if you haven’t done yet.

npm -v

MongoDB

We are using MongoDB as our database. MongoDB is document driven NoSql database. If you want to learn more about MongoDB and if you haven’t installed MongoDB yet, please refer to my article on MongoDB.
You can verify mongo using following command.

mongo --version

Start project

Now it’s time for us to start working on our project. First of all I will create a folder named MERN (refers to Mongo Express React Node) where I want to keep my node project. Then, inside MERN folder I want to give the project name and for that, I will create FirstRest folder and go inside it. Upto now we haven’t done anything rather that creating the project folder.

mkdir MERN 
cd MERNmkdir FirstRest
cd FirstRest

Initialize node.js project

Now we initialize our node.js project with npm init inside FirstRest directory.

npm init

While initiating the node.js, you will be asked different things. You only have to choose default name, add description, add author’s name and choose default License to generate package.json. If have have done any mistake, don’t worry you can change it afterwards. After completing the operation you will see the following screen.

Image for post

Install Express.js

Let’s install express and setup the server. We need to run the server to make our API accessible to web browser or tools for testing the API like Postman. If you are not familiar with ExpressJS please refer to the official page. So, install express with the help of npm.

npm install express --save

The above command will install the dependencies.

Create starter file index.js

It’s time for opening the project with the help of IDE. I will prefer vscode to run the project. You can see the node_modules folder and package.json file in the project. Since index.js is our entry file, we are going to configure the index.js file. Let’s add the following code to the index.js file on root of the project.

//index.js//Import Express
let express = require('express')//Start App
let app = express();//Assign port
var port = process.env.PORT || 8080;// Welcome message
app.get('/', (req, res) => res.send('Welcome to Express'));// Launch app to the specified port
app.listen(port, function() {
console.log("Running FirstRest on Port "+ port);
})

Run your server

Run the project with following command on project directory.

node index

Open up the project on http://localhost:8080 on your browser and you will get the following screen.

Image for post

Structuring Project

We need to create the model, controller and routes for creating our first api on node.js.

model → For managing the database layer (request and response)
controller → For defining all the http requests and handle them
routes →For defining all the endpoints

Create router

We add router.js file to the root of the project and add following code to test api.

//routes.js//initialize express router
let router = require('express').Router();//set default API response
router.get('/', function(req, res) {
res.json({
status: 'API Works',
message: 'Welcome to FirstRest API'
});
});//Export API routes
module.exports = router;

Modify index file
Now we modify index.js, so that router is available to us. We add following code to our existing starter file index.js.

//index.js//Import routes
let apiRoutes = require("./routes")//Use API routes in the App
app.use('/api', apiRoutes)

We need to stop the server once and start again in order to observe the change we have made. So, first run ctrl+c or cmd+c.
Then start the server with node index. For obtaining the changes we had made previously, we have to open the browser with http://localhost:8080/api.
Now you can see the following screen as output. Great!

Image for post

Watch and restart express-server

Till now, the scenario of our project is to run the express-server every time when we make change to our project. This is really disgusting when we are working on development. So, I have one solution to avoid this kind of problem by installing nodemon. This will allow the express-server to watch the changes and restart it by itself. See how we are going to install it below.

//On Windows
npm install -g nodemon// On Mac/Linux
sudo npm install -g nodemon

Start with nodemon
After we have installed nodemon, let’s run our project with nodemon by using following command.

nodemon index

You can now see that express-server is restarted automatically when it detects some change in the project file. Wow, great! now our development would be faster.

Setup MongoDB

Since we are using MongoDB as our database, we need to have up and running mongoDb on our machine. If you haven’t done yet, don’t worry, consult article on MongoDB and make it running.
For running your MongoDB shell you have to enter the following command. Please make sure your MongoDB is running before you open the shell. Keep this window open for using our database.

mongo

I ran with some status=14 error while trying to start mongodb. So, I stuck for sometime and found best solution in medium and if you got stuck somewhere with same kind of error, please look at this link.
Ignore this if you have no problem in starting mongodb.

Install Mongoose and Body-Parser
We need to install Mongoose and Body-Parser. Let me explain what they are and how to install them.

Mongoose is the node.js package for modeling mongodb. It helps to handle the business logic and validation for mongodb on node.js. Learn more about Mongoose here.
Body-Parser enables app to parse the data coming from request. For eg: form data from urlencode. We need to import them in our app and use them as well.

Now install both of them using following commands.

npm install mongoose --save
npm install body-parser --save

Now we update our index.js with the mongoose and body-parser. Following is the code to be added.

//index.js//import body parser
let bodyParser = require('body-parser');//import mongoose
let mongoose = require('mongoose');//configure bodyparser to hande the post requests
app.use(bodyParser.urlencoded({
extended: true
}));app.use(bodyParser.json());//connect to mongoose
const dbPath = 'mongodb://localhost/firstrest';
const options = {useNewUrlParser: true, useUnifiedTopology: true}
const mongo = mongoose.connect(dbPath, options);mongo.then(() => {
console.log('connected');
}, error => {
console.log(error, 'error');
})

Now, our complete index.js file looks like:

//index.jslet express = require('express')
let app = express();
var port = process.env.PORT || 8080;// Welcome message
app.get('/', (req, res) => res.send('Welcome to Express'));// Launch app to the specified port
app.listen(port, function() {
console.log("Running FirstRest on Port "+ port);
})//Import routes
let apiRoutes = require("./routes")//Use API routes in the App
app.use('/api', apiRoutes)//import body parser
let bodyParser = require('body-parser');//import mongoose
let mongoose = require('mongoose');//configure bodyparser to hande the post requests
app.use(bodyParser.urlencoded({
extended: true
}));app.use(bodyParser.json());//connect to mongoose
const dbPath = 'mongodb://localhost/firstrest';
const options = {useNewUrlParser: true, useUnifiedTopology: true}
const mongo = mongoose.connect(dbPath, options);mongo.then(() => {
console.log('connected');
}, error => {
console.log(error, 'error');
})

Now its time for use to work for our Model, Routes and Controller. For now, we are just implementing the CRUD of Bio with some fields. We are adding the bio to the database, retrieving the bio, updating it and deleting it. Let’s include following fields in our bio model.

  • name
  • email
  • phone
  • address

We will need following endpoints to run our api.

  • GET api/bio → Retrieves all the bio data
  • POST api/bio → Add new bio data
  • GET api/bio/{id} → Retrieve the single bio data
  • PUT api/bio/{id} → Update the bio data
  • DELETE api/bio → Delete the bio data

Now we going to add model and controller for performing CRUD of Bio.

Create Model

Add file named bioModel.js to the root of the project and add following lines of code to the model.

//bioModel.jsvar mongoose = require('mongoose');//schema
var bioSchema = mongoose.Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
phone: {
type: String,
required: true
},
address: {
type: String,
required: true
},
created_at: {
type: Date,
default: Date.now
}
});// Export Bio Model
var Bio = module.exports = mongoose.model('bio', bioSchema);module.exports.get = function (callback, limit) {
Bio.find(callback).limit(limit);
}

Create Routes

We now update the route.js we defined before with following lines of code to include different endpoints we discussed above.

//routes.js//initialize express router
let router = require('express').Router();//set default API response
router.get('/', function(req, res) {
res.json({
status: 'API Works',
message: 'Welcome to FirstRest API'
});
});//Import Bio Controller
var bioController = require('./bioController');// Bio routes
router.route('/bio')
.get(bioController.index)
.post(bioController.add);router.route('/bio/:bio_id')
.get(bioController.view)
.patch(bioController.update)
.put(bioController.update)
.delete(bioController.delete);//Export API routes
module.exports = router;

Create Controller

We create a file with name bioController.js to the root of the project. We add following lines of code to handle different types of request and provide response according the request we get.

//bioController.js//Import Bio Model
Bio = require('./bioModel');//For index
exports.index = function (req, res) {
Bio.get(function (err, bio) {
if (err)
res.json({
status: "error",
message: err
});
res.json({
status: "success",
message: "Got Bio Successfully!",
data: bio
});
});
};//For creating new bio
exports.add = function (req, res) {
var bio = new Bio();
bio.name = req.body.name? req.body.name: bio.name;
bio.email = req.body.email;
bio.phone = req.body.phone;
bio.address = req.body.address;//Save and check error
bio.save(function (err) {
if (err)
res.json(err);res.json({
message: "New Bio Added!",
data: bio
});
});
};// View Bio
exports.view = function (req, res) {
Bio.findById(req.params.bio_id, function (err, bio) {
if (err)
res.send(err);
res.json({
message: 'Bio Details',
data: bio
});
});
};// Update Bio
exports.update = function (req, res) {
Bio.findById(req.params.bio_id, function (err, bio) {
if (err)
res.send(err);
bio.name = req.body.name ? req.body.name : bio.name;
bio.email = req.body.email;
bio.phone = req.body.phone;
bio.address = req.body.address;//save and check errors
bio.save(function (err) {
if (err)
res.json(err)
res.json({
message: "Bio Updated Successfully",
data: bio
});
});
});
};// Delete Bio
exports.delete = function (req, res) {
Bio.deleteOne({
_id: req.params.bio_id
}, function (err, contact) {
if (err)
res.send(err)
res.json({
status: "success",
message: 'Bio Deleted'
})
})
}

Demo

Now we need to open postman for testing our Api. If you have not installed postman yet and if you are on Ubuntu, please refer this link to install postman to the system. If you are in other OS, first install postman.
We are all set to test our api.

First of all let’s see what we have on our bio. Please enter http://localhost:8080/api/bio and send the GET request as shown below and you will get the response with empty list.

Image for post

Let us add a data to our bio. You need to select POST as request type, navigate to body and choose the option as I have selected below. Then add the following fields and their values.

Image for post

After running sending the request, we have created a new bio on our database. We add 2–3 more bios to our database as before.

Image for post

Again we retrieve the data that we have on bio with GET request as follows.

Image for post

For retrieving the single bio, we pass bio id the url with GET request as given below.

Image for post

We are now updating the value of one of the bio with PUT request as follows.

Image for post

Similarly, we can delete the bio using id as given below with DELETE request.

Image for post

After deleting one of the bio, lets retrieve the remaining bios from our database as given below.

Image for post

Wow! it simply worked perfectly. We did a simple CRUD of a bio with the help of Node.js, ExpressJS and MongoDB. Did you enjoy making your First Rest API with Node.js, Express and MongoDB? Let me know, if you enjoyed creating your First API with me. If you have any confusions or you got stuck somewhere please let me know in the comments below. You can also refer to my Github repository to access the project and run it directly. I will come up with more articles on MERN stack on the days to come.
Stay tuned!

Post a Comment

Previous Post Next Post