Do you feel stuck while using the Node JS API? To your rescue, we have a quick and easy to understand step-by-step guide on How to Use Node JS API.

It begins by recalling the features of node.js. In simple words, node.js is a javascript environment that allows you to build dynamic applications, servers, backend APIs, etc.

As compared to the previous versions of JavaScript engines, node.js gives you an extra edge to create a super-interactive platform. In node.js, we come across various frameworks like Express, MongoDB, React, etc.

Each one of them serves a different purpose in terms of front-end and back-end development. Sometimes, these frameworks are used in a combination of one or two to create the desired Node.js API.

Understanding The Node.js API

The only reason behind the massive use of Node API is its accessibility. Because it allows you to make easy transformations, handle errors, and regulate parameters in the case of Node JS API.

Node JS API offers wide range of functionality support that makes the development process much quicker and potent. Experts advise to approach for Node JS Development Agency who possess expertise in working with NodeJS API and has a good track-record in developing robust applications using NodeJS.

Our veteran Node JS experts have prepared this step-by-step manifest on using NodeJS API, but the following guide is inclusive of JavaScript coding. Hence, we advise you to get a thorough knowledge of the same before diving into the guide.

Creating A REST API With Node.js

To begin with, we will learn how to create a Nodejs REST API. The suffix REST before the API stands for Representational State Transfer.

This kind of APIs is efficient in establishing communication between two softwares. REST APIs or RESTful APIs overcomes the limitations of conventional websites and servers.

The conventional method of sending requests or retrieving data does not support the dynamic performance of applications.

Because an application involves many things apart from loading numerous HTTP requests. In a regular network, the server loads dedicated HTML pages for the requested URL. But this is not the case in an app.

An application must be able to send information without jumping into another webpage. Hence, the RESTful API is used for achieving such versatility. It allows us to develop hybrid applications that can perform tasks like GET, POST, PATCH, DELETE, etc.

Now, you are ready to dive deeper into the step-by-step guide of how to create a Node JS RESTful API:-

Setup

The first step involved here will be to set up the right environment and gather the right resources. Make sure to install the latest version of node.js from its official website.

In case if the latest version is not compatible with your system, then you can install the long term stability version from the same website.

Now, select a folder of your choice to create a project in it. You can give it any name of your choice or use the one used by us i.e. nodejs-rest-api.

The next step involves running the nodes package manager by executing npm init. This ensures the availability of all the dependencies required to build a Node JS RESTful API.

So, the code goes something like this:

{

 "name": "node-rest-api",

 "version": "1.0.0",

 "description": "A tutorial of how to use node.js for creating a RESTful API project",

 "main": "index.js",

 "scripts": {

   "test": "echo "Error: no test specified" && exit 1"

 },

"keywords": {

   “node”,

   “restful”,

   “api”,

 },

"repository": {

   "type": "git",

   "url": "<link of the git repository>(if you want to add any)"

 },

 "author": "<name of the author>",

 "license": "ISC",

 "dependencies": {

   "express": "^4.16.2",
 "jsonwebtoken": "^8.5.1",
    "mongodb": "^3.6.3",
    "mongoose": "^5.11.3",


}

}

In this project, we will use the Express framework for creating the Node JS RESTful API. With the completion of this step, we have gathered all the right resources and prepared our environment for creating a dynamic Nodejs REST API. Thus, let’s move on to the next step!

Creating A User Module

To create a user module, we first need to create a user schema. This schema requires an object data modeling library such as Mongoose.

Navigate to the target users.model.js to create a schema in it.

 const mongoose = require("mongoose");
const userSchema = new mongoose.Schema({
  firstName: {
    type: String,
  },
  lastName: {
    type: String,
  },
  emailID: {
    type: String,
  },
  password: {
    type: String,
  },
  permissionLevel: {
    type: Number,
  },
});

All the above lines of code are followed by the attachment of the schema module as follows:

const userModel = mongoose.model("Users", userSchema);
module.exports = userModel;

Now, this module is pretty much ready to carry out stateless operations such as Create, Read, Update, Delete(CRUD).

For performing the ‘create user’ functionality, we need to define a route to the module like this:

