In today’s data-driven world, businesses are increasingly turning to MongoDB REST APIs to leverage the power of NoSQL databases. As traditional relational databases struggle with the ever-growing volume of unstructured data, MongoDB is a popular solution with its scalability and flexibility. This guide elaborates on building a robust REST API using this powerful database.

Creating a MongoDB REST API

Selecting the appropriate database for your REST API is crucial, and based on current trends, MongoDB is one of the most popular databases for web applications. MongoDB RESTful API is simple to set up and allows you to store and retrieve documents, making it great for Unstructured Data.

Using Express JS as the backend web server with MongoDB as the document store is a common way of implementing the MongoDB REST API strategy. This approach conveniently links MongoDB’s Document Model to the JSON-based REST API payloads. You can use Express to build a backend middle tier that runs on Node.js and exposes REST API routes to your application. The Node.js Driver also connects the Express.js server to the MongoDB Atlas cluster. For this, you will need to install Node.js by following the appropriate guidelines mentioned here.

You will also need to sign up for MongoDB Atlas, which is a Cloud Database as a service. MongoDB Atlas offers a free sandbox environment that will allow you to focus on building your MongoDB REST API. Further, you will require a Code Editor like Visual Studio Code or Sublime Text.

It’s worth noting that one of the first things you can do to ensure a successful start of MongoDB REST API is to prepare your workspace. The first step is to verify that your MongoDB instance is operational. Once you’ve confirmed that the MongoDB instance is up and running, you may use the MongoDB client to connect to the server and inspect your collection, data, and run queries, among other things.

From the MongoDB REST API, you need to populate the MongoDB Database with the data, which can be done using the mongo package. The mongo package includes the ‘mongoimport‘ command, which allows you to import data files. You can import three different data files via the command line. These are JSON (JavaScript Object Notation), CSV (Comma Separated Values), and TSV (tab-separated values). 

You’ll need to make an application folder for the app to live in. To start the application, you’ll need to generate a package.json file that contains all of the node application’s metadata. The file instructs npm to install the package dependencies as well as the scripts you will write to run the application and you can get started with MongoDB REST API.

Simplify MongoDB and REST API ETL with Hevo’s No-code Data Pipeline

A fully managed No-code Data Pipeline platform like Hevo Data helps you integrate and load data from MongoDB and  150+ Data Sources (including 40 Free Data Sources like REST APIs) to a destination of your choice in real-time effortlessly. 

Get Started with Hevo for Free

Step 1: Setting up the Project

If you have Node.js installed, you can run the following command to start the application from the command line:

npm init -y

The above command will create a package.json file.

Step 2: Installing Application Dependencies

For MongoDB REST API to run, you need a file that will serve as the application’s command centre. When you ask npm to run your application, it will initially run this file. This file can include object instances of both your modules and third-party modules installed from the npm directory.

touch app.js
npm install express mongodb body-parser --save

You created a file named app.js, which will be the application’s main entry point, and installed a few dependencies that are required to run your application using the commands above.

These are the dependencies:

  • Express: A framework for Node.js.
  • MongoDB: The MongoDB team has supplied an official module to let your Node.js application communicate with MongoDB.
  • Body-parser: It will handle request bodies with Express.

Step 3: Run Code

const Express = require("express");
const BodyParser = require("body-parser");
const MongoClient = require("mongodb").MongoClient;
const ObjectId = require("mongodb").ObjectID;
var app = Express();
app.use(BodyParser.urlencoded({ extended: true }));
app.listen(5000, () => {});

Here, you are importing the dependencies you downloaded before. Use the Express object to initialize the express framework, which will utilize the express framework to start the server and run your application on a certain port, as well as configure the body-parser, which is a middleware that parses incoming chunks of data.

Step 4: Testing Application for MongoDB REST API

node app.js

Step 5: Establishing Connection with MongoDB REST API

For this, you will need the MongoDB REST API connection string. Choose Clusters from the Atlas dashboard, then the Overview page, and then the Connect button. You will need to add the string to the app.js file and perform the following code adjustments.

const Express = require("express");
const BodyParser = require("body-parser");
const MongoClient = require("mongodb").MongoClient;
const ObjectId = require("mongodb").ObjectID;
const DATABASE_NAME = "accounting_department";

var app = Express();
app.use(BodyParser.urlencoded({ extended: true }));
var database, collection;

app.listen(5000, () => {
    MongoClient.connect(CONNECTION_URL, { useNewUrlParser: true }, (error, client) => {
        if(error) {
            throw error;
        database = client.db(DATABASE_NAME);
        collection = database.collection("personnel");
        console.log("Connected to `" + DATABASE_NAME + "`!");

Step 6: Build MongoDB REST API Endpoint

Next, you will need to establish and query endpoints for the data. To add the data, we’ll need to construct an endpoint. To app.js, add the following code:"/personnel", (request, response) => {
    collection.insert(request.body, (error, result) => {
        if(error) {
            return response.status(500).send(error);

Step 7: Testing the MongoDB REST API

curl -X POST \
    -H 'content-type:application/json' \
    -d '{"firstname":"John","lastname":"Doe"}' \

You’ll see the personnel record for John Doe added into the MongoDB database of ‘accounting_department.’

Your MongoDB REST API is ready to use


This article showed how to create a MongoDB REST API. It also gave you an in-depth understanding of MongoDB’s features and REST architecture‘s limits, so you can better comprehend and apply MongoDB REST API where it’s needed. Once you know how to create API MongoDB integration, you can use it in several MongoDB REST API example applications. REST API with MongoDB can also be used in web applications, retail e-commerce, and other such applications where real-time data analysis is required. 

Extracting complex data from a diverse set of free data sources like MongoDB and REST APIs can be a challenging task and this is where Hevo saves the day!

Visit our Website to Explore Hevo

Hevo Data offers a faster way to move data from 150+ data sources such as SaaS applications, Databases like MongoDB, Files, etc. Further, Hevo’s native REST API connector can help connect with a variety of non-native/custom sources into your Data Warehouse to be visualized in a BI tool. Hevo is fully automated and hence does not require you to code.

Want to take Hevo for a spin? Sign Up for a 14-day free trial and experience the feature-rich Hevo suite first hand. You can also have a look at the unbeatable Hevo pricing that will help you choose the right plan for your business needs.

Drop your thoughts about building MongoDB REST APIs in the comment section below!

Isola Saheed Ganiyu
Technical Content Writer, Hevo Data

Isola is a freelance writer specializing in the domains of data integration and data analysis. He has a passion towards creating engaging and educational content, breaking down these sophisticated subjects for easily understanding.

No-code Data Pipeline for MongoDB &REST APIs