Programming

How to Create Node.js API in 30 Minutes (Guide Inside)

create node js api guide

It’s always intimidating for the beginners to get started with a basic nodejs CRUD.  But before start developing your Node.js API, you must know the answers of the following questions:

What is node js?

How can you run node JS?

What is API and how it works?

What is the REST API?

Let’s quickly get some understanding about these prerequisites; otherwise, you will not be able to understand this article. First, we will help you to get some prior knowledge regarding JavaScript, Node.js, API, and REST API.

Many of you may already have some experience with JavaScript but for those who are new with this term, must know the basics of JavaScript.

JavaScript is a lightweight computer programming language, commonly used on the web pages. It is embedded in HTML code and allows client-side script to interact with the user and make dynamic pages.

The JavaScript is known as Client-side Scripting Language. You can insert some JavaScript code in an ordinary web page. As soon as the browser loads the page, the built-in interpreter inside the browser will find and read the JavaScript code and run it accordingly.

After understanding JavaScript, it’s time to dig deeper to get some insights about other relevant prerequisites so, let’s explore more.

What is node js?

Node js, a JavaScript runtime that has everything you need to run a program written in JavaScript. It is developed on Chrome’s V8 JavaScript engine, and as of now, it is considered as an efficient runtime and uses an event-driven, non-blocking I/O model that makes it super lightweight.

Node js is developed by the original JavaScript developers, who wanted to extend the JavaScript and enable it to run on your machine as a standalone application.

It allows you to do much more with the JavaScript than just creating the websites interactive. Today, JavaScript is much more efficient and can do other scripting languages, same as Python.

Both browser JavaScript and Node.js run on the V8 JavaScript runtime engine. The V8 JavaScript runtime engine takes your JavaScript code and alters it into a faster machine code that computer can run without even interpreting.

One of the most obvious reasons that people rely on the Node is that they don’t have to learn more than one language. They can learn one language, JavaScript and utilize it to develop every part of the full stack applications.

Since Node is an asynchronous event-driven runtime; therefore, it provides robust performance specifically for those applications which require various small tasks done in parallel hence allows for high concurrency.

Keep in mind that for highly trafficked API endpoints, high concurrency is a typical requirement. Developing backend applications with Node makes it easy to scale different types of applications.

How can you run node JS?

It’s easy to run Node.js; you need to run a command on CLI (command line interface).

Why use Node.js Framework?

The node.js framework is used for developing efficient, scalable Node.js server-side applications. There are many reasons to use this framework over other frameworks. Few benefits of Node.js framework are:

  • It is ultra-fast and highly scalable, e.g., PayPal, Uber, Netflix
  • Requires less line of codes
  • Builds faster with fewer resources
  • 40% fewer files
  • Faster response
  • 2x request/sec

Large ecosystem of the open source library

(front + back) JavaScript

What is API and How it Works?

API or application programming is a set of definitions and protocols for building and integrating application software. It serves as a channel to access the information between an enterprise and applications that use its resources.

Such resources are located on a host database system.  We will be discovering the MongoDB, a No SQL database system.

Web API’s plays a significant role in web development and serves with a well-documented structure of data flow either to or from the server.

To make the API concept more straightforward, we can say that the API is somehow involved in the underlying implementation of information generation but only shows the required data to developers.

You can better understand API when you will create it. To create an API, you can use server-side JavaScript technology, Node.js.

Node.js is super flexible, and it’s easy to create an API by calling a send ( ) on the response object with the parameters passed in as an object.

Types of APIs

No matter, you are looking to develop the best game apps or want to execute any other project what you need is to pick up the right API.  Here are a few of the types of available APIs.

1. Production API

Every app that you create needs a production API. It acts as the server that involves sending real data from the database, updates it, and enforces all the permissions and business logic. It controls permissions, which means it does not allow a user to update information which he does not suppose to plus, it makes sure that the data never returns to the users who shouldn’t see it.

2. Simple Object Access Protocol (SOAP) API

SOAP API enables you to create your own API. SOAP API comprises official standards because it is a protocol itself. SOAP API allows the sender to build a message route that is based on the logical services that must be applied to the message in between its way to the destination.  SOAP API provides secure and compliant connections, control access, reliable delivery, and supports the dynamic service discovery.

