How to Build Simple RESTful APIs with Python and Flask
Tags: beginners, python
Published: 2021-03-20 16:50:40

## 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.](https://www.redhat.com/en/topics/api/what-is-a-rest-api)
## 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](https://www.python.org/) installed on your system.
[Postman](https://www.postman.com/) 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](https://flask.palletsprojects.com/en/1.1.x/)
```python
pip install Flask
```
## Install Flask-RESTful
Flask-RESTful is an extension for Flask that adds support for quickly building REST APIs [more](https://flask-restful.readthedocs.io/en/latest/). the command for the installation
```python
pip install flask-restful
```
##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](https://pandas.pydata.org/pandas-docs/stable/getting_started/install.html)
```python
pip install pandas
```
##Lets Start ✨
First, we have to Import the dependencies.
```python
from flask import Flask, jsonify 
from flask_restful import Resource, Api , reqparse
import pandas as pd 
```
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](https://flask-restful.readthedocs.io/en/latest/api.html#:~:text=resource%20(%20Type%5BResource%5D%20),the%20resource%20method%20as%20args.)

* `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.
```python
app=Flask(__name__)
api=Api(app)
```
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.
```python
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")
```
#####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.
```python
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'})
```

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.
```python
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'})

```
adding the defined resources along with their corresponding URLs 
```python
api.add_resource(read_Delete, '/<int:ID>')
api.add_resource(Create_Update,'/')
```
main function for calling the app
```python
if __name__ == '__main__':
    app.run(debug=True)
```
🎉🎉 Our API is ready
Now, Visit the URL [http://127.0.0.1:5000/ ](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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y965rknu0qi0n9f19dac.jpg)
It works fine.
#### POST request 
Let's try to input the data pass the link with ID and parameters.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vi4e4buc9apw87gqy6zl.jpg)
####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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6nojr17wtmtffmuu0nec.jpg)
####DELETE request
The last thing to do is the DELETE method, select it and pass the link with ID at the end.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x9fle6laxisd17m03usr.jpg)
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.