Is FastApi better than Flask?

Prakash R
featurepreneur
Published in
4 min readAug 19, 2021

Deployment of machine learning models can take different routes depending upon the platform where you want to serve the model. The web interface is the most common way to serve a model but not limited to android and IOS apps or an IOT device like Raspberry Pi. If you research this in detail, then one framework that tops the search query is the flask framework which is a minimalistic application to quickly set up web servers but it has some issues which are now solved in a newly released framework call FastAPI which is gaining a lot of popularity these days.

In this article, we will see how the FastAPI framework has an edge over Flask with an example code to understand things in a better way.

Flask

It is a Python-based framework that allows you to hook up websites with less amount of code. You can create a small-scale website with this as it allows customization at every step. Being a minimalistic package, only core components are bundled with this and all other extensions require explicit setup. Flask is used by many developers to host their APIs. API (Application Program Interface) is an interface that allows communication between multiple intermediaries meaning 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 flask looks like this:

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

Problems with Flask

The problem with this approach is that there is no data validation, meaning, that we can pass any type of data being it string, tuple, numbers, or any character. This can break the program often and you can imagine if an ML model getting wrong data types, the program will crash. You can create a data checker before passing the values further but it would add up additional work.

The error pages in Flask as simple HTML pages that can raise decoder errors when the API is being called in other applications. There are other issues with Flask such as slow nature, no async, and web sockets support that can speed up the processes, and finally no automated docs generation system. You need to manually design the user interface for the usage and examples of the API. All these issues are resolved in the new framework.

FastAPI

It is a modern framework that allows you to build APIs seamlessly without much effort. It has the ability to separate the server code from the business logic increasing code maintainability. As the name itself has fast in it, it is much faster as compared to the flask because it’s built over 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 the runtime and returns the reason for bad inputs to the user in the JSON format only which frees developers from managing this exception explicitly.

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

It does all these things OpenAI specifications and Swagger for implementing these specifications. Being a developer, you are only focusing on the logic building part and the rest of the things are managed by the FastAPI. Let’s look at the same example which was created using Flask now implemented in FastAPI:

import uvicornfrom fastapi import FastAPIapp = 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)

You can see that the code is very similar to flask but here we are using uvicorn server which is an ASGI implementation. Also, here we are not routing any endpoints and creating them directly using decorators which makes more sense. The function here simply takes the arguments required further which eliminates the need for the request object to be called.

Conclusion

Based on all the factors, I would suggest adopting FastAPI over Flask. It is very easy to set up, migrating an old flask project into this won’t take much time, async, web sockets, and automatic docs generation feature is the cherry on top.

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

--

--