Sitemap
Towards AI

We build Enterprise AI. We teach what we learn. Join 100K+ AI practitioners on Towards AI Academy. Free: 6-day Agentic AI Engineering Email Guide: https://email-course.towardsai.net/

Programming

FastAPI — The Spiffy Way Beyond Flask!

An elegant and efficient framework to expose production-ready low latency APIs within minutes.

7 min readOct 12, 2020

--

Press enter or click to view image in full size

In recent times, there has been an exponential growth of data science and machine learning applications. With the advent of these data-driven applications, python is the go-to choice for most of the developers. In the last few years, python has jumped to the number one position for the languages used for ML which is mostly due to the convenience of packaging the models and exposing them as a service.

Model preparation and training is one of many steps in the machine learning lifecycle. Besides an active ML application, there go multiple things that work concurrently under the hood. On a high level, it includes Data cleaning and preparation, selecting and fine-tuning algorithms, model training, delivering the model prediction in the form of an endpoint by exposing an endpoint know as .

What is an API?

An A () is a computing interface that defines interactions between multiple software intermediaries. It defines the kinds of calls or requests that can be made, how to make them, the data formats that should be used, and the conventions to follow.

Think of FastAPI as a wrapper around your data science application to expose its functionality as RESTFUL microservices.

Since the inception of enterprise data science, Flask has been the standard for data scientists to quickly expose an HTTP endpoint for delivering the application. It’s fairly lightweight, mature, well-documented, and it’s been around for long enough to have established its root within organizations.

To productionize a machine learning model, the standard approach is to wrap it in a REST API and deploy it as a microservice. Flask is currently the de facto choice for writing these APIs for a couple of reasons:

  • Flask is minimal. Because inference APIs have historically tended to be simple predict() methods, the complexities introduced by more opinionated frameworks (like Django) have been seen as unnecessary.
  • Flask is written in Python, which has become the standard language of machine learning. All major frameworks have Python bindings, and virtually all data scientists/ML engineers are familiar with it.

What is FastAPI?

FastAPI is a modern, fast (high-performance), a web framework for building APIs with Python 3.6+ based on standard Python type hints. FastAPI is a Python API microframework built on top of Starlette, Pydantic, and Uvicorn.

Press enter or click to view image in full size
FastAPI is built on top of Pydantic and Starlette

All web frameworks need to balance between the functionality and flexibility for the developer. Flask is low level enough to provide a large degree of freedom, but a lot is left for the developer to do. FastAPI is just like Flask, but it manages to strike a healthier balance.

Why FastAPI?

  • One of the biggest disadvantages of Python WSGI web frameworks compared to the ones in Node.js or Go was the inability to handle requests asynchronously. Since the introduction of ASGI, this is no longer an issue, and FastAPI is taking full advantage of this. All you have to do is simply declare the endpoints with the async keyword like this:
@app.post("/")
def endpoint():
# ...
# call async functions here with `await`
# ...
return {"msg": "FastAPI is awesome!"}
  • FastAPI comes with an automated interactive interface in the form of API documentation. It has a simple, but elegant interface that creates an API document on the fly. The FastAPI is based on the open standards for OpenAPI and JSON Schema. As a result, it can automatically build a SwaggerUI for the web API without any additional coding as long as you use the appropriate Pydantic data types. SwaggerUI is interactive in nature and allows us to test an API directly from the browser. The automatic documentation has been inspired by the APISpec.
Press enter or click to view image in full size
Swagger UI for the FastAPI app
  • Flask users have to install the Flask-rest plus package to create REST endpoints for their data science application. The FastAPI supports the GET, PUT, POST, DELETE, OPTIONS, HEAD, PATCH, and TRACE Rest operations without any additional packages. All of the routes along with their operations are automatically generated in the documentation.
  • FastAPI comes up with a built-in injection system to handle dependencies at your endpoint. It provides an efficient way to implement user authentication.
  • FastAPI is the least complicated web framework among its peers when it comes to database integration. It doesn’t restrict you to build your application around a few databases of its choice. Instead, it supports all the databases you can think with a way to smoothly integrate them with your application.
  • FastAPI is really fast! It is not only fast to code, but it also processes requests super fast! In a survey done by TechEmpower benchmark tool to benchmark performance among multiple API frameworks, FastAPI outperformed flask by a large margin.
Press enter or click to view image in full size

FastAPI in Action:

FastAPI is built on the ideology of i.e If I have seen farther it is by standing on the shoulders of Giants. FastAPI stands on the shoulder of two significant giants:

Get Shubham Saboo’s stories in your inbox

Join Medium for free to get updates from this writer.

The FastAPI is available on PyPI in the form of an easy to install python package. The best thing about FastAPI is its Flask like simple syntax, which makes it very easy to adapt for someone who has previously used Flask.

$ pip install fastapi

As FastAPI is async by nature it also requires an ASGI server to expose the endpoints for production such as Uvicorn or Hypercorn.

$ pip install uvicorn
$ pip install hypercorn

Starting with FastAPI is as simple as it can get, you just need to have a file in your project where you can easily define the different API endpoints using decorators similarly to the flask.

# Import Dependencies
from typing import Optional
from fastapi import FastAPI
# Initialize the app with FastAPI object
app = FastAPI()
# First Endpoint
@app.get("/")
def read_root():
return {"Hello": "World"}
# Second Endpoint
@app.get("/items/{item_id}")
def read_item(item_id: int, q: Optional[str] = None):
return {"item_id": item_id, "q": q}

Till now it was very similar to what you have done with flask, and you might be wondering if I have to do the same things what sense does it make to ship my code from Flask to FastAPI. To justify your efforts FastAPI comes with this amazing on-the-fly interactive API document generator. It provides you with a cleaner, simpler and elegant user interface to try out your APIs from the web with zero lines of HTML code.

Press enter or click to view image in full size
Automated Interactive doc generated on-the-fly…

Now we will see the PUT method in action and how does the FastAPI use Pydantic at its core to declare the function body using standard python types.

# Importing Dependencies 
from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel
# Initialize the app with FastAPI object
app = FastAPI()
# Defining a custom object using Pydantic
class Item(BaseModel):
str price: float
is_offer: Optional[bool] = None
# Endpoint-1
@app.get("/")
def read_root():
return {"Hello": "World"}
# Endpoint-2
@app.get("/items/{item_id}")
def read_item(item_id: int, q: Optional[str] = None):
return {"item_id": item_id, "q": q}
# Endpoint-3
@app.put("/items/{item_id}")
def update_item(item_id: int, item: Item):
return {"item_name": item.name, "item_id": item_id}

Running the above code will result in triggering the events that will automatically create the API doc as per the updated endpoints.

Press enter or click to view image in full size

By clicking on it will provide you with a text box to input the item_id directly from the web interface and interact with the API.

Press enter or click to view image in full size

Now by clicking on the button, the user interface will automatically communicate with your API, send the parameters, get the results and show them on the screen

Press enter or click to view image in full size

Summary

FastAPI first came into the picture in 2018, as compared to flask it is a relatively new framework but still, it is becoming the de-facto choice for building high-performance data science applications. It follows a minimalist approach to that of flask but adds innovative features on top of that which makes it very efficient and intuitive to use.

If you would like to learn more or want to me write more on this subject, feel free to reach out…

My social links: LinkedIn| Twitter | Github

If you liked this post or found it helpful, please take a minute to press the clap button, it increases the post visibility for other medium users.

--

Towards AI
Towards AI

Published in Towards AI

We build Enterprise AI. We teach what we learn. Join 100K+ AI practitioners on Towards AI Academy. Free: 6-day Agentic AI Engineering Email Guide: https://email-course.towardsai.net/

Shubham Saboo
Shubham Saboo

Written by Shubham Saboo

AI PM at Google | Creator of Opensource Awesome LLM Apps repo | Founder of theunwindai.com