Tezeract logo

Learn How To Integrate Flask API With Machine Learning Model and testing it on Postman

Creating APIs with flask

Content

Introduction

Flask is one of the simplest but most widely used Python microservices web frameworks for building APIs. It is designed in a way that every beginner can take a quick start from it for building an API as it’s quite simple and easy and then can be scaled up for more complex architectures and applications.

I would highly recommend giving a few minutes to read Flask API documentation which will help you understand it in a better way and clear your base level queries regarding the different terminologies, such as what is meant by the micro web framework.

In this article, we will discuss how we will be creating APIs with Flask that can be integrated with Machine learning or deep learning models.

When the first time in my AI Journey, I tried to build a Flask API, integrate DL Model with it and test it using postman by sending the Image for prediction, I faced too many difficulties and wasn’t able to find a quick and easy solutions. 

If you already started practicing AI and especially computer vision, you must implement a very first step practice project for each beginner and that is Cat-vs-Dog Classification. I already have the trained classification model and have its .h5 file, with the help of which I would try to answer all of the following queries and many more:

  1. How to write a Flask API?
  2. How to Integrate ML model with Flask?
  3. How to write POST requests in Flask-Python?
  4. What is Postman?
  5. How to send an Image from Postman?
  6. How to get/read Image on Flask from Postman?

To get the answers to all of the above queries and some more, let’s get your hands dirty with the code!

Creating APIs with flask

The following piece of code will give the answer to the queries mentioned above at point number 1, 3, and 6.

from flask import Flask, render_template, Response,jsonify,request
import cv2
import numpy as np
import os
import sys

app=Flask(__name__)


@app.route('/predict_image',methods=['POST'])
def Predict_Image():
  
    image = request.files['image'].read()
    npimg = np.fromstring(image, np.uint8)
    img = cv2.imdecode(npimg,cv2.IMREAD_COLOR)

    cv2.imshow('image',img)
    cv2.waitKey(0) 
    cv2.destroyAllWindows() 

    dic = {"status":200,"msg":"ok"}

    return jsonify(dic)


if __name__=='__main__':
    app.run(host='0.0.0.0', port=8000, threaded=True) 

Code Overview

Line by line explanation of the above code

Line 01 ~ Line 05: Importing all the necessary libraries

Line 07: Importing the Flask module which is necessary.

Line 10: Defining the route and naming the API (‘/predict_image’), Also defining the method of API, in this case, its ‘POST’, which means we’re taking some data(image) and sending some data (JSON response) as well.

Line 11: Naming the function for API.

Line 13 ~ Line 15: It is one of the most important pieces of code, in which we are reading the image (sent from postman/frontend app), and converting it to an array (our original image).

Line 17 ~ Line 19: Here we’re just popping up the image to confirm, that we’re getting the same image with the same format as sent. (These lines must be commented in a deployment mode).

Line 21 ~ Line 23: Creating a dictionary and converting it to JSON then sending it as a response of API.

Line 26 ~ Line 27: Running and executing the Flask app here. (Defining the host and port for the app to run on it).

Once you’re done with the code, it’s time to run your app. For running the app, open the terminal where you have your code file(.py), as my name is ‘app.py’. Install all the necessary libraries (recommend is to create the conda environment for it), and now type the command ‘ python app.py ’. Once the command runs successfully, you will see the app running

terminal of code file

As of now, the app is working perfectly, and running on the defined host & port, you can put the running URL with your API name ( in this case, it ‘/predict_image ’ ) on the POSTMAN to test your API.

Testing Flask APIs on Postman

Postman is a tool that was built to simplify API testing but now its becomes a platform for developers to build, use and test the APIs. With postman, you can create better and faster APIs because of streamlined collaborations and the simplified steps for the API lifecycle.

post man image

Step 1

If you don’t have the POSTMAN installed on your local system, visit the attached link and download it.

testing flask api on postman step 1

Step 2

Now, as we’re working on the image data and need to send the image via POSTMAN, we need to select the Body type as ‘form-data’ and put the header of ‘Content-Type’ as well as mentioned in the attached snapshot.

testing flask api on postman step 2

Step 3

Put the key-value pair in the request body, in our example, we are sending the image so we need to select the key type as File.

testing flask api on postman step 3

Step 4

Select the file (image) you want to send to your Flask Backend App to process it.

Learn How To Integrate Flask API With Machine Learning Model and testing it on Postman Tezeract
testing flask api on postman step 4

Step 5

Press the Send button and now you can see the response dictionary you have written in the code will be displayed in the POSTMAN. As currently there is a command written in the code to display the image (cv2.imshow), you will also see the image on your screen. This line will be commented on in the next phase. And now you have got the answer to point (4) & (5).

testing flask api on postman step 5

Integrating Flask API with ML Model

In the snap attached below, I have added a few lines of code where I am integrating our ML model and which will give you the answer to the query “How to Integrate ML model with Flask”.

from flask import Flask, render_template, Response,jsonify,request
import cv2
import numpy as np
import os
import sys
from tensorflow import keras
import numpy as np

app=Flask(__name__)
IMG_SIZE=180

@app.route('/predict_image',methods=['POST'])
def Predict_Image():
  
    image = request.files['image'].read()
    npimg = np.fromstring(image, np.uint8)
    img = cv2.imdecode(npimg,cv2.IMREAD_COLOR) #This img variable will have your image

    resized_img = cv2.resize(img,(IMG_SIZE,IMG_SIZE)) #resizing the image
    resized_img = resized_img.reshape(-1,IMG_SIZE,IMG_SIZE,3) #reshaping the image

    print(type(resized_img));print(resized_img);print(resized_img.shape)
    
    model = keras.models.load_model('model2.h5')

    prediction = model.predict(resized_img)[0][0]

    print("Prediction: ",prediction)

    if prediction<=0.5:
        prediction_class = 'Cat'
    elif prediction>0.5:
        prediction_class = 'Dog'

    print("Prediction Label: ",prediction_class)

    # cv2.imshow('image',img)
    # cv2.waitKey(0) 
    # cv2.destroyAllWindows() 

    dic = {"status":200,"msg":"ok","Predicted_Label":prediction_class}

    return jsonify(dic)


if __name__=='__main__':
    app.run(host='0.0.0.0', port=8000, threaded=True,debug=False) 

Line 10: Defining the image size which will be used for image pre-processing according to dimensions we must have defined while building training/testing data for model building. 

Line 19 ~ Line 22: Resizing and reshaping the image and then putting some print statement to verify. These actions are performed according to the size and shape of the image input passed to the ML model while building and training it.

Line 24 ~ Line 35: In this piece of code, the model is being loaded and the image which was the input of the API had been passed to the model for the prediction. Once the model predicted the class, the data is processed and the numeric value is converted into a class label that a normal human can understand. As mentioned in the article at the very start, the model used in this example is a classification model which predicts between cat and dog. I had passed a dog image for the test and it predicts it correctly!

P.S: Make sure you have passed the correct model path while loading the model.

integrating flask api with ml model

Conclusion

In this article, I have tried to clarify the basic queries precisely and solve the difficulties which every AI engineer faces at the early stages when trying to integrate the ML model with the API to interact with it.

Apart from the integration, I have provided some other helpful basics tricks such as ‘How to send an image via POSTMAN and read it in Flask’, in which beginners struggle a lot to find direct solutions.

Hope it helps!

In the next part, I will be trying to solve the problem of ‘How to deploy AI model on EC2 instance’. So, stay connected.

Abdul Hannan

Abdul Hannan

Co-Founder & CEO

Share

Suggested Articles