Simple REST Server + Python + MongoDB From Zero do Hero

Fernando Raposo
6 min readAug 23, 2019

The objective of this tutorial is to present a step-by-step procedure for creating a small toy system containing the following features:

  1. Use Python to create a Simple REST Server;
  2. Use Python to access a document-oriented NoSQL database (MongoDB);
  3. Use Chrome Poster to interact with our system using HTTP Requests (GET/ POST), browser → server →database; and then database → server → browser.

Prerequisites
In order to develop the code you need to have Python3.x installed . A good tutorial about this can be found here. You must also understand how to use Pip to manage packages and the concepts of virtual environments to use packages and modules that do not come as part of the standard library.
A good IDE is also recommended. I would suggest using VSCode or Pycharm. For this tutorial I decided to use the latter in its Free Community version.

1. Simple REST Server

1.1. First, open PyCharm and create a new Project using Python3.7. Let’s name it myServer. Then create your first Python file, let’s call it moviesREST.py

1.2. Open Terminal and install Flask-Restful using Pip:

$pip install flask-restful

1.3. After the installation of flask-restful is completed, add the following code to moviesREST.py:

from flask import Flask
from flask_restful import Api
from moviesDAO import MoviesDAO

app = Flask(__name__)
api = Api(app)

api.add_resource(MoviesDAO, "/certain-movie/<string:name>")

app.run(debug=True)

By doing this, you are creating a server that will be running on http://127.0.0.1:5000 or http://localhost:5000
The number 5000 after the colon is the port number, and after that you can reference your endpoints. So, the command below is setting an endpoint implemented by MoviesDAO Object that receives a string as a parameter.

api.add_resource(MoviesDAO, "/certain-movie/<string:name>")

As a result, what you want when you put on your browser something like http://localhost:5000/certain-movie/jaws is to tell the browser to send a HTTP GET Request to our “myServer” server. It connects to “certain-movie” endpoint, passing a parameter string “jaws”, which is last piece of the URL.
So far, we have not talked about MoviesDAO, so let’s talk about it now…

1.4. Next, create a new Python file named moviesDAO.py and paste this code:

from flask_restful import Resource


class MoviesDAO(Resource):

def get(self ,name):
if name == 'jaws':
return 'Jaws Found!', 200
return 'Jaws Not Found!', 404

This means that your endpoint, if receiving a GET Request, will take the parameter received and check if it is equal to “jaws” or not.
If the string is equal, it will return the message “Jaws Found!” followed by code 200. Whereas, it will return “Jaws Not Found” followed by code 404 if unequal.
Always try to use the code that suits best for the case. You can learn more about it here. It’s valid to mention that you are returning more than one parameter (a string and a number). This is OK in Python, but a bit strange if you are used to other languages like Java or C.

2. Access Remote MongoDB

MongoDB is a Free document NoSQL database typically used for high volume data storage. Its 5th position in the top database engines shows that its use has been increasing recently. When we say MongoDB stores documents, we can imagine sets of JSON objects that are easily accessed in a way similar to what SQL does on Relational Databases.

 { "name":"Caroline", "age":54, "car":"Volvo" }

The object above can be a document stored at MongoDB, or simply a JSON Object. The cool thing is that Python Dictionaries are very close to JSON Objects allowing Python to support JSON almost natively. Now, you will create your MongoDB base to later connect it to your server “myServer”.

2.1. MongoDB Atlas is a free solution that provides a cloud MongoDB available to anyone. Despite the free version limitations, it is perfect to study purposes. Go here and follow the steps to create an account.

2.2. Follow the MongoDB Atlas tutorial, create an user, define password… and make sure to load the Sample Dataset to your Cluster Collections. We are interested on loading specially the sample_mflix collection which we will use as our remote film catalog.

2.3. Once the Sample Dataset is created, let’s access it from outside! On the MongoDB Atlas control panel displayed below, go to Clusters and click on CONNECT button. When the box appears, select “Connect Your Application”.

2.4. Then, as shown below, choose Python and version 3.6 or later on driver version(1). Next, copy the text on (2)“Full Driver Example”. Now go back to Pycharm…

2.5. On Pycharm, create a new file called connector.py and adjust the copied text from MongoDB Atlas as shown below. The code is creating a database connection.

The MongoDB connection

2.6. Also, we need to install pymongo using Pip.
So, on Terminal enter:

$pip install pymongo

Now, go back to refactor moviesDAO.py as shown below:

from connector import get_connection
from flask_restful import Resource


conn = get_connection('<user>', '<password>')
colection = conn['sample_mflix']['movies']


class MoviesDAO(Resource):

def get(self,name):
myquery = {'title':name}
mydoc = colection.find_one(myquery)
if mydoc is not None:
return mydoc['title'], 200
return 'Movie Not Found', 404

2.7. Above, first, you import the function “get_connetion” that was developed inside file connector.py. The get_connection function receives the username and password you defined at MongoDB Atlas and returns a connection. Calling “conn[‘sample_mflix’][‘movies’]” is enough to get the movies collection that is inside sample_mflix database. The get method from class MoviesDAO was also changed, as it creates a query to search for a title with the name the request receives as a parameter. Now, it is time to start your server.

3. Running Service + Chrome Poster

3.1. On Pycharm, go to movieREST.py and press Ctrl + Shift + F10. This will start your server. Then, as presented below, you will see on console that the server is up and running on http://127.0.0.1:5000

The Server Running

3.2. In order to test our calls to the server, I suggest using Chrome Poster Extension. It is small and straightforward. Install it and open it writing on URL as shown below and press GET:

3.3. You will receive a return code (200) from the server and the text returned by the MongoDB. As an exercise try to put something else instead of “Jaws” and see the results. And we are Done! We have a REST server in Python running on port 5000 capable of receiving requests to search on MongoDB.

3.4. As a bonus, on GitHub you will find an addition to MoviesDAO.py containing a POST Request that you can invoke on Poster, for instance, to search for a movie with a piece of a string, not necessarely the exact name. Below, you see a search to any movie that has “Planet Of” as substring of its title.

Conclusion

I hope this tutorial was usefulto you in a way that it could be a starting point to something bigger.

Comments, suggestions, ideas…
LinkedIn

--

--

Fernando Raposo

Computer Scientist, MSc UFPE — JAVA, PL/SQL, Angular, Python, Software Testing