FastAPI vs Flask | Is FastAPI the correct replacement for flasks?

Share on facebook
Share on twitter
Share on linkedin
Share on telegram
Share on whatsapp

Contents

Once you are done with model building and proper hyperparameter tuning, the next step in data science projects is show final results To the general public. It is essential to do it this way because not everyone is interested in seeing the code and is more interested in the final result. It also helps data science wannabes to build a project from start to finish which gives them an advantage over others and gives them a taste for other technologies.

Deploying machine learning models can take different routes depending on the platform on which you want to deliver the model. the web interface is the most common way to post a model, but it is not limited to Android and IOS apps or an IOT device like Raspberry Pi. If you investigate this in detail, so a frame heading the search query is the flask frame which is a minimalist application to quickly configure web servers but it has some issues which now resolve to a recently launched frame call FastAPI which is gaining a lot of popularity these days.

In this article, we will see how the FastAPI framework has an advantage over Flask with some example code to understand things in a better way. Before that, if you are interested in android application implementation then you can read my article Implementation of ML in the Android application.

It is a Python based framework that allows you to connect websites with less amount of code. You can create a small-scale website with this as it allows customization at every step. Being a minimalist package, only core components are included and all other extensions require explicit configuration. Many developers use Flask to host their APIs. API (Application Program Interface) is an interface that allows communication between multiple intermediaries, which means that one can access any type of data using any technology. For instance, you can access an API using Javascript which could be built using Python. A simple program in a flask looks like this:

from flask import Flask, jsonify
app = Flask(__name__)
@app.route("/<name>", methods=['GET'])
def home(name):
    return jsonify({"message": f"Hello! {name}"})
if __name__ == "__main__":
    app.run(debug=True)

By pressing the url localhost / AnyNameHere, a JSON result similar to this will be displayed: (I use the chrome extension called JSON viewer. You may be prompted for plain text instead of this formatted output)

img_1-8741078

Problems with the flask

The problem with this approach is that there are no data validation, which means we can pass any type of data, be it chains, tuples, numbers or any character. This can break the program often and you can imagine that if an ML model gets wrong data types, the program will crash. You can create a data checker before passing the values ​​over, but I would add additional work.

Error pages in Flask as plain HTML pages that can generate decoder errors when the API is called in other applications. There are other problems with Flask, like slow nature, no asyncand web socket support that can speed up processes and, Finally, no automated document generation system. You need to manually design the UI for API usage and examples. All these problems are solved in the new framework.

FastAPI

It is a modern framework that allows you to create APIs smoothly and without much effort. Has the ability to separate server code from business logic increasing code maintainability. As the name itself is fast, it is much faster compared to the flask because it is built on ASGI (Asynchronous server gateway interface) instead of WSGI (Web server gateway interface). It has a data validation system that can detect any invalid data type at runtime and returns the reason for incorrect entries to the user only in JSON format, which frees developers from explicitly handling this exception.

That generates the documentation on the fly when you are developing the API, which is the most requested by all developers. Documentation is a great way for other developers to collaborate on a project, as it presents everything that can be done with the necessary instructions. It also generates a good GUI that solves everything that was missing in the flask.

It does all of these things with the OpenAI and Swagger specifications to implement these specifications. As a developer, it is only focusing on the logical construction part and the rest of the stuff is managed by FastAPI. Let's see the same example that was created using Flask now implemented in FastAPI:

import uvicorn
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def home(name: str):
    return {"message": f"Hello! {name}"}
if __name__ == "__main__":
    uvicorn.run(app, host="127.0.0.1", port=8000, debug=True)

By pressing the url localhost /? Name = AnyNameHere, you will be prompted for a result like:

img_2-7383572

You can see that the code is very similar to flask, but here we are using uvicorn server, what is an ASGI implementation. What's more, here we are without routing any end points and create them directly using decorators, what makes the most sense. The function here simply takes the required arguments further than eliminates the need for the request object be called.

img_3-9515011

There is another documentation generator that is included with FastAPI, namely, ReDoc which also generated a beautiful documentation with all the endpoints listed. It can be accessed by pressing the end point / redoc:

25693temp-4256177

To configure data validation, we can simply create the data type class inherited from the Pydantic base model. It is a library that offers data validation through Python type annotations. We can add the description of the entities and provide the custom example to display in the docs.

ML FastAPI example

I would like to share an example where an ML DecisionTree classifier model was implemented using FastAPI. The problem statement for this is a musical genre classifier where based on technical aspects of music such as tempo, the valencia, the music is rock or hip-hop. I did a music class to validate the data that will be passed to the model that looks like this:

from pydantic import BaseModel
class Music(BaseModel):
    acousticness: float 
    danceability: float 
    energy: float 
    instrumentalness: float 
    liveness: float 
    speechiness: float 
    tempo: float 
    valence: float

img_4-1385000

If you want to see the complete code, go to this GitHub repository.

Conclution: Which to choose?

After all this discussion, the question remains unanswered, who wins? Based on all factors, I would I suggest adopting FastAPI over Flask. Is very easy to configure, migrating an old flask project to this one will not take long, async, web sockets y automatic document generation function it's the cherry on top.

One can choose the flask frame to configure the whole web interface (Front-end y back-end) but in regards to ML where the main objective is to check if the model is working in production environment or not, creating an API makes more sense because the rest of the stuff can be managed by other teams of developers and to clearly explain to them the use of the program you developed, FastAPI auto docs is a good solution.

Connect with the author

You can connect with me at Linkedin to discuss anything related to Python development and data science, GitHub to see my projects or you can read my articles in the middle.

Kaustubh – Half

Subscribe to our Newsletter

We will not send you SPAM mail. We hate it as much as you.