Skip to content

WebNinjaDeveloper.com

Programming Tutorials




Menu
  • Home
  • Youtube Channel
  • Official Blog
  • Nearby Places Finder
  • Direction Route Finder
  • Distance & Time Calculator
Menu

Build a Python CRUD REST API in Flask and MongoDB Using Flask-PyMongo Library in Browser

Posted on November 22, 2022

 

 

Welcome folks today in this blog post we will be building the python crud rest api in browser using flask and mongodb database. For this we will be using the flask-pymongo library.

 

 

Get Started

 

 

In order to get started you need to install the dependencies using the pip command as shown below

 

 

pip install flask_pymongo

 

 

pip install bcrypt

 

 

As you can see we are installing the above dependencies inside the flask project. Now we need to create the app.py file and copy paste the following code

 

 

app.py

 

 

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
from flask import Flask
from flask_pymongo import PyMongo
from bson.json_util import dumps
from bson.objectid import ObjectId
from flask import jsonify,request
from werkzeug.security import generate_password_hash,check_password_hash
 
app = Flask(__name__)
app.secret_key = "secretkey"
 
app.config['MONGO_URI'] = "mongodb://localhost:27017/crud"
 
mongo = PyMongo(app)
 
if __name__ == "__main__":
    app.run(debug=True)

 

 

As you can see we are importing the required libraries such as the flask and also the flask_pymongo library. And then we are making the new flask app. And also we are setting the secret key and also we are setting the config url of the mongo database. And here as you can see the mongodb uri contains the port number which is 27017 and also we have the mongodb database which is crud here. And then we are wrapping the flask app inside the PyMongo constructor. And then we are starting the flask app using the run() method.

 

 

Creating the Database in MongoDB

 

 

You can start the MongoDB Compass desktop software and then we can create a new database as shown below

 

 

 

 

And now if you run the app.py file inside the console you will see the below screenshot in browser

 

 

 

As you can see if you open 404 error will be there. This indicates that there is route specified for this as shown above.

 

 

Configuring the Routes

 

 

Now guys we will be configuring the routes inside the flask app as shown below

 

 

Adding the Users in MongoDB Database

 

 

Now guys we will be adding the users inside the mongodb database. For this we will be using the post route. So you need to copy paste the below code

 

 

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@app.route('/add',methods=['POST'])
def add_user():
    _json = request.json
    _name = _json['name']
    _email = _json['email']
    _password = _json['password']
 
    if _name and _email and _password and request.method == "POST":
 
        _hashed_password = generate_password_hash(_password)
 
        id = mongo.db.user.insert({'name':_name,'email':_email,'password':_hashed_password})
 
        resp = jsonify("User Added successfully")
 
        resp.status_code = 200
 
        return resp
 
    else:
 
        return not_found()

 

 

As you can see in the above code we are writing the post route which is /adduser inside this we have defined the method add_user(). Here we are getting all the required json request data submitted by the user. Here we are using the json property of the request object. And then we are getting the name,email and password fields that the user submits while making the post request in postman. And then we are comparing if the name,email and password data exist and then we are checking the request method if it is post or not. If it is post we are converting the normal password to the hashed password using the generate_password_hash() function. And then we are inserting the details to the mongodb database using the insert() method And here we are inserting the name,email and password. And then we are returning the json response back to the client using the jsonify() method. And then we are also returning the status code and also the response as well. And in the else block if the data is not send alongside with the post request we will show the 404 error message using the not_found() method.

 

Now we need to define this not_found() method as shown below

 

 

Python
1
2
3
4
5
6
7
8
9
10
11
@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

 

 

As you can see in the above code we are defining the 404 error function we are defining the json object which contains the two properties which is the status and the message of the error. And then we are returning the 404 status code. And also returning the response as well.

 

Now if you open the postman http client and make the post request to the specified url which is http://localhost:5000/add and pass the json data as shown below. You will get the message that the users has been successfully added and also a user record will be inserted inside the mongodb database

 

 

 

 

 

Getting all the Users From MongoDB Database

 

 

Now we will be writing the simple GET route where if you go we will be returning all the added users inside the mongodb database as shown below

 

 

Python
1
2
3
4
5
@app.route('/users')
def users():
    users = mongo.db.user.find()
    resp = dumps(users)
    return resp

 

 

As you can see we have written the route which is /users and for this we have defined the method which is called users() and inside this method we are fetching all the users present inside the user collection in mongodb database using the find() method and then we are returning the users as the json response back to the client using the dumps() method.

 

Now if you make the get request to the route /users inside the postman you will get the below json response

 

 

 

 

Getting Specific User Information Using ID From MongoDB Database

 

 

Now we will be writing the simple GET route where if you go we will be returning a specific user information which is present inside the mongodb database as shown below

 

 

Python
1
2
3
4
5
@app.route('/users/<id>')
def user(id):
    user = mongo.db.user.find_one({'_id':ObjectId(id)})
    resp = dumps(user)
    return resp

 

 

As you can see we have written the route which is /users/<id>and for this we have defined the method which is called user(id) and inside this method we are only fetching the specific user information using it’s id which is passed in the url as the parameter present and using the id we are using the find_one() method and passing the id as an argument and then we are returning the user as the json response back to the client using the dumps() method.

 

