How to Build a RESTful API Using Node, Express, and MongoDB ?
Last Updated :
24 Jul, 2024
This article guides developers through the process of creating a RESTful API using Node.js, Express.js, and MongoDB. It covers setting up the environment, defining routes, implementing CRUD operations, and integrating with MongoDB for data storage, providing a comprehensive introduction to building scalable and efficient APIs.
Prerequisites:
What is a RESTful API?
REST, short for Representational State Transfer, defines an architectural style for constructing web services that utilize HTTP requests to interact with and manipulate data. It serves as a standardized method enabling disparate computer systems to communicate seamlessly over the internet.
To illustrate this concept, consider a scenario at a café where you're placing an order for food. Here's how the analogy aligns with the components of a RESTful API:
- The menu represents the available operations such as GET, POST, PUT, and DELETE.
- Placing an order mirrors sending a request to the server.
- The server acts as the kitchen where the request is processed.
- The waiter serves as the API, facilitating communication between you (the client) and the kitchen (the server).
We have discussed different CRUD operations API:
Create a New Book (POST):
JavaScript
app.get('/', (req, res) => {
res.send('Welcome to the Books API!');
});
// Create a new book
app.post('/books', async (req, res) => {
res.send('Created a new book');
});
// Get all books
app.get('/books', async (req, res) => {
res.send('Received all books');
});
// Get a specific book by ID
app.get('/books/:id', async (req, res) => {
res.send('Got a book by ID')
});
// Update a book by ID
app.put('/books/:id', async (req, res) => {
res.send('Updated book by ID');
});
// Delete a book by ID
app.delete('/books/:id', async (req, res) => {
res.send('Deleted book')
});
We've implemented five methods aligned with REST principles: Post, Get, Put and Delete. These methods are associated with specific HTTP request types, each catering to different operations on our book collection. The "app" instance handles these methods by taking the route as its primary parameter and a callback function as the second parameter.

Create Mongoose Model:
JavaScript
const mongoose = require('mongoose');
const bookSchema = new mongoose.Schema({
title: {
type: String,
required: true
},
author: {
type: String
required: true
},
});
const Book = mongoose.model('Book', bookSchema);
module.exports = Book;
We have created a Mongoose schema for books, consisting of the title and author fields both of which are required. Now, import this model into the index.js file.
const Book = require('./models/book');
POST Request:
Let's create book using the Book model (POST)
JavaScript
// Create a new book
app.post('/books', async (req, res) => {
try {
const book = new Book(req.body);
await book.save();
res.status(201).json(book);
} catch (error) {
res.status(400)
.json({ error: error.message });
}
});
We've implemented try-catch blocks to handle success and error messages. The use of async-await syntax ensures a structured and readable code style, allowing us to seamlessly wait for promises and enhancing error handling. This approach contributes to a cleaner and maintainable codebase for our Books API.
Now add data to the body in postman and send a POST request.

GET Request:
Now lets receive the book we just created.
JavaScript
// Get all books
app.get('/books', async (req, res) => {
try {
const books = await Book.find();
res.json(books);
} catch (error) {
res.status(500)
.json({ error: error.message });
}
});
Send a GET request via postman. You can change the body data if you want.

Head over to MongoDB website and you will see all the data being stored in our database.

