How to create REfull API using nodejs and Express js and perform basic CRUD operation

Hi, I am Ghulam Rabbani Ansari 3rd year computer science engineering student or you can say a tech enthusiast who wants to write and educate people about technology I know. I have been thinking of writing blogs since my first year. Finally my first blog is here. I hope this will help people.

restapi.png

So, in this article we are going to learn how to create basic RESTful API using Nodejs and Expressjs libraries on MVC structure. First let me introduce you to the above mentioned keywords.

RESTful API : REST stands for Representational State Transfer which is a software architectural design pattern. REST architecture is also used by other languages like Ruby, PHP and C#. API stands for Application programming interface which is used to communicate between client request and server and also to access resources from another application.

Nodejs: It is a javascript runtime environment built on a chrome V8 engine. It helps to run javascript code and also provides modules to deal with file systems and operating systems. If you are reading this article then you must be familiar with the basics of Nodejs and Express.js.

Expressjs: It is a javascript library or you can say backend web application framework for node.js which provides functionality to easily design and build web application APIs .

MVC : It stands for Model VIew Controller which is a software design architecture proposed in 2000 by Trygve Reenskaug. Model defines the structure or Schema of the data that is being stored in a database. View defines how the data is being shown to the user and the Controller controls the request and response from the user and server. But in nodejs it is a little bit different from MVC that we will see below.

Setting up,

Make sure you have installed Node and npm on your local machine. To check open command prompt and type node -v to know about node and npm -v to check npm availability. This should create the following result. Your versions may differ from mine. Npm automatically gets downloaded with the node.

folowing result.png

If the desired result is not showing then install node here.

Now create an empty folder anywhere you want and open it with vs code. Open the terminal of the vs code and type npm init -y it will create a package.json file which holds all dependencies that will be used in the project. After this install express, mongoose and body-parser by writing

by writing.png

After it gets downloaded you will see a node_modules folder and package_lock.json file.

Now create an index.js file in the root folder. If you are a beginner you might be wondering what mongoose and body-parser are.

- Mongoose: It is a node js-based Object Data modeling library for mongodb.

- Body Parser : It acts as a middleware in nodejs. It is responsible for handling incoming request bodies.

Now you are all set to write code and create a server. As we discussed earlier, we will use MVC architecture, So to fulfill the promise create two more folder named models and controllers and for connection and handling routes create db and routes folder. Now the folder structure should look like this,

folderstrucutre.png

Index.js creates an app with the help of express and listen to the server on the desired port. This should look like this,

//Importing express library to create server.
const express = require('express');
//Defining port no to listen the server
const PORT = 4000;
//Require conn file for db connection
require('./db/conn');
//Importing postRoute from routes
const postRoute = require('./routes/postRoute');

//Creating and app from express
const app = express();


//TO handle json data we will use express.json
app.use(express.json());

app.use(postRoute);

//Listeing to server and should come at last of all the code
app.listen(PORT,()=>{
    console.log(`server is runnig at ${PORT}`);
})

As you can see above I have imported the connection file and postRoute, In the db folder create conn.js file and it contains the code,

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/postbasicapi',{
    useNewUrlparser:true,

    useUnifiedTopology:true
}).then(()=>{
    console.log(`Connection successful`)
}).catch((err)=>{
    console.log(`something went wrong ${err}`);
})

In the routes folder create a postRoute.js file and it will contain the code,

//Importing Express library
const express = require('express');

//Creating router from express router
const router  = express.Router();

//Importing all the controller from postController
const {createPost,getAllPost,getPost,updatePost,deletePost} = require('../controllers/postController')

//Creating the post route
router.post('/post',createPost);

//Creating route to get all the posts
router.get('/post',getAllPost)

//Creating the route for getting single post
router.get('/post/:id',getPost)

//Creating route to update the post
router.patch('/post/:id',updatePost)

//Creating route to delete the post
router.delete('/post/:id',deletePost)


//Exporting Router
module.exports = router;

As you can see, we have imported controllers from postController to handle requests and responses from the client and server. So, now create the postController.js file inside the controller folder and it contains the code,

//import models
const postModel = require("../models/postModel");

//Creating the post request method
const createPost = async (req, res) => {
  try {
    const post = new postModel(req.body);
    const postData = await post.save();
    res.json(postData);
  } catch (err) {
    res.send(err);
  }
};

//Creating the get request method
const getAllPost = async (req, res) => {
  try {
    const posts = await postModel.find();
    res.send(posts);
  } catch (err) {
    res.send(err);
  }
};

//Creating get request method for single post
const getPost = async (req, res) => {
  try {
    const id = req.params.id;
    const post = await postModel.findById(id);
    res.send(post);
  } catch (err) {
    res.send(err);
  }
};

//Creating update request method
const updatePost = async (req, res) => {
  try {
    const _id = req.params.id;
    const updatedPost = await postModel
      .findOneAndUpdate({ _id }, { new: true })
      .save();
    res.send(updatedPost);
  } catch (err) {
    res.send(err);
  }
};

//Creating delete post
const deletePost = async (req, res) => {
  try {
    const id = req.params.id;
    const deletedPost = await postModel.findByIdAndDelete(id);
    res.send(deletedPost);
    res.json({ message: `post deleted with ${id}` });
  } catch (err) {
    res.send(err);
  }
};

//Exporting all the method and will be imported to routes
module.exports = { createPost, getAllPost, getPost, updatePost, deletePost };

In the postController.js file, we have imported models from postModel which describes the Schema of the data, create a postModel.js file inside the models folder and it will contain the code,

//import mongoose to create Schema and model
const mongoose = require("mongoose");

const postSchema = new mongoose.Schema({
  creator: {
    type: String,
    required: true,
    maxlength: 30,
  },
  title: {
    type: String,
    required: true,
    maxlength: 100,
  },
  description: {
    type: String,
  },
  createdAt: {
    type: Date,
    default: Date.now(),
  },
});

//Model creation
const postModel = mongoose.model("postModel", postSchema);

//Exporst models and will be imorted to controllers
module.exports = postModel;

Final folder structure should look like,

final strucutre.png

Now install the nodemon by writing “npm i nodemon”. It runs the server automatically when any changes happen in the file, if you don’t have nodemon installed then you have to start the server after every request, response and file changes.

Do one more change to package.json file, and that is, add "start": "nodemon index.js" In the “script”, below “test” key. like this,

script tag.png

Run the server by typing npm start. It should give the following results,

following results npm start.png

You can test it on POSTMANby creating post, get, put and delete requests.

That’s for this article, I hope it helps you a little bit.

Follow me on Twitter, LinkedIn

Did you find this article valuable?

Support ghulamrabbani by becoming a sponsor. Any amount is appreciated!