Python Flask REST API MongoDB CRUD Example


In this post we will implement Python flask REST API MongoDB CRUD example, where CRUD means Create, Read, Update, and Delete operations. So we will perform these CRUD operations on MongoDB. We will create REST or RESTful API using Flask in Python. We need to install the required module Flask-PyMongo for connecting to MongoDB using Flask in Python.


Have Python 3.6.5 installed in Windows (or Unix)

Installing MongoDB in Windows

Example and Source Code

We do not have front-end or User Interface (UI) here. We are building REST or RESTful web services which could be consumed by any consumer. These services are decoupled from consumer. You can use any UI technologies, such as, ReactJSAngularJS or even jQuery, HTML to showcase your data for your users.

Preparing your workspace

Preparing your workspace is one of the first things that you can do to make sure that you start off well. The first step is to check your working directory.

When you are working in the Python terminal, you need first navigate to the directory, where your file is located and then start up Python, i.e., you have to make sure that your file is located in the directory where you want to work from.

For this Python Flask REST API MongoDB CRUD Example, we need modules, such as, flask and flask-pymongo. The module flask works as a web framework and flask-pymongo module is required to establish connection with MongoDB database and query the database using flask in Python programming language.

We will create a project directory flask-rest-mongodb in any physical location of your disk drive.

In subsequent section I may not speak about this project root directory and we will assume that we are talking relative to the project root directory.

Configuring Flask and MongoDB

Create the below script(py is the extension to indicate Python script) where we import the flask module. This file should be created under the project root directory. Notice how we create flask instance.

We have also configured MongoDB database with Flask and we are using here roytuts database.

As we mentioned Installing MongoDB in Windows in the prerequisites section, so you must go through this tutorial to install MongoDB server and create database roytuts.

from flask import Flask
from flask_pymongo import PyMongo

app = Flask(__name__)
app.secret_key = "secret key"
app.config["MONGO_URI"] = "mongodb://localhost:27017/roytuts"
mongo = PyMongo(app)

Creating REST Endpoints

Now we will create REST endpoints for performing CRUD operations.

We will create script under the project root directory. This script is the perfect instance of Python Flask REST API MongoDB CRUD Example. It defines all REST URIs for performing CRUD operations. It will also query MongoDB database server to read, insert, update and delete.

Here, we use http GET, POST, PUT method and DELETE methods for fetching, creating, updating and deleting user from or to MongoDB, respectively.

I have defined only 404 method to handle not found error. You should basically handle required errors, such as, server errors for http responses 500, occurred during the REST API calls.

We convert BSON to JSON using bson.json_util module to avoid serialization error.

We are updating record to or deleting record from MongoDB server using _id value.

The full source code is given below:

from app import app, mongo
from bson.json_util import dumps
from bson.objectid import ObjectId
from flask import jsonify, request
from werkzeug import generate_password_hash, check_password_hash

@app.route('/add', methods=['POST'])
def add_user():
	_json = request.json
	_name = _json['name']
	_email = _json['email']
	_password = _json['pwd']
	# validate the received values
	if _name and _email and _password and request.method == 'POST':
		#do not save password as a plain text
		_hashed_password = generate_password_hash(_password)
		# save details
		id = mongo.db.user.insert({'name': _name, 'email': _email, 'pwd': _hashed_password})
		resp = jsonify('User added successfully!')
		resp.status_code = 200
		return resp
		return not_found()
def users():
	users = mongo.db.user.find()
	resp = dumps(users)
	return resp
def user(id):
	user = mongo.db.user.find_one({'_id': ObjectId(id)})
	resp = dumps(user)
	return resp

@app.route('/update', methods=['PUT'])
def update_user():
	_json = request.json
	_id = _json['_id']
	_name = _json['name']
	_email = _json['email']
	_password = _json['pwd']		
	# validate the received values
	if _name and _email and _password and _id and request.method == 'PUT':
		#do not save password as a plain text
		_hashed_password = generate_password_hash(_password)
		# save edits
		mongo.db.user.update_one({'_id': ObjectId(_id['$oid']) if '$oid' in _id else ObjectId(_id)}, {'$set': {'name': _name, 'email': _email, 'pwd': _hashed_password}})
		resp = jsonify('User updated successfully!')
		resp.status_code = 200
		return resp
		return not_found()
@app.route('/delete/<id>', methods=['DELETE'])
def delete_user(id):
	mongo.db.user.delete_one({'_id': ObjectId(id)})
	resp = jsonify('User deleted successfully!')
	resp.status_code = 200
	return resp
def not_found(error=None):
    message = {
        'status': 404,
        'message': 'Not Found: ' + request.url,
    resp = jsonify(message)
    resp.status_code = 404

    return resp

if __name__ == "__main__":

Related Posts:

Running the Application

Now we are done with coding, so we will run our application by executing the Python script

Once you execute the using command python, then you will see below output in the cmd console as shown in the below image.

python flask rest api mongodb crud example

Testing the Application

We will use REST client here to test our application.

Creating User

python flask rest api mongodb crud example

Reading User

Reading All

Request Method – GET

Request URL – http://localhost:5000/users


[{"_id": {"$oid": "5d1f12a04ecb7854a4b347a4"}, "name": "Soumitra", "email": "", "pwd": "pbkdf2:sha256:150000$yHXEkhfI$1e9241c184dee07faf7ed38814d6c61bff0eaf3f499d63d70267b753dc68c42a"}]
Reading Single

Request Method – GET

Request URL – http://localhost:5000/5d1f12a04ecb7854a4b347a4


{"_id": {"$oid": "5d1f12a04ecb7854a4b347a4"}, "name": "Soumitra", "email": "", "pwd": "pbkdf2:sha256:150000$yHXEkhfI$1e9241c184dee07faf7ed38814d6c61bff0eaf3f499d63d70267b753dc68c42a"}

Updating User

Request Method – PUT

Request URL – http://localhost:5000/update

Request Body

  	"_id": "5d1f12a04ecb7854a4b347a4",
	"name":"Soumitra Roy",

Response – "User updated successfully!"

Deleting User

Request Method – DELETE

Request URL – http://localhost:5000/delete/5d1f12a04ecb7854a4b347a4

Response – "User deleted successfully!"

That’s all. Hope you got an idea on Python Flask REST API MongoDB CRUD Example.

You may also like to read Spring Boot MongoDB CRUD Example.

Source Code

source code

Thanks for reading.

4 Thoughts to “Python Flask REST API MongoDB CRUD Example”

  1. Tim

    I found that if you just do something like this it seems to work better for me. Found example searching the web.

    db_response = mongo.db.user.delete_one({‘_id’: ObjectId(id)})”
    if db_response.deleted_count == 1:

    resp = jsonify(“User id {} was not found!”.format(id))
    resp.status_code = 404
    return resp

  2. Tim

    Thanks, great tutorial!!

    I notice if I pass delete an invalid _id that it still returns a status of 200 with a response value of null. Should I be checking the return value from the “mongo.db.user.delete_one({‘_id’: ObjectId(id)})” call?

    I will research this but would appreciate any input.

  3. Matt

    Lovely guide! Thanks!

    You have a typo in one step. Under “Reading All” the URL you give is missing the /users at the end.

Leave a Comment