Now if you make the get request to the route /users/<id> inside the postman and passing the id of the user that you want the information you will get the below json response

 

 

 

 

 

Deleting Specific User Information Using ID From MongoDB Database

 

 

Now we will be writing the simple DELETE route where if you go we will be deleting a specific user using it’s id which is present inside the mongodb database as shown below

 

 

Python
1
2
3
4
5
6
@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

 

 

As you can see we have written the route which is /delete/<id>and for this we have defined the method which is called delete_user(id) and inside this method we are deleting the user using it’s id passed in the method as an argument. We are getting the id in the request as an argument and then we are using the delete_one() method and passing the id as an argument inside this method to delete the user. And after deletion we are returning the simple json response back to the client that the user is deleted. And also returning the status code of success which is 200.

 

Now if you make the delete request to the route /delete/<id> inside the postman and passing the id of the user that you want the information you will get the below json response

 

 

 

 

Updating Specific User Information Using ID From MongoDB Database

 

 

Now we will be writing the simple PUT route where if you go we will be updating a specific user using it’s id which is present inside the mongodb database as shown below

 

 

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@app.route('/update/<id>',methods=['PUT'])
def update_user(id):
    _id = id
    _json = request.json
    _name = _json['name']
    _email = _json['email']
    _password = _json['password']
 
    if _name and _email and _password and _id and request.method == "PUT":
 
        _hashed_password = generate_password_hash(_password)
 
        mongo.db.user.update_one({'_id':ObjectId(_id['$oid']) if '$oid' in _id else ObjectId(_id)},{'$set':{'name':_name,'email':_email,'password:':_hashed_password}})
 
        resp = jsonify("User updated successfully")
 
        resp.status_code = 200
 
        return resp
 
    else:
 
        return not_found()

 

 

As you can see we have written the route which is /update/<id>and for this we have defined the method which is called update_user(id) and inside this method we are updating the user using it’s id passed in the method as an argument. We are getting the id in the request as an argument and then we are using the update_one() method and passing the id as an argument inside this method to update the user. And after updation we are returning the simple json response back to the client that the user is updated. And also returning the status code of success which is 200.

 

Now if you make the update request to the route /update/<id> inside the postman and passing the id of the user that you want the information you will get the below json response

 

 

 

Wrapping the blog post this is the full source code of the app.py file as shown below

 

 

app.py

 

 

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
from flask import Flask
from flask_pymongo import PyMongo
from bson.json_util import dumps
from bson.objectid import ObjectId
from flask import jsonify,request
from werkzeug.security import generate_password_hash,check_password_hash
 
app = Flask(__name__)
app.secret_key = "secretkey"
 
app.config['MONGO_URI'] = "mongodb://localhost:27017/crud"
 
mongo = PyMongo(app)
 
@app.route('/add',methods=['POST'])
def add_user():
    _json = request.json
    _name = _json['name']
    _email = _json['email']
    _password = _json['password']
 
    if _name and _email and _password and request.method == "POST":
 
        _hashed_password = generate_password_hash(_password)
 
        id = mongo.db.user.insert({'name':_name,'email':_email,'password':_hashed_password})
 
        resp = jsonify("User Added successfully")
 
        resp.status_code = 200
 
        return resp
 
    else:
 
        return not_found()
 
@app.route('/update/<id>',methods=['PUT'])
def update_user(id):
    _id = id
    _json = request.json
    _name = _json['name']
    _email = _json['email']
    _password = _json['password']
 
    if _name and _email and _password and _id and request.method == "PUT":
 
        _hashed_password = generate_password_hash(_password)
 
        mongo.db.user.update_one({'_id':ObjectId(_id['$oid']) if '$oid' in _id else ObjectId(_id)},{'$set':{'name':_name,'email':_email,'password:':_hashed_password}})
 
        resp = jsonify("User updated successfully")
 
        resp.status_code = 200
 
        return resp
 
    else:
 
        return not_found()
 
@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
 
@app.route('/users')
def users():
    users = mongo.db.user.find()
    resp = dumps(users)
    return resp
 
@app.route('/users/<id>')
def user(id):
    user = mongo.db.user.find_one({'_id':ObjectId(id)})
    resp = dumps(user)
    return resp
 
@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
 
if __name__ == "__main__":
    app.run(debug=True)

 

Recent Posts

  • Android Java Project to Crop,Scale & Rotate Images Selected From Gallery and Save it inside SD Card
  • Android Kotlin Project to Load Image From URL into ImageView Widget
  • Android Java Project to Make HTTP Call to JSONPlaceholder API and Display Data in RecyclerView Using GSON & Volley Library
  • Android Java Project to Download Youtube Video Thumbnail From URL & Save it inside SD Card
  • Android Java Project to Embed Google Maps & Add Markers Using Maps SDK
  • Angular
  • Bunjs
  • C#
  • Deno
  • django
  • Electronjs
  • java
  • javascript
  • Koajs
  • kotlin
  • Laravel
  • meteorjs
  • Nestjs
  • Nextjs
  • Nodejs
  • PHP
  • Python
  • React
  • ReactNative
  • Svelte
  • Tutorials
  • Vuejs




©2023 WebNinjaDeveloper.com | Design: Newspaperly WordPress Theme