Building Production-Ready APIs on FastAPI (and not Flask)

Working on building an application that utilizes your own APIs? Application Program Interface (API) is the backbone for most web application and are popularly used in order to build a robust application.

When it comes to developing machine learning-based APIs, the de facto choice for most developers is to use Flask – a Python framework that allows you to build your website with a few lines of code. However, another framework, FastAPI is gaining momentum among developers these days and in this article, we will compare how FastAPI is different from Flask and how you can build a simple API with FastAPI.

FastAPI vs Flask

For starters, Flask is a minimal Python framework and is used by developers to host APIs (and also build applications). Flask was “good enough” in that it was popular, minimal, and written in Python.

A simple example of a flask application below:

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

The issue with Flask is that you can pass any value since there is no data validation. In an ML scenario especially, this can break your code. Some of the other issues include slow nature, support for async, and web sockets. There is also no automated docs generation system (Swagger) and you will need to manually design the user interface for the docs.

In Flask, to achieve async you can use threads (concurrency) or multiprocessing (parallelism) or by using tools like Celery or RQ. Similarly, for Authentication, you will need third-party extensions.

FastAPI is a modern way to build production-grade APIs. Build on ASGI (Asynchronous Server Gateway Interface) server, it allows you to separate your code from the rest of the application and thus increasing maintainability. FastAPI uses Pydantic for data validation and Starlette for tooling, making it fast compared to Flask.

One of the best features of FastAPI is automatic document generation (via JSON Schema and OpenAPI). This means you can automatically generate your docs and your developer can focus on the code and logic. Docs that be presented in Swagger UI and ReDocs.

FastAPI natively supports a number of security and authentication tools via the fastapi.security package. FastAPI also implements OAuth2 and OpenID Connect via the OpenAPI standards and natively supports CORS.

Getting Started

To install FastAPI you will need Python 3.6+

pip install fastapi

Unlike Flask, FastAPI does not have a built-in development server, hence an ASGI server such as Uvicorn, Daphne or Hypercorn is required for production.

pip install uvicorn[standard]

Now, you can create a main.py file

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

With Pydantic along with type hints, you get a nice editor experience with autocompletion. Pydantic is a library that offers data validation using Python-type annotations.

To run the application, uvicorn main:app –reload and open your browser http://127.0.0.1:8000/items/5?q=somequery.

You will get a JSON response as:

{"item_id": 5, "q": "somequery"}

To get access to the docs, visit http://127.0.0.1:8000/docs or http://127.0.0.1:8000/redoc.

For more details, visit https://fastapi.tiangolo.com/

Conclusion

When you compare Flask vs FastAPI – FastAPI is the clear winner. However, if you plan to build both front-end and backend, Flask is preferred. Migrating your existing work from Flask to FastAPI is also easy and all of the features including auto docs, async, WebSockets, GraphQL, and more.

Leave a Reply

Ask Bharat