Update a Book By ID (PUT):
When you want to update a specific book, you provide the book's unique ID along with the new data in the request. The API then locates the book with the given ID in the database and replaces its existing information with the new data.
JavaScript
// Update a book by ID
app.put('/books/:id', async (req, res) => {
try {
const book =
await Book.findByIdAndUpdate(
req.params.id,
req.body, { new: true }
);
if (!book) {
return res.status(404)
.json({ error: 'Book not found' });
}
res.json(book);
} catch (error) {
res.status(500)
.json({ error: error.message });
}
});
Delete a Book By ID (DELETE):
To delete a specific book, you send a request to the API with the book's unique ID. The API then identifies the book with that ID in the database and removes it.
JavaScript
// Delete a book by ID
app.delete('/books/:id',
async (req, res) => {
try {
const book =
await Book.findByIdAndDelete(req.params.id);
if (!book) {
return res.status(404)
.json({ error: 'Book not found' });
}
res.json({ message: 'Book deleted successfully' });
} catch (error) {
res.status(500)
.json({ error: error.message });
}
});
Example: Below is the Complete Example of MongoDB CRUD operations we have discussed above:
JavaScript
require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
const Book = require('./models/book');
const app = express();
const URI = process.env.MONGODB_URI
mongoose.connect(URI)
const database = mongoose.connection
database.on('err', (err) => {
console.log(err)
})
database.once('connected',
() => {
console.log('Database Connected to the server');
})
app.use(express.json())
app.get('/', (req, res) => {
res.send('Welcome to the Books API!');
});
// Create a new book
app.post('/books', async (req, res) => {
try {
const book = new Book(req.body);
await book.save();
res.status(201).json(book);
} catch (error) {
res.status(400)
.json({ error: error.message });
}
});
// Get all books
app.get('/books', async (req, res) => {
try {
const books = await Book.find();
res.json(books);
} catch (error) {
res.status(500)
.json(
{
error: error.message
}
);
}
});
// Update a book by ID
app.put('/books/:id', async (req, res) => {
try {
const book =
await Book.findByIdAndUpdate(
req.params.id,
req.body,
{ new: true }
);
if (!book) {
return res.status(404)
.json({ error: 'Book not found' });
}
res.json(book);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Delete a book by ID
app.delete('/books/:id',
async (req, res) => {
try {
const book =
await Book.findByIdAndDelete(req.params.id);
if (!book) {
return res.status(404)
.json({ error: 'Book not found' });
}
res.json({ message: 'Book deleted successfully' });
} catch (error) {
res.status(500)
.json({ error: error.message });
}
});
app.listen(3000, (req, res) => {
console.log('Server is listening on port 3000');
});
Here, you have the comprehensive code for implementing a fully functional RESTful API. This code covers all aspects of CRUD operations, allowing you to effortlessly manage your book data. Feel free to modify and build upon it!
Output:
Similar Reads
RESTful Blogging API with Node and Express.js
Blogs Websites have become very popular nowadays for sharing your thoughts among the users over internet. In this article, you will be guided through creating a Restful API for the Blogging website with the help of Node, Express, and MongoDB.Prerequisites:Node JS & NPMExpress JSMongoDBApproach t
5 min read
Creating a REST API Backend using Node.js, Express and Postgres
Creating a REST API backend with Node.js, Express, and PostgreSQL offers a powerful, scalable solution for server-side development. It enables efficient data management and seamless integration with modern web applications.This backend can do Query operations on the PostgreSQL database and provide t
4 min read
How to Retrieve Data from MongoDB Using NodeJS?
MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term âNoSQLâ means ânon-relationalâ. It means that MongoDB isnât based on the table-like relational database structure but provides an altogether different mechanism for the storage and retrieval of data. Thi
3 min read
How To Build a Basic CRUD App With Node and React ?
In this article, we will explore how to build a simple CRUD (Create, Read, Update, Delete) application using Node.js for the backend and React for the frontend. Additionally, we will integrate MongoDB as the database to store our data.Preview of final output:App functionalityCreate a new student (CR
11 min read
How to Create Indexes in MongoDB using Node.js?
MongoDB, a popular NoSQL database, provides powerful indexing capabilities to improve query performance. Indexes in MongoDB help in quickly locating documents and speeding up read operations. In this tutorial, we'll explore how to create indexes in MongoDB using Node.js. What is an Index in MongoDB?
3 min read
How to Connect to a MongoDB Database Using Node.js
MongoDB is a NoSQL database used to store large amounts of data without any traditional relational database table. To connect to a MongoDB database using NodeJS we use the MongoDB library "mongoose". Steps to Connect to a MongoDB Database Using NodeJSStep 1: Create a NodeJS App: First create a NodeJ
4 min read
Build a Social Media REST API Using Node.js: A Complete Guide
Developers build an API(Application Programming Interface) that allows other systems to interact with their Applicationâs functionalities and data. In simple words, API is a set of protocols, rules, and tools that allow different software applications to access allowed functionalities, and data and
15+ min read
How to Build a GraphQL server with NodeJS and Express
GraphQL is the open-supply question-based language that is used for querying the data. The main task of GraphQL is to execute the given question return the appropriate facts and represent it to the person. GrapghQL is the advancement of conventional REST API architecture presenting greater features.
2 min read
How to create routes using Express and Postman?
In this article we are going to implement different HTTP routes using Express JS and Postman. Server side routes are different endpoints of a application that are used to exchange data from client side to server side.Express.js is a framework that works on top of Node.js server to simplify its APIs
3 min read
How to use TypeScript to build Node.js API with Express ?
TypeScript is a powerful version of JavaScript that incorporates static typing and other features, making it easy to build and maintain large applications. Combined with Node.js and Express, TypeScript can enhance your development experience by providing better type safety and tools. This guide will
4 min read