app.post('/users', [

   UsersController.insert

]);

You can even check this function by activating the server and sending a request to the /users module via JSON data.

{

   "firstName" : "miley",

   "lastName" : "cirus",

   "emailID" : "[email protected]",

   "password" : "testcasepwd"

}

For ensuring data security, we use hashing techniques.

To hatch the entered password of user module, use controller:

 /controllers/users.controller.js:
const crypto = require("crypto");
const UserModel = require("../models/users.model");
exports.insert = (req, res) => {
  let salt = crypto.randomBytes(16).toString("base64");
  let hash = crypto
    .createHmac("sha512", salt)
    .update(req.body.password)
    .digest("base64");
  req.body.password = salt + "$" + hash;
  req.body.permissionLevel = 1;
  const user = new UserModel(req.body);
  user.createUser(req.body).then((result) => {
    res.status(201).send({ id: result._id });
  });
};

To complete the create user module, we use the createUser in /models/users.model.js model. It is an important aspect of NodeJS API.

userSchema.methods.createUser = (userData) => {
  const user = new userModel(userData);
  return user.save();
};

Now, we are almost done with this function. The only thing left is to check whether the user exists or not.

To do this, implement the id feature on the get user:

users/:userId

After that, you need to create a route and controller in locations /routes/users.route.js and /controllers/users.controller.js respectively:

const express = require("express");
const app = express.Router();
const UsersController = require("../controller/users.controller");
app.get('/users/:userId', [
    UsersController.getById
]);
module.exports = app;

exports.getById = (req, res) => {
   UserModel.findById(req.params.userId).then((result) => {
       res.status(200).send(result);
   });
};
And, now sum all this up by:
exports.getById = (req, res) => {
  UserModel.findById(req.params.userId).then((result) => {
    result = result.toJSON();
    delete result._id;
    delete result.__v;
    res.status(200).send(result);
  });
};

Upon execution, you will get a result like this:

{
   "firstName" : "miley",
   "lastName" : "cirus",
   "emailID" : "[email protected]",
   "password": "Y+XZEaR7J8xAQCc37nf1rw==$p8b5ykUx6xpC6k8MryDaRmXDxncLumU9mEVabyLdpotO66Qjh0igVOVerdqAh+CUQ4n/E0z48mp8SDTpX2ivuQ==",
   "permissionLevel": 1,
}

It is important to note that the hashed password has been shown up here for understanding purposes only.

You should never show the password irrespective of hashing. Similar to the create operation, we will implement the PATCH functionality also.

For this, we need to use a route /users/:userid in which changed fields will be sent. Hence, our code needs to look something like this:

exports.patchById = (req, res) => {
  if (req.body.password) {
    let salt = crypto.randomBytes(16).toString("base64");
    let hash = crypto
      .createHmac("sha512", salt)
      .update(req.body.password)
      .digest("base64");
    req.body.password = salt + "$" + hash;
  }
  const user = new UserModel({ _id: req.params.userId, body: req.body });
  user.patchUser(req.params.userId, req.body).then((result) => {
    res.status(204).send({});
  });
};

Here, we have used the standard HTTP code 204 to indicate the successful completion of a request for NodeJS API.

To patch some request, we need to include the following code:

userSchema.methods.patchUser = (id, userData) => {
  return new Promise((resolve, reject) => {
    userModel.findById(id, function (err, user) {
      if (err) reject(err);
      for (let i in userData) {
        user[i] = userData[i];
      }
      user.save(function (err, updatedUser) {
        if (err) {
          return reject(err);
        }
        resolve(updatedUser);
      });
    });
  });
};

exports.list = (req, res) => {
  let limit =
    req.query.limit && req.query.limit <= 100 ? parseInt(req.query.limit) : 10; let page = 0; if (req.query) { if (req.query.page) { req.query.page = parseInt(req.query.page); page = Number.isInteger(req.query.page) ? req.query.page : 0; } } const user = new UserModel(); user.list(limit, page).then((result) => {
    res.status(200).send(result);
  });
};

