FastAPI Tutorial: Building APIs with Python in Minutes
Want to build APIs with Python? Learn how to do so using FastAPI with this step-by-step tutorial.
FastAPI is a popular web framework for building APIs with Python. It’s super simple to learn and is loved by developers. FastAPI leverages Python type hints and is based on Pydantic. This makes it simple to define 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 easier to build performant APIs that can handle I/O-bound operations efficiently.
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
Next, install the required packages. You can install FastAPI and uvicorn using pip:
$ pip3 install fastapi uvicorn
This installs FastAPI and all the required dependencies as well as uvicorn, the server that we’ll use to run and test the API that we build. Because we’ll build a simple machine learning model using scikit-learn, install it in your project environment as well:
$ pip3 install scikit-learn
With the installations out of the way, we can get to coding!
Step 2: Create a FastAPI App
Create a main.py file in the project directory. The first step is to create a FastAPI app instance like so:
# 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 that you work with when starting out with data science. It has 150 data records, 4 features, and a target label (species of Iris flowers). To keep things simple, let’s create an API to predict the Iris species.
FastAPI logo
In the coming steps, we’ll build a logistic regression model and create an API endpoint for prediction. After you’ve built the model and defined the /predict/
API endpoint, you should be able to make a POST request to the API with the input features and receive the predicted species as a response.
“FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints.” - FastAPI Documentation
Step 3: Define the Data Model
In this step, we’ll define the data model using Pydantic. We’ll create a class that inherits from Pydantic’s BaseModel. This class will define the structure of our data.
from pydantic import BaseModel
class IrisSpecies(BaseModel):
sepal_length: float
sepal_width: float
petal_length: float
petal_width: float
Step 4: Create the API Endpoint
Now that we have our data model defined, let’s create an API endpoint to predict the Iris species. We’ll use the /predict/
endpoint to receive the input features and return the predicted species.
from fastapi import FastAPI, HTTPException
from fastapi.responses import JSONResponse
from sklearn.linear_model import LogisticRegression
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
app = FastAPI()
# Load the Iris dataset
iris = load_iris()
X = iris.data
y = iris.target
# Split the dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Create a logistic regression model
model = LogisticRegression()
model.fit(X_train, y_train)
@app.post("/predict/")
async def predict_species(iris_species: IrisSpecies):
try:
# Make a prediction using the logistic regression model
prediction = model.predict([[iris_species.sepal_length, iris_species.sepal_width, iris_species.petal_length, iris_species.petal_width]])
return JSONResponse(content={"predicted_species": prediction[0]}, media_type="application/json")
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
Conclusion
In this tutorial, we’ve learned how to build a simple API using FastAPI. We’ve set up the environment, created a FastAPI app, defined a data model, and created an API endpoint to predict the Iris species. With FastAPI, you can build APIs quickly and efficiently.
FastAPI in action
FastAPI is a powerful tool for building APIs with Python. Its simplicity and ease of use make it a great choice for developers of all levels. Whether you’re building a simple API or a complex microservice architecture, FastAPI is a great choice.
FastAPI architecture
By following this tutorial, you’ve taken the first step in building APIs with FastAPI. With practice and patience, you’ll become proficient in building APIs quickly and efficiently.
FastAPI in production