• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer

Rapid Blog

  • Enterprise
  • API Hub
  • Add Your API
  • About
  • Docs
    • API Glossary
  • Blog
    • What is an API?
    • REST API Tutorials
    • Most Popular APIs
  • Sign Up
    • Log In
Blog » API Tutorials » MongoDB API Tutorials » MongoDB REST API
Additional Documentation Appearance

How to Create a REST API using MongoDB

By Team RapidAPI // August 17, 2020

How to create a REST API using MongoDB

In this article, we will create a MongoDB REST API.  The data stored in the database will be proverbs.  The sources will be from the book of that name as well as other well-known authors and thought leaders.  The Proverbs API will pull a random proverb from the sources selected.  There are six sources to start with and we will create two optional parameters.  The two parameters will be “include sources” and “exclude sources”.  That way people can get proverbs from their favorite sources.
 
Before creating the API I checked to see if there are similar APIs already.  In this case, there are two, one called Bestquotes and the other called Quotes and Proverbs.  Both of them have a large number of sources.  I will differentiate my API by allowing full control over the sources used.

The process will be as follows:

  1. Install MongoDB on your server
  2. Populate MongoDB with your data
  3. Create the REST API logic to interact with your data
  4. Create a REST API using the RapidAPI Provider Dashboard
    1. Defining the API name, description, and logo
    2. Specifying API endpoints and available parameters
    3. Choose API plans and pricing
    4. Provide more detailed documentation about your API

Step 1.  Install MongoDB on your server

To install MongoDB you will need root access to your server.  That means you will have either a Dedicated Server or a Virtual Private Server (VPS).  If you are using an Elastic Compute Cloud (EC2) server there is an example configuration.  In my case, I have a VPS with root access enabled.  I followed the MongoDB RedHat install instructions. The first step was creating a file at

/etc/yum.repos.d/mongodb-org-4.2.repo
/etc/yum.repos.d/mongodb-org-4.2.repo with the following contents:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
[mongodb-org-4.2]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/4.2/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-4.2.asc
[mongodb-org-4.2] name=MongoDB Repository baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/4.2/x86_64/ gpgcheck=1 enabled=1 gpgkey=https://www.mongodb.org/static/pgp/server-4.2.asc
[mongodb-org-4.2]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/4.2/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-4.2.asc

Then I installed the MongoDB packages with

yum install -y mongodb-org
yum install -y mongodb-org.  Next I ran it using
service mongod start
service mongod start.

Then when I ran it by typing ‘mongo’ I got a welcome message, several information messages, and a command prompt!

Step 2.  Populate MongoDB with your data

The simplest form of an API is one that is read-only.  That means data can be retrieved but not added, updated, or removed.  For my first API on the RapidAPI platform, I wanted to keep things simple.  For the Proverbs API, there are only 2 fields in one collection in one MongoDB database.  A MongoDB collection is analogous to a table in a SQL database.

The ‘mongoimport’ command is part of the mongo package and it allows you to import data files.  There are three types of data files you can import from the command line.  They are JavaScript Object Notation (JSON), comma separated values (CSV), and tab separated values (TSV).  I created .tsv files because there are commas in many of the quotes.  An example of the command I used was as follows:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
mongoimport -d proverbsdb -c proverbs --type tsv --file "rumi quotes.tsv" --fields=proverb,source
mongoimport -d proverbsdb -c proverbs --type tsv --file "rumi quotes.tsv" --fields=proverb,source
mongoimport -d proverbsdb -c proverbs --type tsv --file "rumi quotes.tsv" --fields=proverb,source

In this command, ‘proverbsdb’ is the name of the database and ‘proverbs’ is the name of the collection.  The data file name is ‘rumi quotes.tsv’ and the two fields in the file (used in the collection) are specified in the ‘fields’ tag.

Step 3.  Create the MongoDB REST API logic to interact with your data

Once you populate MongoDB with your data, you can set up the logic to interact with your data.  For a complex API, you may want to use an API Framework. For this example, I will be returning data from a Mongo query.  Also, if you are using PHP like I am in this example, there is a MongoDB PHP Driver you can install.  But in my experience, using a driver adds a layer of complexity that is distracting.  The syntax of commands is different using a driver.  For this example, I used the documentation for MongoDB Shell Commands.
 
Here is the core logic I used to create the database query.  Find your own ‘apiKeyAllowed’ parameter in the settings of the Provider Dashboard.  It ensures the request is coming from RapidAPI.

First, we validate the input parameters sent in the URL.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
/*
File: proverbs-api.php
Description:
This api takes 3 optional inputs, queries a local MongoDB collection using
the inputs as filters if needed, then returns a proverb and source in JSON.
Inputs:
includeSources - comma separated list of sources to include
excludeSources - comma separated list of sources to exclude
searchTerm - term used to filter results (only letters, numbers, and spaces allowed)
Outputs:
JSON object with the following fields:
source - source of the proverb
proverb - text of the proverb
*/
global $debug;
$debug=false;
$apiKeyAllowed = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$sourcesAllowed = ['proverbs','shakespeare','emerson','thoreau','rumi','tao te ching'];
//Collect Inputs
$includeSrcs = (!empty($_GET['includeSources']))?explode(",",$_GET['includeSources']):[];
$excludeSrcs = (!empty($_GET['excludeSources']))?explode(",",$_GET['excludeSources']):[];
//Only keep letters, numbers, and spaces in the search term
$searchTerm = (!empty($_GET['searchTerm']))?preg_replace('/[^a-zA-Z0-9 ]/','',$_GET['searchTerm']):'';
//Validate source filters
$includeSrcFilters=$excludeSrcFilters=array();
foreach($includeSrcs as $includeSrc) {
if (in_array(strtolower($includeSrc),$sourcesAllowed)) {
$includeSrcFilters[] = strtolower($includeSrc);
}
}
if (empty($includeSrcFilters)) {
foreach($excludeSrcs as $excludeSrc) {
if (in_array(strtolower($excludeSrc),$sourcesAllowed)) {
$excludeSrcFilters[] = strtolower($excludeSrc);
}
}
}
/* File: proverbs-api.php Description: This api takes 3 optional inputs, queries a local MongoDB collection using the inputs as filters if needed, then returns a proverb and source in JSON. Inputs: includeSources - comma separated list of sources to include excludeSources - comma separated list of sources to exclude searchTerm - term used to filter results (only letters, numbers, and spaces allowed) Outputs: JSON object with the following fields: source - source of the proverb proverb - text of the proverb */ global $debug; $debug=false; $apiKeyAllowed = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx"; $sourcesAllowed = ['proverbs','shakespeare','emerson','thoreau','rumi','tao te ching']; //Collect Inputs $includeSrcs = (!empty($_GET['includeSources']))?explode(",",$_GET['includeSources']):[]; $excludeSrcs = (!empty($_GET['excludeSources']))?explode(",",$_GET['excludeSources']):[]; //Only keep letters, numbers, and spaces in the search term $searchTerm = (!empty($_GET['searchTerm']))?preg_replace('/[^a-zA-Z0-9 ]/','',$_GET['searchTerm']):''; //Validate source filters $includeSrcFilters=$excludeSrcFilters=array(); foreach($includeSrcs as $includeSrc) { if (in_array(strtolower($includeSrc),$sourcesAllowed)) { $includeSrcFilters[] = strtolower($includeSrc); } } if (empty($includeSrcFilters)) { foreach($excludeSrcs as $excludeSrc) { if (in_array(strtolower($excludeSrc),$sourcesAllowed)) { $excludeSrcFilters[] = strtolower($excludeSrc); } } }
/*
File: proverbs-api.php
Description:
  This api takes 3 optional inputs, queries a local MongoDB collection using
  the inputs as filters if needed, then returns a proverb and source in JSON.
Inputs:
  includeSources - comma separated list of sources to include
  excludeSources - comma separated list of sources to exclude
  searchTerm - term used to filter results (only letters, numbers, and spaces allowed)
Outputs:
  JSON object with the following fields:
  source - source of the proverb
  proverb - text of the proverb
*/
global $debug;
$debug=false;
$apiKeyAllowed = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$sourcesAllowed = ['proverbs','shakespeare','emerson','thoreau','rumi','tao te ching'];

