Make Python API to access Mongo Atlas Database

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

filter_none

edit
close

play_arrow

link
brightness_4
code

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)

chevron_right


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.
filter_none

edit
close

play_arrow

link
brightness_4
code

from flask import Flask, jsonify, request
from flask_cors import CORS
import pymongo
  
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)

chevron_right


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




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.