Using MongoDB in Flask (Basics)

Hey peeps, I imagine you all have gone through with understanding of REST api in our previous blogs, basically this and this. Also, do see the REST URL naming conventions to follow the best practises and grow your code in the best way.

pymongo

MongoDB

The purpose of showing MongoDB to you introduce you guys to NoSQL databases. The thinking that – NoSQL is slower than SQL is quite wrong as MongoDB has proved to be much better in both SQL and NoSQL (Not only SQL) use cases. Also, MongoDB provides a hugeeeeee variety of aggregations and indices which, believe me, makes it seriously unique and use case friendly.

To learn more about MongoDB, visit documentation.

We will be using PyMongo for our course. You may also use PyModm, it makes MongoDB to be used as an ODM (generally for Django users).

Let’s Create Our Site

We will be creating an app to demonstrate a backend developed for a Blog.

Let’s create 2 endpoints –

  • /eazydevelop/blog – POST – To create a new blog
  • /eazydevelop/blog – GET – To retrieve list of all blogs.

Make a file “blog.py” and write this code inside. You can also get the full code over in this gist. You will find the whole explanation below the code.

Creating The Connection

We have to add (lines 8-10) in order to make a connection to our MongoDB database, using client to make a connection. The object db connects (or creates if not present) to the database – “blogdb” in our mongodb database. Now, we create two collections (think of them as SQL tables), one for blogs and one for articles. (We will be talking about articles later). These global objects have been created for every API that we make. Open a connection just once, globally as your whole backend is connected via that connection, and not inside each API as it would overload the MongoDB server.

Creating New Blogs

Now, as you see, we have written the creation of object in MongoDB inside POST request as POST HTTP verb means creation of resources (blog over here). Therefore, as MongoDB works on JSON data objects, lines 22-31 we insert an object (a blog) into our database having fields – blog name, created by, created on. Created on is assigned the current timestamp using datetime package in python. We return the ID of the created object back to the UI/UX for them to keep track of the object. Let’s see how…!

To test this API, just open Postman and go to http://localhost:5000/eazydevelop/blog via POST request and pass in the required parameters in the body in JSON format. Write down the generated ID for further use below. (case-sensitive)

Retrieving The Blogs

Now let’s write the some code in the part where we accept GET requests in the blog endpoint. This will be line 35 onwards.

We now find all the blogs in the database by calling the .find() function of the collection object (line 37). We have passed in 2 arguments to the find function, the first is an empty dict object, as we do not want to filter any data and return all the data. The next one is the project each document (row) of the collection from which we can remove the “_id” field in each document. This is done as we need to write our own custom BSON encoder to return ObjectID in mongo docs, so right now we will just remove it in the output and chillax. Finally let’s create a list of the result and return it from the view.!!

To test this API, just open Postman and go to http://localhost:5000/eazydevelop/blog via GET request.

Retrieving A Single Blog

Now here comes the difference of the use case. Above, we retrieved the whole list of blogs, but not a single blog. We could also have received a single blog by putting the blog ID as a query parameter. But that would mean filter the blogs and return ALL blogs that match that ID. As we know there should be a single blog, having its own URI, we will make another endpoint which will EMBED the ID into the url, as a URL parameter. So we make another view (function) which takes in the ID as a part of URL itself. (line 46 onwards).

We now use this ID to find the only document present with that ID and return it as response. Also note that the ID in MongoDb is a ObjectId type, so we type case the passed “blog_id” into ObjectId and again typecast the result’s ID to string.

To test this API, just open Postman and go to http://localhost:5000/eazydevelop/56213tsadj1 via GET request. Do change the blog_id with the blog_id you noted above. If you forgot to note it down, insert another blog and get its ID from the output.

You can get the full code here.

Voila..! We have learnt to use MongoDB with Flask. Now to explore more, explore the API Docs of MongoDB from here and try to use them with Flask. Cheers..! Follow our blog below to get the notified of more posts.!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Powered by WordPress.com.

Up ↑

%d bloggers like this: