Site icon Towards AI

FastAPI — the spiffy way beyond flask!

Author(s): Shubham Saboo

Programming

FastAPI — The Spiffy Way Beyond Flask!

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

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 “API”.

What is an API?

An Application Programming Interface (API) 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:

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.

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?

@app.post("/")
async def endpoint():
# ...
# call async functions here with `await`
# ...
return {"msg": "FastAPI is awesome!"}
Swagger UI for the FastAPI app

FastAPI in Action:

FastAPI is built on the ideology of “nanos gigantum humeris insidentes” i.e If I have seen further it is by standing on the shoulders of Giants. FastAPI stands on the shoulder of two big giants:

Installation

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

Examples with Illustrations

Starting with FastAPI is as simple as it can get, you just need to have a main.py 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.

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.

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

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

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| TwitterGithub

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.


FastAPI — the spiffy way beyond flask! was originally published in Towards AI — Multidisciplinary Science Journal on Medium, where people are continuing the conversation by highlighting and responding to this story.

Published via Towards AI

Exit mobile version