Predictive Hacks

Fast & Easy Python APIs using FastAPI


FastAPI is a modern, python-based high-performance web framework used to create Rest APIs. Its key features are that is fast, up to 300% faster to code, fewer bugs, easy to use, and production-friendly.

The only con about Fast API is that it’s relatively new and its community is not so big as other frameworks like Flask but I think it will grow fast as many companies like Microsoft, Netflix, and Uber are already using it.

In this post, I will show you how to create some simple GET and POST APIs using Fast API.


pip install fastapi

We will also need an ASGI server, for production such as Uvicorn.

pip install uvicorn

Hello World

Let’s get started by creating the simplest API. It will return a JSON with the message “Hello World”.

Create a “” file with the following code.

#import FastAPI
from fastapi import FastAPI

#create a FastAPI instance
app = FastAPI()

#create a path operation
#define the path operation function
def root():
    return {"message": "Hello World"}

As you can see, there are 4 main steps to create an API with FastAPI. The first step is to import it, and then to create a FastAPI instance(in our case it’s called app).

After that, we have to create a path operation. That means we have to set the URL path(in our case is ‘/’ but we can set anything like ‘/helloworld’) and its operation. By operation we mean the HTTP methods like GET, POST, PUT and DELETE(in our case the operation is get).

Lastly, we have to define the path operation function. In other words, a function that returns what we want to get from our API(in our case is a JSON with the message Hello World.

Now, navigate to the’s folder through the terminal and run the following:

uvicorn main:app --reload

You should see the following output.

 python fastapi

That means that our API is running at Let’s see what we got.

Path Parameters

Let’s say we want to create a GET API that takes as input two numbers and returns their sum. To add the parameters you just have to put them as the parameters of the path operation function.

from fastapi import FastAPI

app = FastAPI()

def sum(a, b):
    return {"Result": a+b}

You can pass parameters to the URL by adding the symbol “?” then the parameters with the symbol “&” between them. Let’s try the following:
 python fastapi

Easy as that. You can also set the type of the parameters like integer or string so if the user puts a different type, it will return a warning.

def sum(a:int, b:int):
    return {"Result": a+b}

Let’s out a string and see what we will get.
 python fastapi


We will show you how you can create a POST API that expects as input a JSON file. Let’s see an easy example.

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class inputs(BaseModel):
def show_data(data: inputs):

We have to import BaseModel and create a BaseModel class that contains the variables of the JSON file(a, b, c, d in our example). Then, we have to set the class to a variable inside the operation function(data: inputs in our case). Now we can access the variable inside the function using the name of the class variable and the name of its variables like data.a to access the variable a, data.b, etc.

FastAPI provides us automatically with SwaggerUI which is a genius and very helpful UI that allows us to visualize and interact with the API’s resources. It can also be used for testing even for POST APIs like the above. You can access it by adding the /docs in your APIs URL.
 python fastapi

As you can see in the video above, we’ve tested our API and it runs perfectly.

Case Study: Serve a Machine Learning Model Via REST API

For this example, we will train a simple ML model to predict the type of irises (Setosa, Versicolour, and Virginica) using the famous Iris Dataset. Then we will create a POST API using FastAPI that will take as input the features and will return the prediction.

First things first, let’s train our model and save it to a pickle file.

from sklearn import datasets
from sklearn.linear_model import LogisticRegression
import pandas as pd
iris = datasets.load_iris()

import pickle
pickle.dump(model, open('model_iris', 'wb'))

Now, we are ready to create our API.

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class iris(BaseModel):
from sklearn.linear_model import LogisticRegression
import pandas as pd
import pickle
#we are loading the model using pickle
model = pickle.load(open('model_iris', 'rb'))

async def make_predictions(features: iris):

Now If you feed the API above with the following JSON you will get a prediction.

  "a": 1.1,
  "b": 3.3,
  "c": 5,
  "d": 1
  "prediction": "2"

Summing It Up

FastAPI is one of the best Python frameworks for Rest APIs because it’s fast, easy, and production-friendly. Its community will grow fast as companies like Netflix, Uber, and Microsoft are already using it. You don’t need anything more than we cover in this post to start, so start experiment with it!

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Leave a Comment

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore


Image Captioning with HuggingFace

Image captioning with AI is a fascinating application of artificial intelligence (AI) that involves generating textual descriptions for images automatically.


Intro to Chatbots with HuggingFace

In this tutorial, we will show you how to use the Transformers library from HuggingFace to build chatbot pipelines. Let’s