Integrating Flask With MongoDB

Image from Pexels

hello and welcome to my another post this time I will discuss how Flask integration with Mongo DB

now Before starting we have to know what to be prepared first, like

  • Installing Mongo DB on Your Server
  • Install MongoDB Management Tools

In this time we only dicuss about Integrating Flask with Mongo DB, in this case we create simple project named flaskr-mongo it is a simple Blog API project that applies flask and Mongo DB

in this section we will creating Project following this structure

.├──└── projects└──

before we code we must selecting package for mongo connector first, below is available package and ready to use for integrate flask and mongo DB

free to use whichever one, but in this post, I will use MongoEngine

Project Concept

in This Project, we will create a project blog, that includes

  • title
  • post contents

the structure of the project will be like this

now let’s code

first, install the required library

  • flask
  • flask-restful
  • flask-mongo-engine

install with pip

pip install flask flask-restful flask-mongoengine

after install create a package named projects and initialize your flask application

now let’s create a model for mapping data

after creating models, the next step is to create a database for our application, in this case, I using Mongo DB compass to manage my mongo database, you can download it here

Creating Database

The next step after downloading is creating a database, to create the database you need to open your mongo compass and create database

creating a database using mongo compass

the Collection name is the same as your models in your, in my case my models named Posts

Configure the Application

the next step is creating a config file for your application to set up your application integrates with mongo database or many other, create file config named inside projects directory

in we create database connection config and many other configs on there, now let’s set up to automate running for our Application using Makefile

because I run this project on Linux you can set it up like this

now you can run in a terminal using this command

make run-dev
run project automatically using makefile

Creating Views to Implement CRUD Operation

now in this step, we will create a view to implementing CRUD (Create, Read, Update, Delete) Operations for your Application

Defining Route for Our Blog API Projects

in the last step, we define a route for our views, which we just created in the previous step

now our application, in this case, I use Postman

get Data List
Get Specific Data

with Mongo DB we can process data more easily just like we process JSON files or dictionaries and lists in python, thank you for reading, hopefully, it’s useful, click here to join our community, source code available on Github

Interesting with Blockchain and Opensource Project my journal: