Make Python API to access Mongo Atlas Database
Last Updated :
08 Jun, 2020
Prerequisite: Python | Build a REST API using Flask
RESTful APIs are a very helpful tool to manage the backend of an application. It can be used to define the architecture as well as manage the dependencies of the application using routes managed by the API. Flask is a popular micro framework for building web applications.
In this article, we will learn how to make a Flask RESTful API that connects to the MongoDB Atlas database service by MongoDB. Before that, you have to make a user account on MongoDB Atlas using your email address.
Once you are done with the initial setup. Follow the steps below:
- Step1: Make your new project, by clicking on the 'New Project' button. Give your project a name and add members (if any) to how you want to give access to the project. Create a project by clicking on the 'Create Project' button. Your dashboard should look like this.

- Step 2: Click on 'Build a cluster'. Select 'Shared cluster' from the pop-up. Select the required setting. For example : AWS Cloud provider and Mumbai region. You will be given 512MB space on the cloud for hosting your database. Create Cluster. Your dashboard will look like this.

- Step 3: Now, click on 'Connect'. It will open a dialog box. Follow the instructions shown. Add your IP Address to the white list. This is the list of IP addresses that can access the database. Next, create your username and password for accessing the database. Now, click on 'Choose a connection method'.
- Step 4: Now, click on 'Connect your application' on the new dialog box that appears. Select 'Python' in Driver dropdown and '3.6 or later' in Version dropdown. Copy the link in the next line. It would look like:
mongodb+srv://admin:<password>@cluster0-pm5vp.mongodb.net/test?retryWrites=true&w=majority
- Step 5: Your username appears in the link (here, admin). Replace <password> with the password for this user.
This is the link or the URL which connects your Python API to the database. Now, create a sample database by clicking the 'Collections' tab on your dashboard and making a new database by clicking 'Add My Own Data'. Give you a database name and a table name and finish creating a new database.
For this example, I have created a database named 'Example' and a table named 'SampleTable'.
The below python code links to your MongoDB Atlas database using pymongo.
Note: Please install following libraries to run the flask API : flask, pymongo, dnspython, flask_cors
python3
from flask import Flask
from flask_cors import CORS
import pymongo
# Replace your URL here. Don't forget to replace the password.
connection_url = 'mongodb+srv://admin:<password>@cluster0-pm5vp.mongodb.net/test?retryWrites=true&w=majority'
app = Flask(__name__)
client = pymongo.MongoClient(connection_url)
# Database
Database = client.get_database('Example')
# Table
SampleTable = Database.SampleTable
if __name__ == '__main__':
app.run(debug=True)
This will initiate a flask server on your http://localhost/5000 which will be connected to your MongoDB Atlas Database. On successfully execution, the console will look like:
Now you can create routes in the API and define functions to interact with the database. Given below is an example on how to map routes and use them to receive values and interact with the database.
- route(path, methods): is used to define the path through which you can call the corresponding functions. '<SomeData>' is used to extract values from the path.
For example, for the insert function below, the path contains <name>, <id>, which means that the value in the path after the 'insert-one/' will be stored into name and the value after that will be stored in id. methods is used to define the type of methods the function will accept. You can read about from here.
- jsonify(object): is used to created a JSON object from the object passed.
- insert_one(object): is used to insert the passed object into the collection from which it is called.
- find_one(object): is used to find the object in the database which matches with the object passed as a key in the parameters. It returns whole document as an object. This method returns the first object that matches the passed key values.
- find(object): is used to find all the objects which matches the passed key values.
- update_one(object): is used to update the value of some object in the database which matches certain passed key values.
python3
from flask import Flask, jsonify, request
from flask_cors import CORS
import pymongo
connection_url = 'mongodb+srv://admin:samplearticle@cluster0-pm5vp.mongodb.net/test?retryWrites=true&w=majority'
app = Flask(__name__)
client = pymongo.MongoClient(connection_url)
# Database
Database = client.get_database('Example')
# Table
SampleTable = Database.SampleTable
# To insert a single document into the database,
# insert_one() function is used
@app.route('/insert-one/<name>/<id>/', methods=['GET'])
def insertOne(name, id):
queryObject = {
'Name': name,
'ID': id
}
query = SampleTable.insert_one(queryObject)
return "Query inserted...!!!"
# To find the first document that matches a defined query,
# find_one function is used and the query to match is passed
# as an argument.
@app.route('/find-one/<argument>/<value>/', methods=['GET'])
def findOne(argument, value):
queryObject = {argument: value}
query = SampleTable.find_one(queryObject)
query.pop('_id')
return jsonify(query)
# To find all the entries/documents in a table/collection,
# find() function is used. If you want to find all the documents
# that matches a certain query, you can pass a queryObject as an
# argument.
@app.route('/find/', methods=['GET'])
def findAll():
query = SampleTable.find()
output = {}
i = 0
for x in query:
output[i] = x
output[i].pop('_id')
i += 1
return jsonify(output)
# To update a document in a collection, update_one()
# function is used. The queryObject to find the document is passed as
# the first argument, the corresponding updateObject is passed as the
# second argument under the '$set' index.
@app.route('/update/<key>/<value>/<element>/<updateValue>/', methods=['GET'])
def update(key, value, element, updateValue):
queryObject = {key: value}
updateObject = {element: updateValue}
query = SampleTable.update_one(queryObject, {'$set': updateObject})
if query.acknowledged:
return "Update Successful"
else:
return "Update Unsuccessful"
if __name__ == '__main__':
app.run(debug=True)
Output: The above code respond differently for different URL requests.
- insert-one request: http://127.0.0.1:5000/insert-one/chitrank/1/
This inserts the below object into the collection SampleTable and returns 'Query Inserted...!!!' after inserting the document.
{
style="color:rgb(80,80,80);background-color:rgb(255,255,255);"> 'Name' : 'chitrank' ,
'ID' : '1',
}