userSchema.methods.list = (perPage, page) => {
  return new Promise((resolve, reject) => {
    userModel
      .find()
      .limit(perPage)
      .skip(perPage * page)
      .exec(function (err, users) {
        if (err) {
          reject(err);
        } else {
          resolve(users);
        }
      });
  });
};

Now, the final list response will look like this:

[

   {

          "firstName" : "miley",

   "lastName" : "cirus",

   "emailID" : "[email protected]",

       "password": "z4tS/DtiH+0Gb4J6QN1K3w==$al6sGxKBKqxRQkDmhnhQpEB6+DQgDRH2qr47BZcqLm4/fphZ7+a9U+HhxsNaSnGB2l05Oem/BLIOkbtOuw1tXA==",

       "permissionLevel": 1,

       "id": "5b02c5c84817bf28049e58a3"

   },

   {

       "firstName": "Mickey",

       "lastName": "Harry",

       "emailId": "[email protected]",

       "password": "wTsqO1kHuVisfDIcgl5YmQ==$cw7RntNrNBNw3MO2qLbx959xDvvrDu4xjpYfYgYMxRVDcxUUEgulTlNSBJjiDtJ1C85YimkMlYruU59rx2zbCw==",

       "permissionLevel": 1,

       "id": "5b02d038b653603d1ca69729"

   }

]

At last we are left with implementing the DELETE functionality in our program in /users/:userId..

The code responsible for this is stated below:

exports.removeById = (req, res) => {
  const user = new UserModel({ _id: req.params.userId });
  user.removeById(req.params.userId).then((result) => {
    res.status(204).send({});
  });
};

Similar to the createuser functionality, we have used the HTTP code 204 here also. With the inclusion of error conditions, our final code will be:

userSchema.methods.removeById = (userId) => {
  return new Promise((resolve, reject) => {
    userModel.remove({ _id: userId }, (err) => {
      if (err) {
        reject(err);
      } else {
        resolve(err);
      }
    });
  });
};

Finally, the user part of the module is over for now. But we will get to back it after learning the concepts of validation and permissions.

Creating An Auth Module

In an author module, we create a temporary token whenever the system encounters an authorized user.

When the entered email id and password are matched, a response in the name of JWT is being generated for NodeJS API. It prevents the hassle of recursive authentication.

The code of this module begins with creating an endpoint:

{

   "emailID" : "[email protected]",

   "password" : "testcasepwd"

}

After this, the user is validate via /middlewares/verify.user.middleware.js:

const crypto = require("crypto");
const UserModel = require("../models/users.model");
exports.isPasswordAndUserMatch = (req, res, next) => {
  UserModel.find({ emailID: req.body.emailID }).then((user) => {
    if (!user[0]) {
      res.status(404).send({});
    } else {
      let passwordFields = user[0].password.split("$");
      let salt = passwordFields[0];
      let hash = crypto
        .createHmac("sha512", salt)
        .update(req.body.password)
        .digest("base64");
      if (hash === passwordFields[1]) {
        req.body = {
          userId: user[0]._id,
          email: user[0].email,
          permissionLevel: user[0].permissionLevel,
          provider: "email",
          name: user[0].firstName + " " + user[0].lastName,
        };
        return next();
      } else {
        return res.status(400).send({ errors: ["Invalid email or password"] });
      }
    }
  });
};

const crypto = require("crypto");
const jwt = require("jsonwebtoken");
exports.login = (req, res) => {
  try {
    let refreshId = req.body.userId + jwtSecret;
    let salt = crypto.randomBytes(16).toString("base64");
    let hash = crypto
      .createHmac("sha512", salt)
      .update(refreshId)
      .digest("base64");
    req.body.refreshKey = salt;
    let token = jwt.sign(req.body, jwtSecret);
    let b = new Buffer(hash);
    let refresh_token = b.toString("base64");
    res.status(201).send({ accessToken: token, refreshToken: refresh_token });
  } catch (err) {
    console.log(err);
    res.status(500).send({ errors: err });
  }
};

Now, we need to create a route that initializes the required middleware in /routes/auth.routes.js:

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

const VerifyUserMiddleware = require("../middlewares/verify.user.middleware");
const AuthorizationController = require("../controller/authorization.controller");
app.post("/auth", [
  [VerifyUserMiddleware.isPasswordAndUserMatch],
  [AuthorizationController.login],
]);