Also, there are more APIs available, including REST API, internal APIs, and external APIs. But, REST API is easy to use because it has no official standards. Therefore, we are explaining the REST API in detail.

3. What is the REST API?

REST stands for (Representational State Transfer). Rest API is designed to leverage present protocols.  REST API describes the set of functions that developers required to perform the request and receive responses such as GET, POST, and DELETE data through HTTP protocol.

How do REST APIs work?

REST API forms a series of small modules by breaking down a transaction. Every module reports a specific underlying part of the transaction. Such small modules help developers with a lot of flexibility, but, meanwhile, it is challenging for developers to design everything from the start.  Presently, the most popular modules are AmazonS3 Cloud Data Management Interface (CDMI) and OpenStack Swift.

With REST API, you can access networked components that are your request access to a black box whose details for implementation are not clear.

REST is a good go for cloud applications because it is presumed that all calls in REST are stateless, which means nothing can be retained by the RESTful service between executions.

Stateless components can be redeployed freely if something fails to work; these components can scale to hold load changes. This happens because any request can be directed to any instance of a component; there is no need to save anything to keep things remember by the next transaction.

REST is the most preferred choice for webs. But, the REST model also works well for the cloud services since connecting to service with an API depends on how the URL is decoded.

In addition, future expectation is that cloud computing and microservices are great for making RESTful API design.

As of now, you have understood the basic concepts of is node js, node js functions, API, REST API, and their working process. Now, we will help you to know how you can build a node.js API.

Since you are about to start making your API, so it has to be as much efficient in terms of overall performance. Because you are selecting Node.js platform for your API, so relax because it’s an excellent selection.

Benefits of using Node.js

There are many benefits to select Node.js as your API platform; therefore, before starting your journey first get some insights about the benefits which you can achieve:

1. The Fast Suite

Companies always search for the speed on which they can run the Node.js functions.  Node.js operates on the V8 engine that uses JavaScript into native machine code and runs at a faster pace. Moreover, Node.js saves you from troubles involve in forming separate threads because it uses a single thread that takes care of all the asynchronous I/O operations.

It helps web applications to quickly perform significant actions with a suite, including reading, writing to the database, network connections, or file system.

2. Data Streaming

HTTP request and response are considered as two separate events in web platforms, but in reality, they both are data streams. With Node.js, data stream features can be utilized to the fullest for creating few of the best attributes such as processing files at the loading time. This can minimize the overall processing time once data comes in stream forms. It is also deployed for real-time video or audio recording.

3. Node.js Runs Everywhere

JavaScript works on both browser and server; all credit goes to Node.js. It is super flexible to use, and it runs similarly without any snag.  It is easier for enterprises to shift from browser to server through Node.js code migration feature.

Since Node.js has all the features to deliver excellent performance; therefore, you can get started with Node.js API development.

Now, we will guide you to quickly build a Node.js API that you can use as the foundation of any application.

Keep in mind that before start building a Node.js API,  you can use ES6 that is easy to use. For this tutorial, you will need to create a back-end skeleton for a note-taking application e.g., Google Keep.

There are various node.js frameworks available, like Hapi and Sais. These Node.js API with the express framework are simple to use and require minimum coding by giving routing support while providing maximum flexibility than other frameworks.

Before starting your journey with writing, Node.js API don’t forget to install the latest node version using the command mentioned below:

sudo apt-get install nodejs

Moreover, while working on this, you also need to install npm (node package manager) to install further modules used in the API.

sudo apt-get install npm

Node-v and npm-v will show the installed NPM on your machine along with the NODE version. Here, we are using the Mongo database. You can check your installed version of MongoDB using mongo-version.

After that, you need to set up a database in MongoDB with your chosen name. In the mentioned example below, the name is notes_blog.

In this example, an application is created to display, add, delete, and update notes. To get started with the application, you can create a folder and name it manage_notes. Place this folder in the terminal and give npm init.

Now, several questions will appear, you can press enter to initialize your application with the package.json file.

Simply paste the code mentioned below in the package.json and save it in the terminal run “npm install.” This code will install all the packages that are defined in the dependencies section of package.json.

package.json