//Collect Inputs
$includeSrcs = (!empty($_GET['includeSources']))?explode(",",$_GET['includeSources']):[];
$excludeSrcs = (!empty($_GET['excludeSources']))?explode(",",$_GET['excludeSources']):[];

//Only keep letters, numbers, and spaces in the search term
$searchTerm = (!empty($_GET['searchTerm']))?preg_replace('/[^a-zA-Z0-9 ]/','',$_GET['searchTerm']):'';

//Validate source filters
$includeSrcFilters=$excludeSrcFilters=array();
foreach($includeSrcs as $includeSrc) {
  if (in_array(strtolower($includeSrc),$sourcesAllowed)) {
    $includeSrcFilters[] = strtolower($includeSrc);
  }
}
if (empty($includeSrcFilters)) {
  foreach($excludeSrcs as $excludeSrc) {
    if (in_array(strtolower($excludeSrc),$sourcesAllowed)) {
      $excludeSrcFilters[] = strtolower($excludeSrc);
    }
  }
}

Next, we use the inputs to construct a MongoDB query, execute the query, and echo the result in JSON format:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
//Make sure this is a valid request, otherwise stop
$headers = apache_request_headers();
if (empty($headers['X-Rapidapi-Proxy-Secret'])) {
die();
} else if ($headers['X-Rapidapi-Proxy-Secret']!==$apiKeyAllowed) {
die();
} else {
//Now we can pull a proverb from the local database
//Decide if we are including or excluding sources
$ORClause = $ANDClause = $OuterANDClause = $OuterANDEND = '';
//Create a filter for sources to include or exclude
if (!empty($includeSrcFilters)) {
$ORClause = '{$or: [';
foreach ($includeSrcFilters as $includeSource) {
$ORClause.='{source : { $regex : /'.$includeSource.'/, $options: '-i' }},';
}
//Trim last comma and close brackets
$ORClause = substr($ORClause,0,-1).']}';
} else if (!empty($excludeSrcFilters)) {
$ANDClause = '{$and: [';
foreach ($excludeSrcFilters as $excludeSource) {
//The brackets in this regular expression define a group of characters.
// These need to be found in the source field. The ^ in front is a negation.
// This means we are excluding records with a source that matches $excludeSrc.
// The i option means it is a case insensitive match
$ANDClause.='{source : { $regex : /[^'.$excludeSrc.']/, $options: '-i' }},';
}
//trim last comma and close brackets
$ANDClause = substr($ANDClause,0,-1).']}';
}
//Now construct the search term clause - this will wrap around any source clause
if (!empty($searchTerm)) {
$OuterANDClause = '{$and: [{proverb : { $regex : /'.$searchTerm.'/, $options: '-i' }},';
$OuterANDEND = ']}';
}
// Do not include the _id field in the results and return 1 random sample of all matching documents
$sampleAggregate = '{ $project: { _id:0 } },{ $sample: { size: 1 } }';
//Single quotes around the parts of the MongoDB command allow us to only escape the operators once.
// If we used double quotes we would need $sample instead (like the $match MongoDB operator below)
//Construct the command to be executed on the server
$mongoCmd = "mongo proverbsdb --quiet --eval "printjson(db.proverbs.aggregate([{$match: $OuterANDClause $ORClause $ANDClause $OuterANDEND}, $sampleAggregate]).toArray())"";
//This line can be used to make sure we are sending a valid command to Mongo
if ($debug) echo "n mongoCmd is $mongoCmdn";
//Backtick notation executes the command as if it was typed in a console
$proverbsJSON = `$mongoCmd`;
echo $proverbsJSON;
}
//Make sure this is a valid request, otherwise stop $headers = apache_request_headers(); if (empty($headers['X-Rapidapi-Proxy-Secret'])) { die(); } else if ($headers['X-Rapidapi-Proxy-Secret']!==$apiKeyAllowed) { die(); } else { //Now we can pull a proverb from the local database //Decide if we are including or excluding sources $ORClause = $ANDClause = $OuterANDClause = $OuterANDEND = ''; //Create a filter for sources to include or exclude if (!empty($includeSrcFilters)) { $ORClause = '{$or: ['; foreach ($includeSrcFilters as $includeSource) { $ORClause.='{source : { $regex : /'.$includeSource.'/, $options: '-i' }},'; } //Trim last comma and close brackets $ORClause = substr($ORClause,0,-1).']}'; } else if (!empty($excludeSrcFilters)) { $ANDClause = '{$and: ['; foreach ($excludeSrcFilters as $excludeSource) { //The brackets in this regular expression define a group of characters. // These need to be found in the source field. The ^ in front is a negation. // This means we are excluding records with a source that matches $excludeSrc. // The i option means it is a case insensitive match $ANDClause.='{source : { $regex : /[^'.$excludeSrc.']/, $options: '-i' }},'; } //trim last comma and close brackets $ANDClause = substr($ANDClause,0,-1).']}'; } //Now construct the search term clause - this will wrap around any source clause if (!empty($searchTerm)) { $OuterANDClause = '{$and: [{proverb : { $regex : /'.$searchTerm.'/, $options: '-i' }},'; $OuterANDEND = ']}'; } // Do not include the _id field in the results and return 1 random sample of all matching documents $sampleAggregate = '{ $project: { _id:0 } },{ $sample: { size: 1 } }'; //Single quotes around the parts of the MongoDB command allow us to only escape the operators once. // If we used double quotes we would need $sample instead (like the $match MongoDB operator below) //Construct the command to be executed on the server $mongoCmd = "mongo proverbsdb --quiet --eval "printjson(db.proverbs.aggregate([{$match: $OuterANDClause $ORClause $ANDClause $OuterANDEND}, $sampleAggregate]).toArray())""; //This line can be used to make sure we are sending a valid command to Mongo if ($debug) echo "n mongoCmd is $mongoCmdn"; //Backtick notation executes the command as if it was typed in a console $proverbsJSON = `$mongoCmd`; echo $proverbsJSON; }
//Make sure this is a valid request, otherwise stop
$headers = apache_request_headers();
if (empty($headers['X-Rapidapi-Proxy-Secret'])) {
  die();
} else if ($headers['X-Rapidapi-Proxy-Secret']!==$apiKeyAllowed) {
  die();
} else {
  //Now we can pull a proverb from the local database

  //Decide if we are including or excluding sources
  $ORClause = $ANDClause = $OuterANDClause = $OuterANDEND = '';

  //Create a filter for sources to include or exclude
  if (!empty($includeSrcFilters)) {
    $ORClause = '{$or: [';
    foreach ($includeSrcFilters as $includeSource) {
      $ORClause.='{source : { $regex : /'.$includeSource.'/, $options: '-i' }},';
    }
    //Trim last comma and close brackets
    $ORClause = substr($ORClause,0,-1).']}';
  } else if (!empty($excludeSrcFilters)) {
    $ANDClause = '{$and: [';
    foreach ($excludeSrcFilters as $excludeSource) {
      //The brackets in this regular expression define a group of characters.
      //  These need to be found in the source field. The ^ in front is a negation.
      //  This means we are excluding records with a source that matches $excludeSrc.
      //  The i option means it is a case insensitive match
      $ANDClause.='{source : { $regex : /[^'.$excludeSrc.']/, $options: '-i' }},';
    }
    //trim last comma and close brackets
    $ANDClause = substr($ANDClause,0,-1).']}';
  }

  //Now construct the search term clause - this will wrap around any source clause
  if (!empty($searchTerm)) {
    $OuterANDClause = '{$and: [{proverb : { $regex : /'.$searchTerm.'/, $options: '-i' }},';
    $OuterANDEND = ']}';
  }

  // Do not include the _id field in the results and return 1 random sample of all matching documents
  $sampleAggregate = '{ $project: { _id:0 } },{ $sample: { size: 1 } }';
  //Single quotes around the parts of the MongoDB command allow us to only escape the operators once.
  //  If we used double quotes we would need $sample instead (like the $match MongoDB operator below)

  //Construct the command to be executed on the server
  $mongoCmd = "mongo proverbsdb --quiet --eval "printjson(db.proverbs.aggregate([{$match: $OuterANDClause $ORClause $ANDClause $OuterANDEND}, $sampleAggregate]).toArray())"";

  //This line can be used to make sure we are sending a valid command to Mongo
  if ($debug) echo "n mongoCmd is $mongoCmdn";

  //Backtick notation executes the command as if it was typed in a console
  $proverbsJSON = `$mongoCmd`;
  echo $proverbsJSON;
}