module.exports = app;

The response will contain the generated JWT in the accessToken field:

{

   "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI1YjAyYzVjODQ4MTdiZjI4MDQ5ZTU4YTMiLCJlbWFpbCI6Im1hcmNvcy5oZW5yaXF1ZUB0b3B0YWwuY29tIiwicGVybWlzc2lvbkxldmVsIjoxLCJwcm92aWRlciI6ImVtYWlsIiwibmFtZSI6Ik1hcmNvIFNpbHZhIiwicmVmcmVzaF9rZXkiOiJiclhZUHFsbUlBcE1PakZIRG1FeENRPT0iLCJpYXQiOjE1MjY5MjMzMDl9.mmNg-i44VQlUEWP3YIAYXVO-74803v1mu-y9QPUQ5VY",

   "refreshToken": "U3BDQXBWS3kyaHNDaGJNanlJTlFkSXhLMmFHMzA2NzRsUy9Sd2J0YVNDTmUva0pIQ0NwbTJqOU5YZHgxeE12NXVlOUhnMzBWMGNyWmdOTUhSaTdyOGc9PQ=="

}

So, this is how this token will be used inside the authorization header to authenticate the user.

Creating Permissions & Validations Middleware

When it comes to managing a system, the role, and limitations of people handling the system come into the picture.

This is where the point of permissions and validations arises. The first thing we should define is who can use the user’s resources.

Let’s begin with creating a middleware that can validate a user whenever a valid JWT is used.

The path used by us is /middlewares/auth.validation.middleware.js and includes the following code:

const jwt = require("jsonwebtoken");
exports.validJWTNeeded = (req, res, next) => {
  if (req.headers["authorization"]) {
    try {
      let authorization = req.headers["authorization"].split(" ");
      if (authorization[0] !== "Bearer") {
        return res.status(401).send();
      } else {
        req.jwt = jwt.verify(authorization[1], secret);
        return next();
      }
    } catch (err) {
      return res.status(403).send();
    }
  } else {
    return res.status(401).send();
  }
};

Similar to the earlier cases, we will again make use of HTTP codes to handle errors:

  • Code 401 in case of an invalid request
  • When a valid request is observed with an invalid token, or valid token without the permission, the code used will be 403.

Hence, the middleware will have the following code:

exports.minimumPermissionLevelRequired = (required_permission_level) => {
  return (req, res, next) => {
    let user_permission_level = parseInt(req.jwt.permissionLevel);
    let user_id = req.jwt.user_id;
    if (user_permission_level && required_permission_level) {
      return next();
    } else {
      return res.status(403).send();
    }
  };
};

A user module should also have an authentication middleware and this can be done by creating /routes/users.route.js:

app.post('/users', [

   UsersController.insert

]);

app.get("/users", [
  ValidationMiddleware.validJWTNeeded,
  PermissionMiddleware.minimumPermissionLevelRequired("PAID"),
  UsersController.list,
]);
app.get(
  "/users/:userId",
  ValidationMiddleware.validJWTNeeded,
  PermissionMiddleware.minimumPermissionLevelRequired("FREE"),
  [UsersController.getById]
);
app.patch(
  "/users/:userId",
  ValidationMiddleware.validJWTNeeded,
  PermissionMiddleware.minimumPermissionLevelRequired("FREE"),
  [UsersController.patchById]
);
app.delete(
  "/users/:userId",
  ValidationMiddleware.validJWTNeeded,
  PermissionMiddleware.minimumPermissionLevelRequired("ADMIN"),
  [UsersController.removeById]
);

So, the designing part is all over now. The only step left in making our Node JS RESTful API is testing which is continued in the next step.

Routing & Testing

In the case of testing, the best method believed is to include code tests with proper error reporting. But the options available in a third-party solution are more convenient.

Here, we will make use of a free third-party platform called Insomnia. This acts as an application and helps us determine the performance of the NodeJS API.

To begin with, the testing process, let us first create a user by using the POST action.

