Flask REST API MongoDB CRUD Example

Flast REST API Mongo CRUD

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

Prerequisites

Python 3.6.5/3.11.5, Flask 2.3.3/3.0.0, Werkzeug 3.0.1, Flask-PyMongo

Installing MongoDB in Windows

I do not have front-end or User Interface (UI) for this example as I am 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.

Make sure you have the database roytuts (use roytuts command to create from CLI) in Mongo.

Also make sure you have the collection called user (db.createCollection('user') command to create from CLI) in Mongo.

Preparing 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, you need modules, such as, flask, werkzeug and flask-pymongo. The module flask works as a web framework, werkzeug is required for security purpose, for example, hashing the plain text password and flask-pymongo module is required to establish connection with MongoDB database and query the database using flask in Python programming language.

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

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

Flask and MongoDB Config

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

I have also configured MongoDB database with Flask and I am using here roytuts database.

As I 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)

REST Endpoints

Now I will create REST endpoints for performing CRUD operations.

I will create main.py 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, I 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.

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

I am 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 werkzeugy.security 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_one({'name': _name, 'email': _email, 'pwd': _hashed_password})
		resp = jsonify('User added successfully!')
		resp.status_code = 200
		return resp
	else:
		return not_found()
		
@app.route('/users')
def users():
	users = mongo.db.user.find()
	resp = dumps(users)
	return resp
		
@app.route('/user/<id>')
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
	else:
		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
		
@app.errorhandler(404)
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__":
    app.run()

Related Posts:

Running the Flask MongoDB Application

Now I am done with coding, so I will run our application by executing the Python script main.py.

Once you execute the main.py using command python main.py or simply main.py if you have configured the Python on system path, 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 Flask Mongo Application

I will use REST client here to test the Flask Mongo application.

Create User

Request Method: GET

Request URL: http://localhost:5000/add

Request Body JSON:

{
	"name":"Soumitra",
	"email":"contact@roytuts.com",
	"pwd":"pwd"
}

Response: “User added successfully!”

Read User

Read All Users

Request Method: GET

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

Response:

[{"_id": {"$oid": "6544bf46b0be664659e12d62"}, "name": "Soumitra", "email": "contact@roytuts.com", "pwd":
"pbkdf2:sha256:600000$CqFDKAz9QrSs2YFF$1e48afae5de2a5bb71821aa474942993436ef812df752ee5a627bc690c7c5e39"}]

Read Single User

Request Method: GET

Request URL: http://localhost:5000/6544bf46b0be664659e12d62

Response:

{"_id": {"$oid": "6544bf46b0be664659e12d62"}, "name": "Soumitra", "email": "contact@roytuts.com", "pwd":
"pbkdf2:sha256:600000$CqFDKAz9QrSs2YFF$1e48afae5de2a5bb71821aa474942993436ef812df752ee5a627bc690c7c5e39"}

Update User

Request Method: PUT

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

Request Body:

{
  	"_id": "6544bf46b0be664659e12d62",
	"name":"Soumitra Roy",
	"email":"contact@roytuts.com",
	"pwd":"pwd"
}

Response: "User updated successfully!"

Delete User

Request Method: DELETE

Request URL: http://localhost:5000/delete/6544bf46b0be664659e12d62

Response: "User deleted successfully!"

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

Source Code

Download

2 thoughts on “Flask REST API MongoDB CRUD Example

  1. 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:

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

  2. Roy,
    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.

Leave a Reply

Your email address will not be published. Required fields are marked *