Step 4.  Create a REST API using the RapidAPI Provider Dashboard

Once we have the data in place, we use the Provider Dashboard to create the API within RapidAPI.

Defining the API name, description, and logo

The first questions we need to answer about the new API are the name, description, and category.  I chose Education as the category which matches the other 2 similar APIs.  There is also a question about how to specify the API, in my case I’ll leave the default UI option selected.  I don’t have a logo so I took a picture of one of the quotes with square dimensions.  One thing I noticed is at some points in the flow of creating an API it is not clear what to do next.  If in doubt, click on each of the links near the top of the dashboard to make sure you’ve filled them out:

Add API Navigation

When you get to the Endpoints page, don’t bother entering anything in the form field.  Click the button to the right which says “Create REST Endpoint”.

Endpoint Interface

Specifying API endpoints and available parameters

On the Edit Endpoint page, you actually specify the path to a specific endpoint. Also, list what parameters are available.  My Proverbs API has one endpoint but it has 3 optional parameters:

Get Proverb Endpoint

On the Edit Endpoint page, you can test your endpoint. This is very important during development.  I used that to find errors in my JavaScript code sent to MongoDB to retrieve proverbs.  The response is written into a text box so breaks are still in HTML instead of being new lines.  For example, the test interface looks like this:
API Endpoint Testing
While the users testing your endpoint see the JSON response rendered like this:

Rendered API Response

Choose API plans and pricing

Once you have your API endpoints defined, it’s time to decide how to monetize your API.  The pricing page is intuitive. But if you want to enforce both a daily and monthly limit for a plan you need to create a new object.  When you create an object you specify associated endpoints and give it a label.

Pricing Plans for new API

 

Provide more detailed documentation about your API

After specifying pricing plans for your API, make sure you specify additional information in the “Docs” tab.  This will appear in the about section of your API as follows:

Additional Documentation Appearance

Conclusion

In this article, we walked through the creation of a MongoDB REST API.  Starting with server configuration, populating data, and adding logic to interact with it.  Finally, we walked through the RapidAPI Provider Dashboard process for adding an API.
 
After publishing your API you also need to consider how to handle API calls.  For testing and development, this is not a concern.  But if you are expecting your API to go viral (or if it has that potential) then make sure your server can handle it.  Using an auto-scaling cloud solution would be ideal. But if you are using a dedicated or VPS host make sure it is easy to upgrade if needed.  Have fun making APIs!

Related

5/5 - (1 vote)
« Top 8 Best Barcode & UPC APIs
How to use a Currency API with Python to Build a Currency Conversion Chart »

Filed Under: MongoDB API Tutorials, PHP API Tutorials, REST API Tutorials Tagged With: create api, how to, how to build an api, mongodb, php

Team RapidAPI

Reader Interactions

Leave a Reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

Build anything with APIs, faster.

Discover, evaluate, and integrate with any API. RapidAPI is the world’s largest API Hub with over 4 Million developers and 35,000 APIs.

Browse APIs »

APIs mentioned in this article

Browse Most Popular APIs
Browse Most Popular APIs

Footer

  • API Guides
  • API Courses
  • API Glossary
  • API Testing
  • API Management
  • Most Popular APIs
  • Free APIs List
  • How to use an API
  • Learn REST API
  • Build API’s
  • About
  • Build APIs
  • Careers
  • Contact Us
  • Write for Us
  • API Directory
  • Press Room
  • Privacy Policy
  • Terms of Use

© 2025 RapidAPI. All rights reserved.

Building an Enterprise API Program
Learn More

×