{

  "firstName" : "miley",

   "lastName" : "cirus",

   "emailID" : "[email protected]",

   "password" : "testcasepwd"

}

When you pass appropriate data, the API will respond with the user ID:

{

"id": "5b02c5c84817bf28049e58a3"

}

Now, prefix the accessToken, with Bearer, and add it to the request headers Under Authorization. This is an important step as it ensures no unnecessary requests return the HTTP code 401.

When a valid token is authorized, the project /users/:userId pushes the following response:

{

   "firstName" : "miley",

   "lastName" : "cirus",

   "emailID" : "[email protected]",

   "password": "jgfebfk=-/83729bfjf==$p8b5ykUx6xp764g74yu3rb4f34ggjksfnsjfyefo89urejbr44ugbfumU9mEVabyLdpotO66Qjh0igVOVerdqAh+CUQ4n/wefo47018hf034fh1sbue==",

   "permissionLevel": 1,

   "id": "5b02c5c84817bf28049e58a3"

}

So, all the fields are working fine. But do not forget to hide the hatched password in your program.

With the completion of this, we will now work on extracting the list of users. If you get a 403 response, this means the user does not hold the right to reach the endpoint.

With the use of MongoDB, we can manually change the permissionLevel of users and generate a new JWT. This takes to a more finished response:

{

{

“_Id”: “ebfhjy4riefor8e7eufber48gyuf”,   

"firstName" : "miley",

   "lastName" : "cirus",

   "emailID" : "[email protected]",

   "password": "jgfebfk=-/83729bfjf==$p8b5ykUx6xp764g74yu3rb4f34ggjksfnsjfyefo89urejbr44ugbfumU9mEVabyLdpotdfbui3y2rbukewfi0efnrqAh+CUQ4n/wefo47018hf034fh1sbue==",

   "permissionLevel": 7,

“__v”: 0,

   "id": "5b02c5c84817bf28049e58a3"

}

}

Now, we will send a PATCH request to check the update function via /users/:userId endpoint:

{

   "firstName" : "mickey",

   "lastName" : "harry",

}

This API is capable of sending a DELETE request to /users/:userId followed by a 204 HTTP code response as confirmation. To check the deletion of users, you can list the existing users from /users/.

Building A Node.js API

In this section, we will build a NodeJS API that is similar to the backend of a notes app such as Google Keep. It will perform all the basic CRUD actions.

Setup

First of all, install the latest version of node.js. Then, run the npm init to set up all the resources. In the following code, we will use MongoDB and Express framework.

In addition to this, we recommend you to install Nodemon as a dev dependency. Because it is highly useful in restarting the server every time the file changes.

After this, add the following script to package.json:

{
  "name": "node-rest-api-demo1",
  "version": "1.0.0",
  "description": "A node.js sample project for understanding the basics of API",
  "main": "server.js",
  "scripts": {
    "dev": "nodemon server.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.15.2",
    "express": "^4.14.0",
    "mongodb": "^2.2.16"
  },
  "devDependencies": {
    "nodemon": "^1.11.0"
  }
}

So, the setup is complete now. And we are all set to build your Node JS API.

The Server

To set the server, start calling all the dependencies:

// server.js

const express = require('express');

const MongoClient  = require('mongodb').MongoClient;

const bodyParser   = require('body-parser');

const app          = express();

Now, specify a port to let the app listen to the HTTP requests:

// server.js

const port = 8000;

app.listen(port, () => {  console.log('SERVER IS ON ' + port);});

At this point, if you run the dev dependency or nodejs server.js, the console will show the port number.

This indicates that our server is live but incomplete. It requires another great bunch of things in it to work. These things are listed in the forthcoming steps.

CRUD Routes

CRUD

CRUD stands for Create, Read, Update, and Delete. You need to create each route for every functionality. But, how do we test whether our API is working fine or not?

For that, the internet has several platforms that allow you to test your Node.js API by sending sample requests.

One such application is Postman that is widely used to make HTTP requests. You can install this software as it will be used as a part of the next steps.

Read Also: Guide On How To Use Node JS API

Super Organized

In the case of small apps, it is not advised to put all the routes in a common .js file. Hence, we suggest you design different folders for each function.