{

“name”: “blog2”,

“version”: “1.0.0”,

“description”: “”,

“main”: “index.js”,

“scripts”: {

“test”: “echo \”Error: no test specified\” && exit 1″

},

“author”: “”,

“license”: “ISC”,

“dependencies”: {

“mongoose”: “~5.1.8”

}

}

Now create another folder in the root application and name it “DB”. Create a file inside that folder with the following content. Your created file will connect to the Mongo database while holding the code. Paste the code below in the mongoose.js.

const mongoose = require(‘mongoose’);

mongoose.Promise = global.Promise;

let db_url = ‘mongodb://localhost:27017/notes_blog’

mongoose.connect(db_url)

.then(() => {

console.log(`mongoose connected to: ${db_url}`)

}).catch((e) => {

console.log(`mongoose connection error: ${e}`)

})

module.exports.mongoose = mongoose;

You can see the Mongoose module here. It is used to interact with the database. The main purpose of the interaction is to create a connection to the mongo database.

Now, it’s time to establish your application’s starting point which you can do by creating a file in the root folder of your application and name the file as server.js. Paste the following code.

The express and body-parser modules will be imported. bodyParser.json(), bodyParser.urlencoded() are using as the middlewares of body-prser module. It provides access for requesting objects, transforming objects and also exposes it to the req.body object that can also be accessed in our routes as well.

Server.js

const express = require(‘express’);

const bodyParser = require(‘body-parser’);

const app = express();

const port = 3000;

app.use(bodyParser.json());

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

const mongoose = require(“./db/connect_mongo”);

const notesRoute = require(‘./routes/notes.route’);

app.use(‘/’, notesRoute);

app.listen(port, () => {

console.log(‘We are live on ‘ + port);

});

As an instance of the Express framework, initialize your app, and add the body-parser middleware through express’s app.use() method. Moreover, to establish a connection to DB, you will need a “connect_mongo.js” file before requesting to listening to the port. Then you can make the app to listen to the port 3000 using app.listen() function.

Here is an example:

In this example, M denotes model, holding function code of the database. V is representing the view. C stands for the controller, acting as the buffer between view and model. It also accepts the incoming request and sequentially call the corresponding model function, process it, and deliver back the response to view.

Here, you can find some additional route files inside the folder name routes; these files help to resolve the requested URL from view to a specific controller.

Now create another file and name it notes.model.js in a new folder called to model and paste the code mentioned below,

const mongoose = require(“mongoose”);

let notesSchema = new mongoose.Schema({

“title”: {type: String},

“dscription”:{ type: String}

});

// A function to fetch from the notes collection based on the query

notesSchema.statics.fetchNotes = function fetchNotes(nodeTitle) {

return new Promise((resolve, reject) => {

this.find()

.then((existingNotes) =>{

return resolve(existingNotes);

})

.catch((err) =>{

return reject(err);

});

});

};

// A function to fetch particular note from the notes collection based on the Id

notesSchema.statics.fetchNoteById = function fetchNotes(nodeId) {

return new Promise((resolve, reject) => {

let query = { “_id”:nodeId };

this.find(query)

.then((note) =>{

return resolve(note);

})

.catch((err) =>{

return reject(err);

});

});

};

// A function to save a note to the notes collection

notesSchema.statics.saveNote = function saveNote (newNote) {

return new Promise((resolve, reject) => {

Note.collection.save(newNote)

.then((savedNote) =>{

return resolve(savedNote);

})

.catch((err) =>{

return reject(err);

});

});

};

// A function to update a note with note_id

notesSchema.statics.updateNote = function updateNote (noteId, updatedNote) {

return new Promise((resolve, reject) => {

let query = { _id: mongoose.Types.ObjectId(noteId) };

Note.collection.findOneAndUpdate(query, updatedNote, {returnOriginal: false}) //returnOriginal: false will return the updated document

.then((updatedNote) => {

return resolve(updatedNote.value);

})

.catch((err) => {

return reject(err);

});

});

};

// A function to delete a note from notes collection with node_id

notesSchema.statics.deleteNote = function deleteNote(noteId){

let query = { “_id”: mongoose.Types.ObjectId(noteId) };

return new Promise((resolve, reject) => {

this.findByIdAndRemove(query)

.then(() =>{

return resolve();

})

.catch((err) =>{

return reject(err);

});

});

};

