Flask RestPlus API CRUD Operations

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

Flsk Rest-Plus API is more advance than Flask RestFul API which we have explored in our last post. The best feature of it is Automated Swagger. Yes, its true you don’t have to do anything to integrate swagger. it is already there. You only have to define the APIs and the swagger document and GUI will be created automatically for you on your home URL by default(You can change it if you want.

Flask-RestPlus Swagger GUI

Steps

  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 & Get User
  6. Run the server and Test the API With Postman
  7. Update and Delete User (Handle multiple methods with the same class)

SO without wasting any time lets jump in.

Import required Libraries

As discussed we are going to use flask, flask-rstplus, 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 
from flask_restplus import Api, fields , Resource
from werkzeug.utils import cached_property

Initialize app and libraries

We are going to user flask so we will initialize the 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
app.config['SQLALCHEMY_DATABASE_URI']='sqlite:///user_details.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=True 
#Initialize Database
db = SQLAlchemy(app)
#initialize Marshmallow
ma = Marshmallow(app)
#initialize restplus api
api = Api()
api.init_app(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.

#Table
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 & Get User

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.

@api.route('/user')
class UserDetails(Resource):
    def get(self):
        #get users from the database
        users = User.query.all()
        #return the list of users
        return jsonify(users_schema.dump(users)) 

    @api.expect(model)
    def post(self):
        #Instantiate new user
        new_user = User(name=request.json['name'], email=request.json['email'], password=request.json['password'])
        #add new user
        db.session.add(new_user)
        #commit the change to reflect in database
        db.session.commit()
        #return the response
        return user_schema.jsonify(new_user)

There is no change as compared to Flask-Restful. The only change is we are defining route above the class.

As you can see in post request, 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. And in get request we are returning all the users.

Run the server and Test the API With Postman

Now write the final code to run server.

# Run Server
if __name__ == '__main__':
    app.run(debug=True)

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.

venv\script\activate

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

python app.py

Now open your server URL(localhost:5000) in any browser, you will see the swagger GUI there and you can test all your APIs from there.

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

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

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.

@api.route('/user/<int:id>')
class UserPutDelete(Resource):
    @api.expect(model)
    def put(self,id):
        #get User
        user = User.query.get(id)
        #update user data
        user.name = request.json['name']
        user.email = request.json['email']
        user.password = request.json['password']
        #commit to change in database
        db.session.commit()
        return {'message':'data updated'}

    def delete(self,id):
        #get user
        user = User.query.get(id)
        #delete the user
        db.session.delete(user)
        #commit to reflect in database
        db.session.commit()
        return {'message':'data deleted successfully'}

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

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

This is a simple CRUD operation with Flask RestPlus, in future posts, 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:

Leave a Comment

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

Copy link
Powered by Social Snap