- find-one request: http://127.0.0.1:5000/find-one/Name/chitrank/
This request will return an object which matches the values passed in the URL. The returned object will be displayed on the browser window.

- find request: http://127.0.0.1:5000/find/
This request will return all the objects in the calling table. The returned objects will be displayed on the browser window.

- update-one request: http://127.0.0.1:5000/update/ID/1/Name/GeeksForGeeks/
This request will update the object which matches the first two parameter with the last two values. It will return 'Updated Successfully' on successful update
These are some basic operations which I have referred here. These are more than enough to manage a database. MongoDB provides a wide range of operations about which you can read fromMongoDB Official Documentation
Similar Reads
Create a database in MongoDB using Python
MongoDB is a general-purpose, document-based, distributed database built for modern application developers and the cloud. It is a document database, which means it stores data in JSON-like documents. This is an efficient way to think about data and is more expressive and powerful than the traditiona
2 min read
Sending Data from a Flask app to MongoDB Database
This article covers how we can configure a MongoDB database with a Flask app and store some data in the database after configuring it. Before directly moving to the configuration phase here is a short overview of all tools and software we will use. MongoDB is an open-source database that stores data
5 min read
How to Create a MongoDB Dump of Database
MongoDB is a popular NoSQL database known for its flexibility, scalability, and ease of use. However, to protect our data from potential data loss or corruption, itâs critical to have a reliable MongoDB backup strategy in place. In this article, we will go through the process of creating a MongoDB d
7 min read
How to Connect Node to a MongoDB Database ?
Connecting Node.js to MongoDB is a common task for backend developers working with NoSQL databases. MongoDB is a powerful, flexible, and scalable database that stores data in a JSON-like format. In this step-by-step guide, we'll walk through the entire process from setting up your development enviro
6 min read
How to Back Up and Restore a MongoDB Database?
MongoDB is considered one of the classic examples of NoSQL systems. Its documents are made up of key-value pairs, which are the basic unit of data in MongoDB. Whether we're dealing with accidental data loss, hardware failures, or other unforeseen issues, having a solid backup and restoration plan ca
5 min read
How To Connect MongoDB Database in a Node.js Applications ?
To connect MongoDB to a Node.js application, you can follow a simple process using the Mongoose library, which provides a flexible way to work with MongoDB. Mongoose acts as an Object Data Modeling (ODM) library, making it easier to structure and interact with MongoDB from Node.js.Prerequisites:Node
2 min read
How to Rename a MongoDB Database?
Renaming a MongoDB database may be necessary for various reasons such as reorganization or clarity. MongoDB provides several methods for renaming a database including using shell commands, dumping and restoring data or directly manipulating database files.In this article, we will learn different app
4 min read
How to use MongoDB atlas to save data ?
As modern applications require a database for storing data, MongoDB is a great choice. MongoDB Atlas is the global cloud database service for modern applications. We can use it for storing our application data on its server. Follows these steps for how to use MongoDB Atlas for saving data:Step 1: Vi
3 min read
How to Create Database and Collection in MongoDB
MongoDB is a widely used NoSQL database renowned for its flexibility, scalability, and performance in managing large volumes of unstructured data. Whether youâre building a small application or handling big data, MongoDB offers an easy-to-use structure for managing your data. In this article, we wil
6 min read
MongoDB - Create Database using Mongo Shell
MongoDB is a popular NoSQL database that uses collections and documents, which are highly flexible and scalable. Unlike relational databases (RDBMS), MongoDB does not use tables and rows but stores data in a more dynamic, JSON-like format. In this article, we'll explore how to create a MongoDB datab
4 min read