REST API Using Python Flask & MongoDB

Creating REST API Using Python Flask & MongoDB

In this tutorial you’ll learn how to create a REST API using Python Flask & MongoDB. This is the second part of the creating a contact manager web app using Angular, Python, MongoDB series. The REST APIs created in this tutorial will be consumed by the Angular web application.

Source code from this tutorial is available on GitHub.

Getting Started With Python Flask

Assuming that you have Python2.7 installed on your system, let’s start by installing flask using pip.

# install flask
pip install flask

Once you have installed flask, create a project directory called PythonMongoAPI. Navigate to the directory and create a file called app.py. Add the following code to app.py :

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Welcome to Python Flask!"

Save the above changes and start the flask app using the following command:

# run the flask app
FLASK_APP=app.py flask run

You will have the application running at http://localhost:5000/.

Getting Started With PyMongo

To connect Python Flask with MongoDB you’ll using a connector called PyMongo. Learning how to get started and working with PyMongo is quite easy. I recommend reading the beginners guide on how to do the basic CRUD operation using PyMongo.

You can install PyMongo using pip.

# install PyMongo
pip install pymongo

Once you have PyMongo installed in your project, you can import the client into app.py and start using it.

# importing PyMongo client
from pymongo import MongoClient

Creating POST REST API Using Python Flask & MongoDB

Let’s start by creating a REST API to add a contact to the MongoDB database. Define a route called add_contact which will accept POST requests to add a new contact to MongoDB.

@app.route("/add_contact", methods = ['POST'])
def add_contact():
    try:
        # code will be here
    except Exception, e:
        # code will be here

Once the request is received in the add_contact route, you need to parse the request data. To use the request object you need to import the request library.

# import request module 
from flask import request

Using the request module parse the data posted to the add_contact REST endpoint and the JSON request to an object. You’ll need to import json module to load the request.data.

# import json module
import json

You can load the json data and parse the request.data.

data = json.loads(request.data)
user_name = data['name']
user_contact = data['contact']

Validate the user_name and user_contact before inserting the data to the MongoDB collection. You’ll making use of the insert_one method to insert the data to the MongoDB collection.

if user_name and user_contact:
    status = db.Contacts.insert_one({
        "name" : user_name,
        "contact" : user_contact
    })

Once the data has been inserted successfully to the MongoDB database a success message will be returned.

Here is how the complete REST API code looks :

from flask import Flask
from flask import request
from pymongo import MongoClient
from bson.json_util import dumps
import json

client = MongoClient('localhost:27017')
db = client.ContactDB

app = Flask(__name__)

@app.route("/add_contact", methods = ['POST'])
def add_contact():
    try:
        data = json.loads(request.data)
        user_name = data['name']
        user_contact = data['contact']
        if user_name and user_contact:
            status = db.Contacts.insert_one({
                "name" : user_name,
                "contact" : user_contact
            })
        return dumps({'message' : 'SUCCESS'})
    except Exception, e:
        return dumps({'error' : str(e)})

Save the above changes and restart the Python flask application. You will have the Add Contact REST API endpoint running at http://localhost:5000/add_contact.

Creating GET REST API Using Python Flask & MongoDB

Creating the GET REST API endpoint is the easier one, since you need to fetch data from the MongoDB database. You’ll be making use of the collection.find() method to get all the contacts from the MongoDB collection. Here is how the GET REST API endpoint looks:

@app.route("/get_all_contact", methods = ['GET'])
def get_all_contact():
    try:
        contacts = db.Contacts.find()
        return dumps(contacts)
    except Exception, e:
        return dumps({'error' : str(e)})

Save the above changes and restart the Python flask application. You will have the REST API endpoint to get all contacts running at http://localhost:5000/get_all_contact.

Final Thoughts

In this tutorial, you saw how to get started with creating a REST API Using Python Flask & MongoDB. You used PyMongo connector to connect Python Flask to the MongoDB database.

In the next part of this tutorial, you’ll be using these two REST API endpoints in the Contact Manager Angular web app that you created in the previous tutorial.

Source code from this tutorial is available on GitHub.

Do let us know thoughts and suggestions in the comments below.