This helps in making the reading process easy and reliable. Arrange the files in a hierarchical manner as:

root > app > routes > index.js and note_routes.js

You can also use the following code to arrange the directories:

mkdir appcd appmkdir routescd routestouch index.jstouch note_routes.js

The First Route

Let us begin by creating a create route. But before that, we would first set up the desired infrastructure from Express:

// routes/note_routes.js

module.exports = function(app, db) {

};

Now, import the above function to index.js:

// routes/index.js

const noteRoutes = require('./note_routes');

module.exports = function(app, db)

{  

noteRoutes(app, db);  

// Other route groups could go here, in the future

};

Now, import it to server.js:

// server.js

const express        = require('express');

const MongoClient    = require('mongodb').MongoClient;

const bodyParser     = require('body-parser');

const app            = express();

const port = 8000;

require('./app/routes')(app, {});

app.listen(port, () => {  console.log('SERVER IS ON ' + port);});

Please remember that we have not used any database here. An argument is just an empty object. But, with the completion of all the above codes, we are now ready to build the actual CREATE route.

// note_routes.js
module.exports = function (app, db) {
  app.post("/notes", (req, res) => {
    // create your note here.
    res.send("welcome");
  });
};

Now, we will test the code by sending a POST request via Postman. Upon successful execution, the console will reflect ‘welcome’. And this proves the success of your route.

Request Parameters

Postman is very useful in requesting parameters. Simply go to the body tab, and add the key-value pairs of your choice. After that, modify the note_routes.js body as shown below:

module.exports = function (app, db) {
  app.post("/notes", (req, res) => {
    console.log(req.body);
    res.send("Hi");
  });
};

The default Express framework of node.js cannot execute the encoded URL. Thus, if you will run the above code, then the result will be ‘undefined’.

Therefore, to make it work the right way, you need to use the pre-installed body-parser package:

// server

const express        = require('express');

const MongoClient    = require('mongodb').MongoClient;

const bodyParser     = require('body-parser');

const app            = express();

const port = 8000;

app.use(bodyParser.urlencoded({ extended: true }));

require('./app/routes')(app, {});

app.listen(port, () => {  console.log('We are live on ' + port);});

Now, the only thing left in setting up your route is the database. You can establish a Mongo Database through mLab.

After this, create a .js file in the root directory of your project:

mkdir config cd configtouch db.js

Now, add the url of your choice:

module.exports = {  url : enter the url};
End the above code by adding the mongoclient setup:
// server.js
const express = require("express");
const MongoClient = require("mongodb").MongoClient;
const bodyParser = require("body-parser");
const db = require("./config/db");
const app = express();
const port = 8000;
app.use(bodyParser.urlencoded({ extended: true }));
MongoClient.connect(db.url, (err, database) => {
  if (err) return console.log(err);
  require("./app/routes")(app, database);
  app.listen(port, () => {
    console.log("SERVER IS ON " + port);
  });
});

People who use the 3.0+ version of MongoDB must do the following modifications:

// server.js
const express = require("express");
const MongoClient = require("mongodb").MongoClient;
const bodyParser = require("body-parser");
const db = require("./app/config/db");
const app = express();
const port = 8000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
MongoClient.connect(db.url, (err, database) => {
  if (err) return console.log(err);
// Make sure you add the database name and not the collection name  
  require("./app/routes/")(app, database);
  app.listen(port, () => {
    console.log("SERVER IS ON " + port);
  });
});

By doing this, we are done with the route making step.

Adding To Database

Since we are building a Node.Js API for note-making purposes, the data needs to be stored in the form of a db argument. To access them, follow:

db.collection('notes')

In this database, you can easily create and save a note into the collection of your choice:

