Featured image of post Integrating Flask With Mongodb

Integrating Flask With Mongodb

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

Project Concept

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

  • title
  • post content

the structure of the project will be like this

├── Makefile
├── projects
│   ├── blog
│   │   ├── api
│   │   │   ├──
│   │   │   ├──
│   │   │   └──
│   │   ├──
│   │   └──
│   ├──
│   └──
└── requirements.txt

Creating Project

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

Installing Library

install library with pip

pip install flask flask-restful flask-mongoengine

Create Base Project Structure

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

# projects/
import os

from flask import Flask
from flask_mongoengine import MongoEngine

from import blog_api_blueprint

db = MongoEngine()

def create_app():
    app = Flask(__name__, static_url_path='')

    # set config
    app_settings = os.getenv('APP_SETTINGS')

    # setup extension


    # shell context for flask cli
    def ctx():
        return {'app': app, 'db': db}

    return app

Creating Models

now let’s create a model for mapping data

# projects/blog/
import mongoengine as me
from datetime import datetime

class Posts(me.Document):
    title: str = me.StringField(required=True, max_length=200)
    contents: str = me.StringField(required=True)
    created_on = me.DateTimeField(

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

Create Database
Create Database

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

Configure Applications

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

import os

class BaseConfig:
    TESTING: bool = False
    SECRET_KEY: str = '@Flaskr-MongoSeCretKeyS'
    DEBUG: bool = False

class DevelopmentConfig(BaseConfig):
    MONGODB_SETTINGS: dict = {
        'db': 'flask_blog_db',
        'host': 'localhost',
        'port': 27017
    BASE_DIR = os.path.abspath(os.path.dirname(__file__))

class ProductionConfig(BaseConfig):

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

	export && export FLASK_ENV=development && export APP_SETTINGS='projects.config.DevelopmentConfig' && flask run

now you can run in a terminal using this command

make run-dev

run flask using makefile
run flask 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 our Application

from flask_restful import abort, fields, marshal_with, Resource, reqparse
from flask import jsonify
from import Posts

# reqparse
posts_parser = reqparse.RequestParser()
posts_parser.add_argument('title', type=str, help="Title is Required", required=True)
posts_parser.add_argument('contents', type=str, help='Contents is Required', required=True)

posts_update = reqparse.RequestParser()
posts_update.add_argument('title', type=str)
posts_update.add_argument('contents', type=str)

# resource fields
resource_fields = {
    'id': fields.String,
    'title': fields.String,
    'contents': fields.String

# views
class PostListView(Resource):
    def get(self):
        posts = Posts.objects()
        return jsonify(posts)

    def post(self):
        args = posts_parser.parse_args()
        posts = Posts(title=args['title'], contents=args['contents'])
        return jsonify({'Messages': 'Data Posted Successfullly'}), 201

class PostDetailView(Resource):

    def get(self, post_id: str):
        post = Posts.objects.get(id=post_id)
        if not post:
            abort(404, message=f"Post with id: {post_id} not found")
        return post

    def put(self, post_id: str):
        args = posts_update.parse_args()
        if args['title']:
        if args['contents']:
        return jsonify(Posts.objects.get(_id=post_id).first()), 200

    def delete(self, post_id: str):
        posts = Posts.objects(id=post_id)
        return jsonify({"message": f"Post with id {post_id} Deleted"}), 204

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

from flask import Blueprint
from flask_restful import Api

# API Blueprint
from import PostListView, PostDetailView

blog_api_blueprint = Blueprint('blog', __name__, template_folder='templates', static_folder='static')
blog_api = Api(blog_api_blueprint)

# routes
blog_api.add_resource(PostListView, "/blog/api/posts/")
blog_api.add_resource(PostDetailView, "/blog/api/posts/<post_id>/")

Test Our Application

now our application, in this case, I use Postman

Get Blog List
Get Blog List

Get Spesific Data
Get Spesific 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

Licensed under CC BY-NC-SA 4.0
Last updated on Jan 13, 2022 18:08 +0700
comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy