How to Build A Machine Learning API using Flask | Towards Data Science

Machine Learning (ML) is a great way to do tasks that cannot be explicitly coded, for example, image classification. But when the model is already built, it will be useless when we don’t deploy it into an application.
Deployment is an essential step in the machine learning workflow. It is a step where we want to apply our ML model into an application. Afterwards, we can use the model in real life.
But how can we create the model as an application? We can build an Application Programming Interface (API). With that, we can access the model from everywhere, whether it is on the mobile application or even on the web application. In Python, there’s a library that can help us to build an API. It’s called Flask.
This article will show you how to build a REST API for our machine learning model using Flask. Without further ado, let’s get started!
Before we get into the implementation, let me explain REST API. REST API stands for Representational State Transfer Application Programming Interface.
The mechanism of REST API looks like this. Let’s say you want to search cat photos on Google. The first step is to send a request to Google by giving them a query like ‘cat photos’. Then, the server will send you a response to your computer, which is the compilation of cat photos.
That’s all about the REST API! It’s the way to communicate between you as the client by requesting something to the server, and then the server will send you the response. Here is an illustration of how the REST API works.
Now you understand the basic concept of REST API. Let’s get into the implementation using Flask. There are several processes that we will cover:
Importing librariesLoad the machine learning modelBuild functions to preprocess and to predict the imageInitialize the flask objectSet the route and the function that returns something to the user’s browserRun and test the API
Importing libraries
Load the machine learning model
Build functions to preprocess and to predict the image
Initialize the flask object
Set the route and the function that returns something to the user’s browser
Run and test the API
The first step is to load the libraries. The libraries that we will import are TensorFlow, Flask, Pillow, and other supporting libraries. If those libraries are not installed, you can install them by using the pip command.
Here is the code to import libraries:
After you load the libraries, the next step is to load the machine learning model. In this case, I will use my image classifier model, which I’ve already pre-trained before using TensorFlow. The model will predict whether the image contains food or not.
Here is the code to load the model:
Side Note: If you train the model on GPU and want to run them on CPU, it’s okay. TensorFlow supports this, and you don’t need to tweak the model at all.
After we load the model, the next step is to create functions to process the image. Because we will get the image from the request by a client, we will use io.BytesIO function to load the image into our Python code. After that, we only need to call the .predict function from our model to predict the result.
Here is the code to preprocess and to predict the image:
Right after you build the functions, now let’s initialize the Flask object. Also, we set the name on the Flask object parameter. This step is to make sure that the python script is read for running a web application.
Here is the command for doing that:
Now let’s set the route and the function that we want to run. A route is a way to access certain functionality on the web. When we access the route, it will run a function and returns the message to the user.
Each route has different ways to interact based on their HyperText Transfer Protocol (HTTP) method. There are several HTTP methods that we can use.
The first one is the GET method, where we only access the route without sending any data. The second one is the POST method. In this method, we can access the route and also send the data to it.
There are also routes like the PUT, PATCH, and DELETE method. But we will not talk about it further. We will use only the GET and POST method for this time.
Now let’s create two routes. The first one is the ‘/’ route path. The route will return the welcome message of the API. Therefore, we will give this route a GET method.
The second one is the ‘/predict’ route path. This route will return the prediction result from an image. We will use the POST method for sending the image into the route. Also, we need to set the key, so the app can know where the image is. We will use the ‘file’ key as the identifier of our image file.
Here is the code for setting up routes and their functions:
After we build functions and their routes, now let’s run the API. But there is a final step before we can run the API. We need to add the .route method into our code like this:
Now go to your terminal, and run one of this command (make sure that you are on the same path with the API file):
flask runORpython app.py
If you run the command, it will return a result like this:
As you can see from above, it shows several logs from TensorFlow. Don’t worry about it. It is just a warning that we can ignore. As long as you can see the ‘Running on’ message, it means that your API is running now.
Now let’s access the API by address http://127.0.0.1:5000/, where 127.0.0.1 is your local address, and 5000 is the port number to access the API. If it is a success, it will show like this on the web:
Great! Our API starts perfectly. Let’s try the API if it can predict an image of whether it contains food or not. We can use an application called Postman to test the API that we have created before. You can download it here.
Here is the preview of the result,
As you can see from above, the API can catch the image and return the prediction result. It means that our API is already working. Well done!
Now you have built the machine learning API using Flask. I hope this article helps you to understand the REST API concept. And also, it can guide you to develop your own API in your project.
If you are interested in this article, you can follow my Medium for more articles like this. Also, if you have any questions or want to have a conversation with me, you can connect with me on LinkedIn.
In case you are still stuck for coding the API, here is the complete code of the API,
Thank you for reading my article!