const note = { 
text: req.body.text, 
title: req.body.title}  
db.collection('notes').insert(note, (err, results) => {}

Just like any other app, our Node.JS API should be able to send a message. The message will indicate whether a note has been created or an error has occurred. To do so, follow the below code:

// note_routes.js
module.exports = function (app, db) {
  const collection = app.post("/notes", (req, res) => {
    const note = {
      text: req.body.text,
      title: req.body.title,
    };

    db.collection("notes").insert(note, (err, result) => {
      if (err) {
        res.send({ error: "An error has occurred" });
      } else {
        res.send(result.ops[0]);
      }
    });
  });
};

In order to check the functioning of Node.JS API, try sending a POST request with Postman. If everything goes well, the response will look something like this:

{        

“text”: “This is my first note.”,

“title”: “A new note”,

“_ID”: “38756473grhebf48y2fb87342”

}

The READ Route

Now, we will try to read our created notes with the help of localhost:8000/notes/585182bd42ac5b07a9755ea3.

Also Read: Node.js vs Java The Ultimate Guide

// note_routes.js

module.exports = function(app, db)

{  

app.get('/notes/:id', (req, res) => {      });

  app.post('/notes', (req, res) =>

{    

const note = {

text: req.body.body,

title: req.body.title };    

db.collection('notes').insert(note, (err, result) =>

{      

if (err)

{         

res.send({ 'error': 'An error has occurred' });       

}

else

{        

res.send(result.ops[0]);      

}    

});  

});};

Now, call the database:

// note_routes.js
module.exports = function (app, db) {
  app.get("/notes/:id", (req, res) => {
    const details = { _id: req.params.id };
    db.collection("notes").findOne(details, (err, item) => {
      if (err) {
        res.send({ error: "An error has occurred" });
      } else {
        res.send(item);
      }
    });
  });
  app.post("/notes", (req, res) => {
    const note = {
      text: req.body.body,
      title: req.body.title,
    };
    db.collection("notes").insert(note, (err, result) => {
      if (err) {
        res.send({ error: "An error has occurred" });
      } else {
        res.send(result.ops[0]);
      }
    });
  });
};

To fix the ID of MongoDB, implement the following code:

// note_routes.js

var ObjectID = require('mongodb').ObjectID;

module.exports = function(app, db)

{  app.get('/notes/:id', (req, res) =>

{    

const id = req.params.id;    

const details = {

'_id': new ObjectID(id) };    

db.collection('notes').findOne(details, (err, item) => {      

if (err)

{        

res.send({'error':'An error has occurred'});      

}

else

{        

res.send(item);      

}     

});  

});

app.post('/notes', (req, res) =>

{    

const note = {

text: req.body.body,

title: req.body.title };    

db.collection('notes').insert(note, (err, result) =>

{      

if (err)

{         

res.send({ 'error': 'An error has occurred' });       

}

else

{        

res.send(result.ops[0]);      

}    

});  

});};

The DELETE Route

Deletion is very much similar to find. The only difference lies in the main function. In case of deletion, we use the remove function instead of findone.

// note_routes.js
app.delete("/notes/:id", (req, res) => {
    const id = req.params.id;
    const details = {
      _id: new ObjectID(id),
    };
    db.collection("notes").remove(details, (err, item) => {
      if (err) {
        res.send({ error: "An error has occurred" });
      } else {
        res.send("entered note ' + id + ' deleted!");
      }
    });
  });

The UPDATE Route

Up to now, we are almost done with all types of functionalities. Another useful route used in note-making API is UPDATE. It is a mixture of READ and CREATE.

Because this takes place in an existing note and performs new operations also.

// note_routes.js
app.put("/notes/:id", (req, res) => {
    const id = req.params.id;
    const details = { _id: new ObjectID(id) };
    const note = { text: req.body.text, title: req.body.title };
    db.collection("notes").update(details, note, (err, result) => {
      if (err) {
        res.send({ error: "An error has occurred" });
      } else {
        res.send(note);
      }
    });
  });

It is important to note here that the PUT request will nullify the respective fields in a note if the body or title is missing. But, it is possible to add some logic to update the fields as per the components of a request.

How To Use An API With Node.js?

In the above sections, we have learned How to Use NodeJS for creating or building a REST API. Along with creation and building, it is equally important to understand the mechanism of Node.js Call REST API.

This is something that has brought us into this section. But before that make sure you have the latest node.js software installed in your system and an active internet connection.

Setting Up An RapidAPI Account

The foremost step involved in setting up a RAPID API account is a simple sign up. You can sign up on the website for free using google/Github/Facebook. Otherwise, you can create a new email-ID.

Subscribe To An API

RAPID API offers three plans like Basic, Pro, Ultra. You can choose any of the three plans at your convenience. Kindly visit the official website to know more about it.

For this project, we have subscribed to the basic plan. Under this, we will use the astrology horoscope to call the API.

Setting Up Project

To set up a project, run the following code in a new terminal:

$ mkdir node-api-call

$ cd node-api-call

$ npm init -y

This creates a terminal into the new directory. Inside which we need to initialize our Node.js API project. To support this, install axios:

npm install --save axios

Create the file app.js and astrology.js at the root of the project. The project structure is;

Add API Call

The RapidAPI is popular because of its dashboard support Node.js Calling REST API. On the leftmost corner, click on the endpoint.

After that, you get a dashboard in the center part that displays the definition and parameters of the endpoint.

From the top-right drop-down menu, you can use the Node (Axios) library. Use the following code to under the astrology.js module:

const axios = require("axios");

const BASE_URL = `https://astrology-horoscope.p.rapidapi.com`

module.exports = {

    getCompatibility: (Name1, birthdate1, Name2, birthdate2) => axios({

        method:"POST",

        url : BASE_URL + `/zodiac_compatibility/result`,

        headers: {

            "content-type":"application/x-www-form-urlencoded",

            "x-rapidapi-host":"astrology-horoscope.p.rapidapi.com",

            "x-rapidapi-key": "yourapikey"

        },

        params: {

            mystic_dob: Name1,

            mystic_dob2: birthdate1,

            mystic_name: Name2,

            mystic_name2: birthdate2,

        }

    })

}

Here, we have used the getCompatibility Axios API call. It takes four arguments as name1, birthdate1, name2, birthdate2. In place of “yourapikey”, use an API-key value of your own dashboard.

Read also: Express vs Koa: Which Node.js Framework Is Best For You?

Make Asynchronous API Call

For making an asynchronous API call, you need to implement the following code:

const AstrologyAPI = require('./astrology')

const asyncApiCall = async () => {

    const response = await AstrologyAPI.getCompatibility('Austin', '1987-05-21', 'Taylor', '1989-09-27')

    console.log(response.data.data.Compatibility.heading)

    console.log(response.data.data.Compatibility)

}

asyncApiCall()

The first line of code imports objects from astrology.js. In continuation of this, an asynchronous function calls getCompatibility. This pulls out the data from the response object. Now, enter the nodejs app.js.

An Excellent Match

{

  heading: 'An Excellent Match',

  details: 'Both the Gemini and the Libra are typical air signs and this should make for similar mental characteristics. Both of them have a strong sense of personal freedom, and more importantly, give each other the required space in a relationship. They both desire constant change and share a very active social life. A Gemini and a Libra couple will indeed be extremely popular in the party circuit. However, one thing to be noted is that Libra is not domestic minded, and this might create bitterness especially when the Gemini is in a mood to settle down. Libra however profusely praises his/her lover, and this pleases the Gemini who loves attention. In the bedroom, Libra is sexually active and fulfills all Gemini fantasies. At work, both of them should be good colleagues as well as friends, and both have a strong marketing ability.'

}

Congratulations! You have just made a brilliant Node.js Call REST API.

Conclusion

By this step-by-step guide, we discussed the various aspects of a node.js API. The simple explanation of an API and its building will be very useful for the node.js developers.

We assume that you had a good learning experience understanding the uses of various frameworks such as Express and MongoDB.

The last section provides another quick guide on How to Use NodeJS on RAPID API. All of this will surely help you to build an efficient and interactive application on the node.js platform .

We hope you had a great experience reading this article and it will help any Node JS Development Company in the long run. Thank You.!You can Connect Now.

Chintan Gor

CTO, eSparkBiz

Enthusiastic for web app development, Chintan Gor has zeal in experimenting with his knowledge of Node, Angular & React in various aspects of development. He keeps on updating his technical know-how thus pinning his name among the topmost CTO's in India. His contribution is penned down by him through various technical blogs on trending tech. He is associated with eSparkBiz from the past 14+ years where one can get premium services.