Loading....

Introduction

In this article, we will learn how to create REST Apis using Nodejs, express js, and taking using MongoDB as a database. Before we start let us clarify what we will explore in this particular article We will explore all CRUD (create, read, update, and delete) operations in MongoDB. We will also explore how to setup MVC (model, view, and controller) pattern in our app. So let's get started….

how to create rest api in node js,what is rest api used for,how to create rest api in php,what is rest api,how to create rest api,how to create rest api in java,how to create rest api in spring boot,how to create rest api in python,

Folder Structure Setup for REST APIs

Create a new folder named express-rest-api and run the following command npm-init -y and after this create a new file named server.js and now create the following folders Controllers, Models, View, and Routes after that we will have have to install the following dependencies.

npm i express nodemon dotenv mongoose. 

 

Explaining Dependencies for REST APIs

Mongoose:  For Operation on MongoDB
Nodemon: It will restart our app automatically when we will save the file or create new files.
Express: Framework of Nodejs we will use for REST APIs.
Dotenv: for managing our app environment.

Setup Environment

For environment setup, we need to create .env file in our project root directory and we will create 2-3 environment variables.

APP_PORT= We will configure the app port by which it will run 3000.
MONGODB_URI = Here we will paste our MongoDB connection string
APP_ENV = This is our app mode, it can be development or production

 

Setup Database for REST APIs 

For database connection, we will create a new folder named Database and in which we will create new file db.js and we will use MongoDB URI from our environment setup.

 

Setup Server.js

Now we setup for server.js file and start to create out REST APIs. we will use express and inti our app, we can workthrough by following code and screen shot.
And after setuping server.js we can run our app.

As now we can see our app is running on PORT 3000 and the database is connected.

Create Model

We will create a new file in the Models Folder named UserModel. So here we will create a UserModel in which we will define some fields which will be necessary For user details like UserName, UserEmail, UserAge, and UserDateofBirth. So let's create it.

 

Create Controller

Here we will create a controller in which we will define some functions by which we can perform our CRUD operations for USERS so let's create it.
Create a new file in the Controllers folder named UserController.

With this function, we can insert users into our database. Now it's time for testing but for testing, we need Postman in which we can send JSON data. But before testing we need to define our routes and that we will be our endpoints.

Create Routes

Here we will create a new file in Routes Folder named UserRoutes.

So here we have defined routes and now we will import routes in Server.js
For import, we will use the fs(file system) module.

Here at line, number 17 we have imported the routes and all routes can be hit by 
API/then your routes. Now let's go to POSTMAN and create a User.

Now the user is created.

CRUD Operations

Now we have completed the create operation let's complete all left operations.

Read:

Here we will read the user's details from the database so first create a controller

Routes:


Routes for Getting Users

 

Update:


Here we will update the user's details from the database so first create a controller. For updating users we will take user-id in query and update data according to that.

Routes:

 

User Updated Successfully.

Delete: 

Here we will delete the user's details from the database so first create a controller.

 

Routes:

 

Now the User is Deleted.

Code - REST APIs

Controller

const UserModel = require('../Models/UserModel');

const UserController = {
    async createUser(req, res, next) {
        try {
            const response = await new UserModel(req.body).save();
            if (response)
                return res.json({ status: 200, data: response });
            else
                return res.json({ status: 400 });
        }
        catch (err) {
            console.log(err)
        }
    },
    async getUsers(req, res, next) {
        try {
            const response = await UserModel.find();
            if (response)
                return res.json({ status: 200, data: response });
            else
                return res.json({ status: 400 });
        }
        catch (err) {
            console.log(err)
        }
    },
    async updateData(req, res, next) {
        try {
            const response = await UserModel.findById({ _id: req.query.userID }, req.body, { new: true });
            if (response)
                return res.json({ status: 200, data: response });
            else
                return res.json({ status: 400 });
        }
        catch (err) {
            console.log(err)
        }
    },
    async deleteUser(req,res,next){
        try {
            const response = await UserModel.findByIdAndDelete({ _id: req.query.userID });
            if (response)
                return res.json({ status: 200, data: response ,message:'User Deleted'});
            else
                return res.json({ status: 400 });
        }
        catch (err) {
            console.log(err)
        }
    }
}

module.exports = UserController;

Database

const dotenv = require('dotenv');
const mongoose = require('mongoose');
dotenv.config();

mongoose.connect(process.env.MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true });
const db = mongoose.connection;

// Database Connection
try {
  db.on('error', console.error.bind(console, 'Connection Error'));
  db.once('open', () => {
    console.log('Database Connected');
  });
} catch (err) {
  console.log(err, 'ERROR');
}

module.exports = db;

Models

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const UserSchema = new Schema({
    UserName: {
        type: String,
        required: true
    },
    UserEmailAddress: {
        type: String,
        required: true
    },
    UserAge: {
        type: String,
        required: true
    },
    UserDateOfBirth: {
        type: String,
        required: true
    },
    UserStatus: {
        type: String,
        default: 'Active'
    },
    isDeleted: {
        type: Boolean,
        default: false
    }
}, { timestamps: true });

module.exports = mongoose.model('UserSchema', UserSchema, 'UserSchema');

Routes

const express = require('express');
const router = express.Router();

const UserController = require('../Controllers/UserController');


router.post('/user/register', UserController.createUser);
router.get('/user/data', UserController.getUsers);
router.put('/user/update', UserController.updateData);
router.delete('/user/delete', UserController.deleteUser);

module.exports = router;

Server.Js

const express = require('express');
const app = express();
const { readdirSync } = require('fs');

// Import Database Connection
const db = require('./Database/db');
//Import Enviroment Variables
const dotenv = require('dotenv');
dotenv.config();

const APP_PORT = process.env.APP_PORT || 3000;
app.use(express.json());
app.use(express.urlencoded({ extended: false }));


// API ROUTES
readdirSync('./Routes').map((route) => app.use('/api', require(`./Routes/${route}`)));

app.listen(APP_PORT, () => {
    console.log(`Server Started At PORT ${APP_PORT}`);
});

Package.json

{
  "name": "express-rest-api",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start":"nodemon server.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "dotenv": "^16.3.1",
    "express": "^4.18.2",
    "mongoose": "^7.4.3",
    "nodemon": "^3.0.1"
  }
}

Conclusion - REST APIs

So from the above article, we learned how we can perform the CRUD operation in Nodejs and create REST APIs we also explore how to build an app on the MVC Platform and make use of our code look cool.

Alert