DEV Community

Cover image for How to Build Simple RESTful APIs with Python and Flask
atultyagi612
atultyagi612

Posted on

How to Build Simple RESTful APIs with Python and Flask

What is REST API?

A REST API (also known as RESTful API) is an application programming interface (API or web API) that conforms to the constraints of REST architectural style and allows for interaction with RESTful web services. REST stands for representational state transfer and was created by computer scientist Roy Fielding.more.

What is Flask?

Flask is a web framework. This means flask provides you with tools, libraries, and technologies that allow you to build a web application. This web application can be some web pages, a blog, a wiki, or go as big as a web-based calendar application or a commercial website. Flask is part of the categories of micro-framework. Micro-framework is normally a framework with little to no dependencies on external libraries.

Why use Flask for rest API?

Flask is able to achieve generally faster performance than Django, generally due to the fact that Flask is much more minimal in design. Flask also has NoSQL support. Flask also has Flask-RESTful an extension for Flask that provides additional support for building REST APIs.Flask-Restful is a lightweight abstraction that works with the existing ORM/libraries. Flask-RESTful encourages best practices with minimal setup. And also take less time to master.

Before you get started

Make sure you have Python installed on your system.
Postman Installed on your system. Postman helps to test your Rest API.

Flask Installation

Write the below command in your cmd for the Installation of Flask using pip.reference

pip install Flask
Enter fullscreen mode Exit fullscreen mode

Install Flask-RESTful

Flask-RESTful is an extension for Flask that adds support for quickly building REST APIs more. the command for the installation

pip install flask-restful
Enter fullscreen mode Exit fullscreen mode

Pandas Installation

We use pandas to CRUD data in CSV file.Write the below command in your cmd for the Installation of Pandas using pip.reference

pip install pandas
Enter fullscreen mode Exit fullscreen mode

Lets Start ✨

First, we have to Import the dependencies.

from flask import Flask, jsonify 
from flask_restful import Resource, Api , reqparse
import pandas as pd 
Enter fullscreen mode Exit fullscreen mode

Now, let’s understand the working of the code line-by-line:

  • from flask import Flask, jsonify -> Import Flask class
    jsonify -> jsonify is a function in Flask's flask. json module. jsonify serializes data to JavaScript Object Notation (JSON) format, wraps it in a Response object with the application/json mimetype.

  • from flask_restful import Resource, Api , reqparse -> import Flask-RESTful. it is an extension for Flask .
    Resource->It is a base class that can define the routing for one or more HTTP methods for a given URL.
    reqparse->Enables adding and parsing of multiple arguments in the context of a single request. Help

  • import pandas as pd -> Importing Pandas library as a name pd.

Now it's time for the main entry point for the application. Create an instance of the class.

app=Flask(__name__)
api=Api(app)
Enter fullscreen mode Exit fullscreen mode

now add reqparse to our code. it Enables adding and parsing of multiple arguments in the context of a single request.
there is only 4 field(in CSV) in csv file so only add 4 arguments to be parse after initializing reqparse and also add help which return a description id if the argument is not valid.

data_arg=reqparse.RequestParser()
data_arg.add_argument("ID" , type=int ,help="Enter ID")
data_arg.add_argument("Name" , type=str ,help="Enter Name")
data_arg.add_argument("Language" , type=str ,help="Enter Language")
data_arg.add_argument("Age" , type=int ,help="Enter Age")
Enter fullscreen mode Exit fullscreen mode
Create classes

Now create a class read_Delete which read and delete data from a CSV file and return Response. In this class we define function get This means that any GET Request on the url endpoint hit this function and delete function will hit by Delete request.

class read_Delete(Resource):
    def __init__(self):
        # read csv file
        self.data = pd.read_csv('data.csv')
    # GET request on the url will hit this function
    def get(self,ID):
        # find data from csv based on user input
        data_fount=self.data.loc[self.data['ID'] == ID].to_json(orient="records")
        # return data found in csv
        return jsonify({'message': data_fount})
    # Delete request on the url will hit this function
    def delete(self,ID):
        if ((self.data['ID'] == ID).any()):
            # Id it present delete data from csv
            self.data = self.data.drop(self.data["ID"].loc[self.data["ID"] == ID].index)
            self.data.to_csv("data.csv", index=False)
            return jsonify({"message": 'Deleted successfully'})
        else:
            return jsonify({"message": 'Not Present'})
Enter fullscreen mode Exit fullscreen mode

Now create a class Create_Update which read data from a CSV file and perform update and create on data. In this class we define functions post , put means any POST PUT Request on the URL endpoint will be hitting their respective function.

class Create_Update(Resource):
    def __init__(self):
        # read data from csv
        self.data = pd.read_csv('data.csv')

    # POST request on the url will hit this function
    def post(self):
        # data parser to parse data from url
        args = data_arg.parse_args()
        # if ID is already present
        if((self.data['ID']==args.ID).any()):
            return jsonify({"message": 'ID already exist'})
        else:
            # Save data to csv
            self.data= self.data.append(args, ignore_index=True)
            self.data.to_csv("data.csv", index=False)
            return jsonify({"message": 'Done'})

    # PUT request on the url will hit this function
    def put(self):
        args = data_arg.parse_args()
        if ((self.data['ID'] == args.ID).any()):
            # if ID already present Update it
            self.data=self.data.drop(self.data["ID"].loc[self.data["ID"] == args.ID].index)
            self.data = self.data.append(args, ignore_index=True)
            self.data.to_csv("data.csv", index=False)
            return jsonify({"message": 'Updated successfully'})
        else:
            # If ID not present Save that data to csv
            self.data = self.data.append(args, ignore_index=True)
            self.data.to_csv("data.csv", index=False)
            return jsonify({"message": 'successfully Created'})

Enter fullscreen mode Exit fullscreen mode

adding the defined resources along with their corresponding URLs

api.add_resource(read_Delete, '/<int:ID>')
api.add_resource(Create_Update,'/')
Enter fullscreen mode Exit fullscreen mode

main function for calling the app

if __name__ == '__main__':
    app.run(debug=True)
Enter fullscreen mode Exit fullscreen mode

πŸŽ‰πŸŽ‰ Our API is ready
Now, Visit the URL http://127.0.0.1:5000/ at your browser, you API is hosted at that URL.

Now its testing time

Let's run our code and open the Postman to be able to test the endpoints.

GET request

for this we have to pass the link with id at the end:
Alt Text
It works fine.

POST request

Let's try to input the data pass the link with ID and parameters.
Alt Text

PUT request

Let's try to update the data, set the PUT method to pass the link with input data for the update.
Alt Text

DELETE request

The last thing to do is the DELETE method, select it and pass the link with ID at the end.
Alt Text
Everything works fine cheer up.

Conclusion

In this article, we create a simple restful API with python. we use the Flask framework and Flask_RESTful library an extension for flask which makes it fast and easy. Our API allows us to CRUD data. I hope you will find this tutorial helpful and useful. Now it's your time to try and build.

Top comments (0)