Image by author
FastAPI is a popular web framework for creating APIs with Python. It's very easy to learn and developers love it.
FastAPI takes advantage of Python type hints and is based on Pydantic. This simplifies the definition of data models and request/response schemas. The framework automatically validates request data against these schemas, reducing potential errors. It also natively supports asynchronous endpoints, making it easy to build high-performance APIs that can handle I/O-bound operations efficiently.
This tutorial will teach you how to create your first API with FastAPI. From setting up your development environment to creating an API for a simple machine learning application, this tutorial takes you through all the steps: defining data models, API endpoints, handling requests, and more. By the end of this tutorial, you will have a good understanding of how to use FastAPI to create APIs quickly and efficiently. Then let's get started.
Step 1: Set up the environment
FastAPI requires Python 3.7 or later. So make sure you have a recent version of Python installed. In the project directory, create and activate a dedicated virtual environment for the project:
$ python3 -m venv v1
$ source v1/bin/activate
The above command to activate the virtual environment works if you are on Linux or MacOS. If you are a Windows user, check the documents to create and activate virtual environments.
Next, install the necessary packages. You can install FastAPI and uvicorn using pip:
$ pip3 install fastapi uvicorn
This installs FastAPI and all required dependencies, as well as uvicorn, the server we will use to run and test the API we built. Because we will be building a simple machine learning model using scikit-learn, install it in your project environment as well:
$ pip3 install scikit-learn
With the installations ready, we can start coding! You can find the code at GitHub.
Step 2 – Create a FastAPI application
Create a main.py file in the project directory. The first step is to create a FastAPI application instance like this:
# Create a FastAPI app
# Root endpoint returns the app description
from fastapi import FastAPI
app = FastAPI()
The Iris dataset is one of the toy datasets you work with when you get started with data science. It has 150 data records, 4 characteristics and a target tag (iris flower species). To keep things simple, let's create an API to predict Iris species.
In the next steps, we will create a logistic regression model and create an API endpoint for the prediction. After having built the model and defined the /predict/
API endpoint, you should be able to make a POST request to the API with the input characteristics and receive the expected species in response.
Iris Prediction API | Image by author
To make it useful, let's also define a root endpoint that returns the description of the application we are creating. For this we define the get_app_description
function and create the root endpoint with the @app
decorator like this:
# Define a function to return a description of the app
def get_app_description():
return (
"Welcome to the Iris Species Prediction API!"
"This API allows you to predict the species of an iris flower based on its sepal and petal measurements."
"Use the '/predict/' endpoint with a POST request to make predictions."
"Example usage: POST to '/predict/' with JSON data containing sepal_length, sepal_width, petal_length, and petal_width."
)
# Define the root endpoint to return the app description
@app.get("https://www.kdnuggets.com/")
async def root():
return {"message": get_app_description()}
Sending a GET request to the root endpoint returns the description.
Step 3: Build a Logistic Regression Classifier
So far we have created an instance of a FastAPI application and defined a root endpoint. Now is the time to do the following:
- Build a machine learning model. We will use a logistic regression classifier. If you want to learn more about logistic regression, read Building Predictive Models: Logistic Regression in Python.
- Define a prediction function that takes the input features and uses the machine learning model to make a prediction for the species (one for setosa, versicolor, and virginica).
Logistic regression classifier | Image by author
We build a simple logistic regression classifier from scikit-learn and define the predict_species
work as shown:
# Build a logistic regression classifier
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
# Load the Iris dataset
iris = load_iris()
x, y = iris.data, iris.target
# Train a logistic regression model
model = LogisticRegression()
model.fit(x, y)
# Define a function to predict the species
def predict_species(sepal_length, sepal_width, petal_length, petal_width):
features = ((sepal_length, sepal_width, petal_length, petal_width))
prediction = model.predict(features)
return iris.target_names(prediction(0))
Step 4: Define the Pydantic model for the input data
Next, we need to model the data we send in the POST request. Here the input features are the length and width of the sepals and petals, all floating point values. To model this, we create a IrisData
class that inherits from Pydantic BaseModel
class like this:
# Define the Pydantic model for your input data
from pydantic import BaseModel
class IrisData(BaseModel):
sepal_length: float
sepal_width: float
petal_length: float
petal_width: float
If you need a quick tutorial on using Pydantic for data modeling and validation, read Pydantic Tutorial: Data Validation in Python Made Easy.
Step 5: Create an API endpoint
Now that we have built the classifier and defined the predict_species
When the function is ready, we can create the API endpoint for the prediction. As before, we can use the @app
decorator to define the /predict/
Endpoint that accepts a POST request and returns the expected species:
# Create API endpoint
@app.post("/predict/")
async def predict_species_api(iris_data: IrisData):
species = predict_species(iris_data.sepal_length, iris_data.sepal_width, iris_data.petal_length, iris_data.petal_width)
return {"species": species}
And it's time to run the application!
Step 6: Run the app
You can run the application with the following command:
$ uvicorn main:app --reload
Here main
is the name of the module and app
is the FastAPI instance. He --reload
flag ensures that the application is reloaded if there is any change to the source code.
When you run the command, you should see similar INFORMATION messages:
INFO: Will watch for changes in these directories: ('/home/balapriya/fastapi-tutorial')
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process (11243) using WatchFiles
INFO: Started server process (11245)
INFO: Waiting for application startup.
INFO: Application startup complete.
…
…
If you navigate to “http://127.0.0.1:8000″(localhost), you should see the application description:
Application running on localhost
Step 7: Test the API
You can now send POST requests to /predict/
final point with the measurements of sepals and petals, with valid values, and obtain the predicted species. You can use a command line utility like cURL. Here is an example:
curl -x 'POST' \
'http://localhost:8000/predict/' \
-H 'Content-Type: application/json' \
-d '{
"sepal_length": 5.1,
"sepal_width": 3.5,
"petal_length": 1.4,
"petal_width": 0.2
}'
For this example request, this is the expected result:
Ending
In this tutorial, we go over creating an API with FastAPI for a simple classification model. We go through modeling the input data to be used in the requests, define the API endpoints, run the application, and query the API.
As an exercise, take an existing machine learning model and build an API on top of it using FastAPI. Happy coding!
twitter.com/balawc27″ rel=”noopener”>Bala Priya C. is a developer and technical writer from India. He enjoys working at the intersection of mathematics, programming, data science, and content creation. His areas of interest and expertise include DevOps, data science, and natural language processing. He likes to read, write, code and drink coffee! Currently, he is working to learn and share his knowledge with the developer community by creating tutorials, how-to guides, opinion pieces, and more. Bala also creates engaging resource descriptions and coding tutorials.
<script async src="//platform.twitter.com/widgets.js” charset=”utf-8″>