In this article, we will explore that what are steps to create an API using Node js and database connectivity with Mongodb in the Node js project. We will cover from scratch how you can build API, set up good folder architecture, handle HTTP requests, API endpoints, and more.
Introduction
API (application programming interface ) plays an important role in communication between two different software systems. It can allow developers to retrieve, insert or update data from external or internal sources and use it in modern web applications.
What is an API?
In simple terms, API acts as a bridge between different systems or it is a set of rules and protocols that allows one software application to interact with another. It is a part of Backend Development.
Why create an API in Node.js?
Node js is a powerful environment in which developers can build server-side applications using JavaScript. Some more advantages are as follows:
- Efficiency: Node js can handle a large number of concurrent connections. This makes it an excellent choice for building high-performance APIs that can handle heavy traffic loads.
- Unified language: JavaScript used by both frontend and as well as backend developer can increase their existing knowledge and skills, resulting in faster development cycles and easier code maintenance.
- Vibrant ecosystem: Node js has a big community that constantly develops and maintains a wide range of modules and libraries.
- Scalability: Node.js applications can be easily scaled by adding more servers or instances.
Setting up a Node.js project
Before we begin to create our API, we need to set up a Node.js project
Initialize a new Node.js project: Open your terminal or command prompt and navigate the directory for your project. Run the following command to initialize a new Node.js project:
npm init -y
Install required dependencies: We will be using Express &, Mongoose, a popular web framework for Node.js. Install it by running the following command:
npm install express mongoose dotenv nodemon nodemon esm
Create the main server file: Now open that folder in VScode and create a new file named server.js.
Import required modules: We will import express for the project.
const express = require('express');
const app = express();
Setup Folder Structure and Follow MVC Pattern
What to Do: Create an environment file named .env and the following code
PORT=4000
Now import it into the server.js file
import dotenv from ‘dotenv’
dotenv.config();
const APP_PORT = process.env.PORT;
Start the server: Before starting the server let’s setup our package.json file or you can add the following code:
“script”:{
“start”:”nodemon -r esm server.js”,
“test”:”echo \"Error: no test specified\" && exit 1”
}
After adding the above code add the following code in your server.js file to start the server
app.listen(APP_PORT, () => {
console.log(`Server is running on port ${APP_PORT}`);
});
Create the Folders: Create the following code in your project root folder:
Controllers, Models, Views, Public, DatabaseConfig, Middlewares, and Routes
Your Folder Structure should look like the following Screenshot:

Database Connection
Open your env file and add the following code you can put your username, password, and database name.
DB_URL = mongodb+srv://usename:[email protected]/databasename?retryWrites=true&w=majority
Create a new file database.js in the DatabaseConfig folder and add the following code
import dotenv from ‘dotenv’
dotenv.config();
import mongoose from ‘mongoose’;
mongoose.connect(process.env.DB_URL, { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false, useCreateIndex: true });
const db = mongoose.connection;
//Database Connection
try {
db.on('error', console.error.bind(console, 'Connection Error'));
db.once('open', () => {
console.log('Database Connected'); 3
});
}
catch (err) {
console.log(err, 'ERROR')
}
export default db;
You can follow the below screenshot

Now import the Database file in the server.js file

Now you can see the server is running and the database is connected in the screenshot.
Handling HTTP requests in Node js project
Now our server is running and we can handle the HTTP requests such as GET, POST, PUT, and DELETE.
Each request will be routed to a specific endpoint.
Create a GET endpoint: Now you have the Routes folder, let’s suppose we want to get the all user data so we will create a new file name as UserRoutes.js and add the following code.
import express from 'express';
const router = express.Router();
router.get('/user');
//We will add some more code here after creating controller
module.exports = router;

Creating Controller: To get details of all users you have to create a controller.
Create a new file in the Controller folder named UserController.js
Creating Model: in the model folder we will create a new file named UserModel.js and add the following code.
import mongoose from 'mongoose';
const Schema = mongoose.Schema;
const UserSchema = new Schema({
FirstName: {
type: String,
required: true
},
LastName: {
type: String,
required: true
},
Password: {
type: String,
required: true
},
UserEmail:{
type: String,
required: true
},
UserMobile:{
type: String,
required: true
},
UserStatus: {
type: String,
default: 'Active'
},
isDeleted: {
type: Boolean,
default: false
}
}, { timestamps: true });
export default mongoose.model('UserSchema', UserSchema, 'UserSchema');
Now Your Folder structure will look like this:

Importing Model in Controller: Now we have created the model and controller, after this, we will import the model into the user controller. So open your usercontroller.js and add this line of code.
import UserModel from "../Models/UserModel"
Creating User Details Function: Here we will write the code to get the all user details in JSON format, you can follow this code:
const UserController = {
async getUsers(req, res, next) {
try {
const result = await UserModel.find();
if (result)
return res.json({ status: 200, data: result });
else
return res.json({ status: 404 });
}
catch (Err) {
console.log('Error in UserController While Getting User Details', Err)
}
}
}
export default UserController;
You can follow this screenshot:

Import Controller in Routes: Now we have completed Controller and Model now import UserController in UserRoutes, you can follow this code:
import express from 'express';
const router = express.Router();
//Imported User Controller
import UserController from '../Controllers/UserController';
router.get('/user',UserController.getUsers);
module.exports = router;
Import Routes in Server.js file: You can simply import user routes but in terms of large-scale projects we will have many routes so we should not import the all routes one by one.
To prevent this we will use the filesystem module of nodejs.
import { readdirSync } from 'fs';
readdirSync('./Routes').map(route => app.use('/api', require(`./Routes/${route}`)));

Hit the EndPoint: Now everything is done let’s hit the endpoint
Your endpoint will be “http://localhost:4000/api/user”
You can hit this in the Browser or Postman

Conclusion – API Node Js Project
Creating an API in Node.js opens up a world of possibilities for developers. With its efficiency, unified language, vibrant ecosystem, and scalability, Node.js provides the best platform for building powerful APIs.
Follow Us on
https://www.linkedin.com/company/scribblers-den/
https://www.facebook.com/scribblersden.blogs
Read More
https://scribblersden.com/queue-data-structure/
Thank You