let Note = mongoose.model(“Note”, notesSchema, “notes”); //set collection name otherwise it forces a plural

module.exports = { Note };

notesSchema.statics.deleteNote = function deleteNote(noteId){

let query = { “_id”: mongoose.Types.ObjectId(noteId) };

return new Promise((resolve, reject) => {

this.findByIdAndRemove(query)

.then(() =>{

return resolve();

})

.catch((err) =>{

return reject(err);

});

});

};

let Note = mongoose.model(“Note”, notesSchema, “notes”); //set collection name otherwise it forces a plural

module.exports = { Note };

In this file, we will again need the Mongoose module then describe our structure of notes collection. This notes collection comprises two fields title and datatype description as a string. Other core functions including update, save, lists and delete notes to mongo database are also written in this file.

Establish another file and name it notes.controller.js in a new folder called controller with the code mentioned below;

let { Note } = require(“./../model/notes.model.js”);

exports.addNote = function (req, res) {

let newNote = {};

newNote.title = req.body.title;

newNote.description = req.body.description;

Note.saveNote(newNote)

.then((savedNote)=>{

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

})

.catch((err)=>{

res.send(err)

})

};

exports.displayNote = function (req, res) {

Note.fetchNotes()

.then((notes)=>{

if(notes.length > 0){

res.send(notes);

} else {

res.send(`No Notes to display`);

}

})

.catch((err)=>{

res.send(err)

})

};

exports.displayNoteById = function (req, res) {

let noteId = req.params.id

Note.fetchNoteById(noteId)

.then((notes)=>{

if(notes.length > 0){

res.send(notes);

} else {

res.send(`Note with id ${noteId} doesn’t exist`);

}

})

.catch((err)=>{

res.send(err)

})

};

exports.removeNote = function (req, res) {

let noteId = req.params.id

Note.deleteNote(noteId)

.then(()=>{

res.send(`Note successfully deleted`);

})

.catch((err)=>{

res.send(err)

})

};

exports.modifyNote = function (req, res) {

let noteIdToBeUpdated = req.params.id

let modifiedNote = req.body

Note.updateNote(noteIdToBeUpdated,modifiedNote)

.then((updatedNote)=>{

res.send(

{

mesage:”Note updated successfully”,

data:updatedNote

}

);

})

.catch((err)=>{

console.log(err);

res.send(err)

})

};

Next step for defining the application’s routes creates a file name it notes.route.js in a new folder called routes with the code below:

const express = require(‘express’);

const router = express.Router();

const notesController = require(‘../controller/notes.controller’)

router.post(‘/saveNote’, notesController.addNote);

router.get(‘/listNote’, notesController.displayNote);

router.get(‘/listNote/:id’, notesController.displayNoteById);

router.delete(‘/removeNote/:id’, notesController.removeNote);

router.put(‘/updateNote/:id’, notesController.modifyNote);

module.exports = router;

This file will need the controller file (notes.controller.js) that we mentioned above in the blog.

Don’t forget to add a notes.route.js file in server.js before the app.listen() function. As per the client URL request, the route is matched, and the corresponding controller method is called from here and sequentially request the particular model function, and the response gets back to the client side.

In the end, your structure must be looking like this:

manage_notes

node_modules

package.json

server.js

db

connect_mongo.js

controller

notes.controller.js

models

notes.model.js

routes

notes.route.js

Finally, save all these files and place the application folder in the terminal and enter “npm start.” Now you can find the server listening to the port 3000 as stated in the server.js file.  For testing the application, we will use an application called postman from where the HTTP request can be completed through query or body parameters.

Now start creating your own Node.JS API by applying the following CRUD operations,

  1. Testing the API’s In Postman
  2. Saving A Note
  3. Display A Note By Id
  4. Display All Notes
  5. Update A Note
  6. Delete A Note

In this blog, we tried to explain how to build a Node.js API under 3o minutes using REST APIs and CRUD operations. We hope that going through this blog helped you and you are all set to develop your next Node.js API.

 

About Author: Rameez Ramzan is an Assistant Manager – Digital Marketing at Cubix, a Washington based renowned game development company. He specializes in paid marketing, SEO and SMM and site audits to help sites perform better.

Click to comment

Leave a Reply

Your email address will not be published. Required fields are marked *

To Top