DEV Community

Sanjay Saini
Sanjay Saini

Posted on • Originally published at sanjaysaini.tech

Build Restful API with Nodejs Express MongoDB

Build Restful API with Nodejs Express MongoDB

In this article I will share how to build Restful API with Nodejs Express MongoDB that will expose endpoints to the basic CRUD operations. This restful API can be consumed by any frontend application developed in any web dev technologies.

I will write another article on developing frontend application and consume this restful API in that app.

Let’s see what we need to build this Restful API.

Prerequisite

  • In order to develop and run this restful API, we need Node.js, which is JavaScript runtime installed on our machine. With Node.js comes NPM which is a node package manager that we will use to install other packages like Express needed to develop this API. So download and install the latest Node.js available from this link.
  • We need code editor as well, I will recommend VS Code but if you already have any other code editor that you are using to write C# code then stick with that otherwise download and install VS Code from this link.
  • We need Postman which is a famous API Client tool used in testing web API by sending web requests and inspecting response from the API. So download and install Postman for free from this link.
  • Last, we need to have MongoDB installed on the machine. You can download and install MongoDB community edition free from this link.

MongoDB Installation/Setup

MongoDb is a no-SQL database that stores data in the form of JSON object which is called Document. All Documents are stored in the container called Collection. So first Collection is created and then Document in inserted into it. Download and run the installer, select Custom option and follow the wizard instructions and keep the default setting as is. It will create data folder at C:\Program Files\MongoDB\Server\4.2\data to store databases and also start MongoDB Server as window service after installation is finished. That’s all we need to do on MondoDB side for this API.

Now that we have setup our dev environment and installed all the required software we are ready to start and build restful API with Nodejs Express MongoDB.

Get Started…

Start with creating project folder webapi that will contain code for our restful API and move into it.

$ mkdir webapi

$ cd webapi

Now we will start with creating package.json file which is the first building block for Node.js application and holds application configuration and package dependencies details that is required in order to run the application.

So open the command window in the project folder and run following command to create it.

$ npm init --yes

Install Express, Mongoose and body-parser

Express is a minimal and flexible Node.js web application framework which is developed on top of Http module of Node.js that provides a robust set of features and myriad of HTTP utility methods and middleware to create a robust web API.

Mongoose is a MondoDB object data modelling package that provides a straight-forward, schema-based solution to model data in the Node.js application. It includes built-in type casting, validation, query building, business logic hooks and more, out of the box.

body-paser is Node.js middleware for parsing incoming request bodies in a middleware before request handlers and is available under the req.body property.

So install all these packages by running following command in the command window.

$ npm i express mongoose body-parser –save

–save option will add entry for these packages in the dependencies section in package.json file for our project.

Write Code…

Now open the code editor to start writing code. Run following command to start VS Code editor in the project folder.

$ vscode .

Create db.js file and add following code to create and export connection with MongoDB using mongoose.

const mongoose = require("mongoose");
mongoose.connect(
  "mongodb://localhost:27017/customerDb",
  { useNewUrlParser: true, useUnifiedTopology: true },
  err => {
    if (!err) console.log("Successfully connect to MondoDB...");
    else
      console.log(
        "Connection to MongoDb failed :" + JSON
         .stringify(err, undefined, 2)
      );
  }
);

module.exports = mongoose;

Create index.js file and add following code to create Express server to host our restful API. It will also import mongodb connection from db.js.

const bodyParser = require("body-parser");
const { mongoose } = require("./db");
const customer = require("./Controller/CustomerController");

const express = require("express");
const app = express();

//added middleware code
app.use(bodyParser.json());
app.use("/customers", customer);

const port = process.env.port || 3000;
app.listen(port, () => {
  console.log(`server listening at port :${port}`);
});

Now we need to create object data model to store Customer data in the MongoDB database. So create Models folder and create Customer.js file in it. Add following code to hold Customer model schema and export it as well.

const mongoose = require("mongoose");

var Customer = mongoose.model("Customer", {
  first_name: String,
  last_name: String,
  gender: String,
  age: Number,
  email: String
});

module.exports = { Customer };

The last piece of code is to add controller code that will expose our restful API endpoints. So create Controller folder and in it create CustomerController.js file.

Now add following code for CRUD operations.

  • Add following code to handle GET request to fetch the Customers.
router.get("/", (req, resp) => {
  Customer.find((err, docs) => {
    if (err)
      console.log(
        "Error while getting customers..." + JSON
         .stringify(err, undefined, 2)
      );
    else resp.send(docs);
  });
});
  • To create new Customer, add following code to handle POST request from the client.
router.post("/", (req, resp) => {
  let cust = new Customer({
    first_name: req.body.first_name,
    last_name: req.body.last_name,
    gender: req.body.gender,
    age: req.body.age,
    email: req.body.email
  });
  cust.save((err, doc) => {
    if (err)
      console.log(
        "error in saving customers..." + JSON
         .stringify(err, undefined, 2)
      );
    else resp.send(doc);
  });
});
  • Add following code to handle PUT request from client to update existing Customer.
router.put("/:id", (req, resp) => {
  let customerId = req.params.id;
  if (!ObjectId.isValid(customerId))
    return resp.status(400)
               .send(`Customer not found for id :${customerId}`);
  • And to handle DELETE request to delete the Customer, Add following code.
router.delete("/:id", (req, resp) => {
  let customerId = req.params.id;
  if (!ObjectId.isValid(customerId))
    return resp.status(400)
               .send(`Customer not found for id :${customerId}`);

  Customer.deleteOne({ _id: customerId }, (err, docs) => {
    if (err)
      console.log(
        "Error while deleting customers..." + JSON
         .stringify(err, undefined, 2)
      );
    else resp.send(docs);
  });
});

That’s all we need to code for now…

Launch the API

Now run following command to host our restful API.

$ node index.js

It will launch the web server that will host our API available at http://localhost:3000/Customers

Test the API

Now open the Postman Web API Client application and click on the Create a request to initiate an API request to our restful API.

Take following steps to test POST request handler to create the Customer.

  • Select POST HTTP verb from the drop down.
  • Enter request URL http://localhost:3000/Customers for post request.
  • Select Body tab and then select raw radio button and finally select type JSON from the drop down.
  • In the request body enter following JSON object representing our Customer resource that we want to create.
{
  "first_name" : "Amit",
  "last_name" : "Patil",
  "gender" : "Male",
  "age" : 39,
  "email" : "Amit@gmail.com"
}

You can test rest of the CRUD operations by following my article where I have tested another web api using PostMan. Although web api is different but steps to test any we api are same with PostMan.

Hope you have enjoyed it…check out my other articles.

The post Build Restful API with Nodejs Express MongoDB appeared first on Sanjay Saini’s Tech World.

Top comments (3)

Collapse
 
romanazeem profile image
Roman Azeem

I have a query .. How can we use router. without even importing this class. and also i am confusing in Controller code..Is that i have to write the crud operation one by one in controller class to test the server webapi? and please explain router in crud operations

Collapse
 
sanjaysaini2000 profile image
Sanjay Saini

you need to add all the curd operations code for get/post/put/delete in the controller class as I mentioned in the article. you also need to import express and create express.Router object 'router' in the controller class plus few other objects used. you can get source code from my github repo -github.com/sanjaysaini2000/node-ex...

Collapse
 
romanazeem profile image
Roman Azeem

I got it. Thank man for sorting this out for me.