Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
MVC Architecture
3.
REST API
4.
Creating MVC Architecture for Restful API ExpressJs
4.1.
MODEL
4.2.
CONTROLLER
4.3.
VIEW
5.
Frequently Asked Questions
5.1.
What are the advantages of using MVC architecture in RESTful API development?
5.2.
Can MVC architecture be used with other frameworks or languages?
5.3.
How does ExpressJS fit into MVC architecture for RESTful API development?
6.
Conclusion
Last Updated: Mar 27, 2024
Medium

Creating MVC Architecture for Restful API ExpressJs

Author Shiva
0 upvote

Introduction

Have you ever faced problems with folder structure and keeping files in place? In software development, following commonly accepted guidelines and patterns is crucial for building outstanding projects. These guidelines, while not strict rules, have proven to be very effective and are widely embraced by developers everywhere.

Creating MVC Architecture for Restful API ExpressJs

In this article, we will create MVC Architecture for Restful API ExpressJs.

MVC Architecture

The Model-View-Controller (MVC) architecture was created for desktop graphical user interfaces. It has gained widespread popularity in developing web applications, mobile apps, etc. It divides an application into three interconnected parts. Initially, all components of a software application were processed on the same machine. However, a categorised approach was introduced, where specific code segments are separated and written independently. This approach enhances modularity and allows for more efficient development and maintenance.

To learn more about the architecture in depth, refer to this article.

REST API

REST stands for Representational State Transfer. API stands for an application programming interface. API acts as an interface between the information provider and the information user.

REST APIs, often known as RESTful APIs. To simplify communication between clients and servers, they use HTTP methods, including GETPOSTPUT, and DELETE. It's essential to manage these HTTP methods to implement REST APIs in an ExpressJS server. We may enable database interactions, perform operations using model functions, and return results to users by defining the relevant endpoints. The model serves as a middleman, making database-related tasks easier and assuring seamless API and database interaction.

Creating MVC Architecture for Restful API ExpressJs

Now that we have a basic understanding of MVC architecture and RESTful API. We are now ready to code. 

Let’s start with the model first. For this, we will be using MongoDB. Let’s consider an e-commerce application where we need to keep information about the user. Below is the schema of the user for an e-commerce application. This is why we have isAdmin as a property. It will look more or less similar to your application too. The schema defines the structure and content of the Model.

MODEL

import mongoose from 'mongoose';
const userSchema = mongoose.Schema(
{
	name: {
		type: String,
		required: true,
	},
	email: {
		type: String,
		required: true,
		unique: true,
	},
	password: {
		type: String,
		required: true,
	},
	isAdmin: {
		type: Boolean,
		required: true,
		default: false,
	},
},
{
	timestamps: true,
}
);

const User = mongoose.model('User', userSchema);
export default User;

CONTROLLER

Now, As for the bridge between Model and View, which is Controller. The controller is responsible for the logic of the application. It controls the way the user interacts with the MVC application. Here we are going to define just the basic operation related to the user of an application.

import asyncHandler from '../middleware/asyncHandler.js';
import generateToken from '../utils/generateToken.js';
import User from '../models/userModel.js';

// @desc    Get user profile
// @route   GET /api/users/profile
// @access  Private
const getUserProfile = asyncHandler(async (req, res) => {
const user = await User.findById(req.user._id.toString());


if (user) {
	res.json({
		_id: user._id,
		name: user.name,
		email: user.email,
		isAdmin: user.isAdmin,
	});
  } else {
		res.status(404);
		throw new Error('User not found');
	}
});


// @desc    Update user profile
// @route   PUT /api/users/profile
// @access  Private
const updateUserProfile = asyncHandler(async (req, res) => {
const user = await User.findById(req.user._id);


if (user) {
	user.name = req.body.name || user.name;
	user.email = req.body.email || user.email;
	if (req.body.password) {
		user.password = req.body.password;
	}
	const updatedUser = await user.save();
	res.json({
		_id: updatedUser._id,
		name: updatedUser.name,
		email: updatedUser.email,
		isAdmin: updatedUser.isAdmin,
	});
	} else {
		res.status(404);
		throw new Error('User not found');
	}
});

// @desc    Delete user
// @route   DELETE /api/users/:id
// @access  Private/Admin
const deleteUser = asyncHandler(async (req, res) => {
const user = await User.findById(req.params.id);


if (user) {
	if (user.isAdmin) {
		res.status(400);
		throw new Error('Can not delete admin user');
	}
	await User.deleteOne({ _id: user._id });
	res.json({ message: 'User removed' });
	} else {
		res.status(404);
		throw new Error('User not found');
	}
});


export {
	getUserProfile,
	updateUserProfile,
	deleteUser,
};

@desc@route, and @access in comments are there to smooth out the development purpose. Desc is short for description, rest are self-explanatory.  It gives you enough high level about the function.

VIEW

Now, as for the View section. It is related to the front end and will be specific to your application. Use the functions in the controller however way you want. The main objective was to separate the model and various operations related to the model in different files.

Time to check whether the endpoints are working properly. For this, we will use the getUserProfile function at the endpoint “localhost:5000/api/users/profile”. To do this, write the line below in your server file.

app.use('/api/users/profile', getUserProfile);
output

Frequently Asked Questions

What are the advantages of using MVC architecture in RESTful API development?

MVC architecture in RESTful API development is very advantageous. MVC offers concern separation, encourages code reuse, boosts maintainability, allows for parallel development, improves testability, and makes it simpler for developers working on various application components to collaborate.

Can MVC architecture be used with other frameworks or languages?

MVC architecture applies to any framework or language. It is a frequently used design pattern that can be utilised with many different programming languages and frameworks, including Ruby on Rails, Django, ASP.NET MVC, and others.

How does ExpressJS fit into MVC architecture for RESTful API development?

Express.js is a small framework that works on top of Node.js web server functionality to simplify its APIs. In an MVC design, it can be used as the controller, managing incoming requests, organising interactions between the model and view, and returning responses to the client.

Conclusion

In this article, we learned about Creating MVC Architecture for Restful API ExpressJs. We briefly touched on MVC architecture and RESTful API. We also looked at some example code on how actually to implement the architecture in the application and some best practices.

We hope this blog increases your knowledge regarding MVC. Don’t forget to check out these articles:

 

You may refer to our Guided Path on Code Studios for enhancing your skill set on DSACompetitive ProgrammingSystem Design, etc. Check out essential interview questions, practice our available mock tests, look at the interview bundle for interview preparations, and so much more!

Happy Learning, Ninja!

Live masterclass