Flask Rest Api CRUD operations

Hi, guys in this post we are going to code a simple CRUD operation (User Management) with flask. This is a continuing post of our Flask REST API Series. In the last video, we have successfully installed all the required dependencies and ran our first program, if you have not done that please follow that first Click Here.


  1. Import required Libraries
  2. Initialize app and libraries
  3. Define a User Model
  4. Define & initialize User Schema using Marshmallow
  5. Define a Route for UserCreation
  6. Run the server and Test the API With Postman
  7. Define a Route for Get Users
  8. Update and Delete User (Handle multiple methods with the same class)

SO without wasting any time lets jump in.

Import required Libraries

As discussed in previous video we are going to use flask, sqlalchemy and marshmallow so import all these packages

#Import required packages
from flask import Flask, request, jsonify 
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow

Initialize app and libraries

We are going to user flask so we will initialize flask application, Then we will initialize the SQLAlchemy database and finally we will initialize the marshmallow like below.

# Initialize app
app = Flask(__name__)
#Database for SQLAlchemy
#Initialize Database
db = SQLAlchemy(app)
#initialize Marshmallow
ma = Marshmallow(app)

Define a User Model

For our User management, we need a database. SQLAlchemy is such a powerful library that will help us and make our work so ease that we can handle the database like classes. so let’s create our model like below.

class User(db.Model):
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    name = db.Column(db.String)
    email = db.Column(db.String)
    password = db.Column(db.String)
    def __init__(self, name, email, password):
        self.name = name
        self.email = email
        self.password = password

As you can clearly understand we are creating a User class by inheriting it from the base class db.model and then like class variables we are declaring our columns. we are using db.Column to instantiating the field as a column. db.integer shows that the column is an integer column.

Define & initialize User Schema using Marshmallow

For marshaling our output we are using marshmallow. if you are confuse why we should use this then you can think like that suppose your database have many fields but you want to show some of them in that case we use marshaling to format our data. so let’s do that.

#Marshmallow Schema
class UserSchema(ma.Schema):
    class Meta:
        fields = ('id','name','email','password')

# Initialize schema
user_schema = UserSchema()
users_schema = UserSchema(many=True)

As you can see we have defined a class as UserSchema and that is our schema class that responsible for marshaling. below that, we have instantiated two objects. user_schema is responsible for handling one user data and users_schema is responsible for many.

Define a Route for UserCreation

Now this is the time to handle a route. So we are going to create a route that will handle POST request and then we will get data from request. Instantiate a user with the data and save it to database like below.

# Create a user
@app.route('/user', methods=['POST'])
def add_user():
    #get data from request
    name = request.json['name']
    email = request.json['email']
    password = request.json['password']
    #Instantiate new user
    new_user = User(name, email, password)
    #add new user
    #commit the change to reflect in database
    #return the response
    return user_schema.jsonify(new_user)    #or you can use: return jsonify(user_schema.dump(new_user))

As you can see we are creating a user and saving the database. As a return we are sending all the user data ad response. Here we are using jsonify to jsonify the user object then formatted the data with user_schema.

Run the server and Test the API With Postman

Now write the final code to run server.

# Run Server
if __name__ == '__main__':

Now save the file and open terminal with activating your virtual environment. (Please skip if you have already activated the virtual environment. For our case, we have a virtual environment named venv. replace venv with your own virtual environment name.


Now run the python file. In our case we have named it as app.py (Replace filename as yours)

python app.py

Finally, open postman and test the API by sending a post request to your server URL (localhost:5000 in our case). As a response, you will get the user details with the new userid generated in the database. CONGRATULATIONS 🥳.

Congratulations banner with colorful watercolor brush strokes. Vector paper illustration.

Define a Route for Get Users

Now lets go one more step ahead. Lets create another route that will give the user details to the request. so lets declare another route with get request.

#get all users
@app.route('/user', methods=['GET'])
def get_users():
    users = User.query.all()
    result = users_schema.dump(users)
    return jsonify(result)                  #or you can write single line: jsonify(users_schema.dump(users)) 

NOTE: Put these code after the post method and before main function.

As you can see from the code we are queering for all the users. User.query.all() this is how we query in SQLAlchemy. this query mean “select * from user”. Then we are formatting all the users with our schema and returning the result to the request.

Update and Delete User (Handle multiple methods with the same class)

Last two methods of CRUD is Update and Delete so lets do that. But in this time we will not create two different route like above we can also handle multiple request of same route like below.

#Put and Delete a specific user. 
#(you can do this like you done for post and get request but here i am doing to show you how to handle multiple methods)
@app.route('/user/<int:id>', methods=['PUT', 'DELETE'])
def put_delete(id):
    if request.method == 'PUT':
        user = User.query.get(id)
        user.name = request.json['name']
        user.email = request.json['email']
        user.password = request.json['password']
        return {'message':'data updated'}

    if request.method=='DELETE':
        user = User.query.get(id)
        return {'message':'data deleted successfully'}

Finally Save the file. Run and test all the APIs from postman.

Rod Randomberger from Cyberspace — THANK YOU ❤❤❤ Dear Tumblrs ...

This is a simple CRUD operation, in future posts, we will cover Flask-RESTful and RestPlus and finally, we will deploy our API in serverless. Hope you have liked learning this, if so please show your support in the comment section below. Also, subscribe to YouTube for getting videos for these concepts.

If you get any doubts, feel free to contact me.

Connect with us on social media to get updates for future posts. YouTubeInstagramFacebook.

Posts You May Like:

Article Name
Flask Rest Api CRUD Operations
Hi, guys in this post we are going to code a simple CRUD operation (User Management) with flask. This is a continuing post of our Flask REST API Series

Leave a Comment

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

Copy link
Powered by Social Snap