Simple Machine Learning Flask API (using Flasgger)

Shrinand Kadekodi
4 min readJan 23, 2022

For users to interact with any Machine Learning application, some kind of a GUI or a web application is necessary. A web application is much more practical as anyone in the world can use it. Python has a library called Flask which helps in this. In this post we will see how to use Flask and flasgger to create a small API for our Machine Learning application.

Installing Libraries:

To create the API we need to install Flask and flasgger libraries. The following commands in Anaconda prompt will install them:
conda install -c anaconda flask
conda install -c conda-forge flasgger
In addition to this, I have saved a Machine Learning model in a pickle file. It is a simple model to predict house price depending on the different input given. We wont look into the model as the focus of this post is to build the Flask API.

Implementation:

The below image shows the steps of how to develop a Flask API

Flask requires route and for each route a function. A route is a way to access certain functionality on the web and run a function. Each route has different ways to interact based on their HyperText Transfer Protocol (HTTP) method. The default path is ‘/’. The below code shows how the routes are set:

# Import Libraries
from flask import Flask,request
import numpy as np
import pandas as pd
import pickle
import flasgger
from flasgger import Swagger
from flasgger.utils import swag_from
# Initialize Flask app and embed in Swagger
app = Flask(__name__)
swagger = Swagger(app)
# Load the file and read the model
pickle_in = open('classifier.pkl','rb')
classifier = pickle.load(pickle_in)
# default route
@app.route('/')
def welcome():
return 'Welcome All'

Flasgger implementation:

Flasgger Documentation states the following — “ Flasgger is a Flask extension to extract OpenAPI-Specification from all Flask views registered in your API. Flasgger also comes with SwaggerUI embedded so you can access http://localhost:5000/apidocs and visualize and interact with your API resources”. Thus it makes easy the process of creating a UI layout as you will see shortly.
Flasgger requires the input in a specific format. The most common is to use docstring implementation where you can specify the parameters. But a more elegant implementation would be to use yaml file which has the parameters and its definition. I have utilized the below yaml code for defining the parameters:

House prediction
---
tags:
- House Prediction API
parameters:
- name: area
in: query
type: number
required: true
- name: bedroom
in: query
type: number
required: true
- name: bath
in: query
type: number
required: true
- name: Locality1
in: query
type: number
required: true
- name: Locality2
in: query
type: number
required: true
- name: Locality3
in: query
type: number
required: true
- name: Locality4
in: query
type: number
required: true

responses:
200:
description: House Information Given Successfully

The above yaml code is pretty much simple. For each parameter I have described the name, its type and whether its optional or not. We need to specify the yaml file where the route to enter user data is defined. It is more clear in the code below:

# route to take data from user and predict the house price
@app.route('/predict',methods=['Get'])
@swag_from('getdata.yml')
def predictHousingPrice():

area = request.args.get("area")
bedroom = request.args.get("bedroom")
bath = request.args.get("bath")
Locality1 = request.args.get("Locality1")
Locality2 = request.args.get("Locality2")
Locality3 = request.args.get("Locality3")
Locality4 = request.args.get("Locality4")
prediction = classifier.predict([[area,bedroom,bath,Locality1,Locality2,Locality3,Locality4]])
print(prediction)
return "The estimated price is " + str(prediction) + "lakhs."

Result:

On running the script you are able to see the UI on http://127.0.0.1:5000/apidocs path. The image shows that on entering the values in the fields, the predicted price is shown.

The full code for reference

# Import Libraries
from flask import Flask,request
import numpy as np
import pandas as pd
import pickle
import flasgger
from flasgger import Swagger
from flasgger.utils import swag_from
# Initialize Flask app and embed in Swagger
app = Flask(__name__)
swagger = Swagger(app)
# Load the file and read the model
pickle_in = open('classifier.pkl','rb')
classifier = pickle.load(pickle_in)
# default route
@app.route('/')
def welcome():
return 'Welcome All'
# route to take data from user and predict the house price
@app.route('/predict',methods=['Get'])
@swag_from('getdata.yml')
def predictHousingPrice():

area = request.args.get("area")
bedroom = request.args.get("bedroom")
bath = request.args.get("bath")
Locality1 = request.args.get("Locality1")
Locality2 = request.args.get("Locality2")
Locality3 = request.args.get("Locality3")
Locality4 = request.args.get("Locality4")
prediction = classifier.predict([[area,bedroom,bath,Locality1,Locality2,Locality3,Locality4]])
print(prediction)
return "The estimated price is " + str(prediction) + "lakhs."
if __name__=='__main__':
app.run()

I hope that this blog was helpful in getting started with Flask API for Machine Learning. Let me know your thoughts.

References:
- A lot of googling amongst which the major sources were stackoverflow.com, dev.to, youtube.com, https://github.com/flasgger/flasgger and medium.com

Originally published at http://evrythngunder3d.wordpress.com on January 23, 2022.

--

--