REST API with NodeJS and Express

In this tutorial, we will see why we should create our rest API in node.

Why REST API in Node?

Let’s go back to our traditional rest API system which is based on either blocking operation or threading. Suppose two concurrent requests occurs( r1 and r2), each of them require database operation. How it works in Node –

When the same concurrent request comes in node then it will register an event with its callback and move ahead it will not wait for query response for a particular request. So when r1 request comes then node’s event loop (yes there is an event loop in the node which serves this purpose.) register an event with its callback function and move ahead for serving r2 request and similarly register its event with its callback. Whenever any query finishes it triggers its corresponding event and execute its callback to completion without being interrupted.

Prerequisites for REST API in Node.

  1. Node
  2. NPM
  3. Express
  4. MongoDB

Installing Node and NPM — 

To get started, head over to https://nodejs.org and download the most stable release of NodeJS. Don’t download the latest version since it may contain bugs and features that could be removed from the final version. in the latest version of node now we get NPM package as well. To confirm the installation open your command prompt and try to execute the following commands.

node -v
npm -v

the first command will return the installed version of node and second command will return the installed version of npm. If you are getting both of them then the installation is correct and you can proceed further.

Starting on Node App:- 

  1. create a directory to hold your application, and make that your working directory.
mkdir myapp
cd myapp

2. Use the npm init command to create a package.json file for your application. 

npm init

The package.json file contains a couple of properties. First one is name which holds the name of the app, second is version which shows the version of your app, a description of your app, main that points to the entry point of your application. There’s also scripts, that can be run when you need to perform some repetitive tasks, authorname, licence, dependencies and devDependencies.

This command prompts you for a number of things, such as the name and version of your application. For now, you can simply hit RETURN to accept the defaults for most of them, with the following exception:

entry point: (index.js)

3. Installation of Express — 

Express — Express.js is a web application framework for Node.js, released as free and open-source software under the MIT License. It is designed for building web applications and APIs. 

Now install Express in the myapp directory and save it in the dependencies list. For example:

npm install express --save

Creating the app.

Now open index.js and write following code in it. what we are doing here? We are simply importing our express package and creating an instance of node app. then we are binding a simple listener to it at port 3000. Your app will now be accessible using http://localhost:3000,

var express = require("express");
var app = express();
app.listen(3000, () => {
console.log("Server running on port 3000");
});

But it is not meaningful. so let’s create a meaningful API. for that we need a database, right!

4. Installing MongoDB — 

MongoDB- MongoDB is a schemaless non-relational database that stores data in a JavaScript friendly format.

When interacting with a Mongo database, the best tool to use in NodeJS is Mongoose. Mongoose lets you define schemas and models for your data, and use the schema to execute common Mongo methods like find, findOne etc.

npm install mongoose body-parser — save

Body-parser enables your app to parse data from an incoming request like form data via urlencode. We need to import this to our app and use them. 

Add the following section in your index.js.

// Import Body parser
let bodyParser = require('body-parser');// Import Mongoose
let mongoose = require('mongoose');// Configure bodyparser to handle post requests
app.use(bodyParser.urlencoded({
extended: true
}));app.use(bodyParser.json());// Connect to Mongoose and set connection variable
//connect to mongodb instance where database is mydb
mongoose.connect('mongodb://127.0.0.1:27017/mydb')

Now, for example, we are creating an app in which we are setting a student profile is our database and later on, we will retrieve the value from the database. To save the data we will use POST API and for retrieving the data we will use GET API.

First, we will create a schema, a modal object of our Student object. create a file student.js.

let mongoose = require('mongoose')
let studentSchema = mongoose.Schema({
name: String,
class: String
}, { collection: 'students' })
let Student = mongoose.model('Student', studentSchema)module.exports = Student

Now import student.js in index.js and use Student object.

//save new student
app.post('/', (req, res, next) => {
//create new student using schema
let newStudent = new Student({
name: req.body.name,
marks: req.body.marks,
teachers: req.body.teachers
})
//save new student to db
newStudent.save((err, result) => {
if (err) { console.log(err) }
else { res.json(result) }
})
})
app.get('/', (req, res, next) => {
//use find() method to return all students
Student.find((err, result) => {
if(err) { console.log(err) }
else { res.json(result) }
})
})

Your whole index.js will look like — 

let express = require('express')
let bodyParser = require('body-parser')
let path = require('path')
let mongoose = require('mongoose')
//import Student Model from ./student.js
let Student = require('./student.js')
//initialize express app
let app = express()
//configure express app to parse json content and form data
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
//configure express app to serve static files
app.use(express.static(path.join(__dirname, 'public')))
//connect to mongodb instance where database is mydb
mongoose.connect('mongodb://127.0.0.1:27017/mydb')
//save new student
app.post('/', (req, res, next) => {
//create new student using schema
let newStudent = new Student({
name: req.body.name,
marks: req.body.marks,
teachers: req.body.teachers
})
//save new student to db
newStudent.save((err, result) => {
if (err) { console.log(err) }
else { res.json(result) }
})
})
app.get('/', (req, res, next) => {
//use find() method to return all students
Student.find((err, result) => {
if(err) { console.log(err) }
else { res.json(result) }
})
})
//listen on port 3000
app.listen(3000, () => {
console.log('Server listening on port 3000')
})

Now open your command prompt and run your node app.

node index.js

Now test your API using POSTMAN. – https://www.getpostman.com/

That’s All.

What we did over here?

  1. We learned how to install node, npm, express, and MongoDB.
  2. We learned how to connect MongoDB with our express app (using mongoose)
  3. Finally, we learn how to write a REST API using Node and Express.

We here at HYR Global Source have a very deep understanding of web development growing process, In the last 5 years, we have worked with various clients and students, and helped them in creating better products and career respectively. 

In HYR Global Source, We have dedicated mentorship programs for students and software professionals to get into the world of web development. If it is something which interests you please connect us here – https://www.hyrglobalsource.com/contact.html

If you already well versed in technology, then we are always looking for bright minds like you, Please check out career page here – https://www.hyrglobalsource.com/careers.html

Leave a Reply

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