Deploying a machine learning model isn’t just about training it—it’s about making it accessible to the outside world so other applications (websites, apps, services) can actually use it.
That’s where FastAPI comes in. FastAPI is a modern Python framework that makes it super easy to turn your machine learning model into a web API.
In this guide, you’ll build an API that predicts the species of a penguin based on its bill length and flipper length. You’ll:
- Train a small machine learning model
- Save it
- Build an API around it
- Run it locally and test it with Swagger UI (an auto-generated interface)
Even if this is your first ML deployment, you’ll be able to follow along.
- Python 3.7 or higher installed
- Basic knowledge of Python (you can run scripts and install packages)
- That’s it! (You don’t need deep ML knowledge — I’ll keep it simple.)
Step 1: Set Up Your Environment
Create a project folder:
mkdir penguin_api && cd penguin_api
💡 This makes a new folder called penguin_api and moves you into it.
📸 Screenshot idea: terminal showing the penguin_api folder created and entered.
Create a Virtual Environment
# Windows python -m venv venv venvScriptsactivate # macOS/Linux python3 -m venv venv source venv/bin/activate
👉 If it works, you should see (venv) at the start of your terminal prompt.
📸 Screenshot idea: terminal showing (venv) active.
Install Required Packages
pip install fastapi uvicorn scikit-learn pandas
✅ If successful, you’ll see packages downloading with no errors.
📸 Screenshot idea: pip installation logs.
Step 2: Prepare Your Machine Learning Model
You’ll use the Palmer Penguins dataset. It has measurements of penguins’ bills and flippers, which can predict the species.
👉 Download the dataset as penguins.csv from this repo and put it in your project folder.
📸 Screenshot idea: project folder with penguins.csv visible.
Create the Model Script
Create a file called model.py and add:
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier import pickle df = pd.read_csv("penguins.csv") X = df[["bill_length_mm", "flipper_length_mm"]] y = df["species"] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) clf = RandomForestClassifier() clf.fit(X_train, y_train) with open("model.pkl", "wb") as f: pickle.dump(clf, f)
Run:
python model.py
✅ If successful, you’ll see no errors and a file called model.pkl in your folder.
📸 Screenshot idea: project folder showing model.py and model.pkl.
Step 3: Create the FastAPI Application
Create a file called main.py:
from fastapi import FastAPI from pydantic import BaseModel import pickle with open("model.pkl", "rb") as f: model = pickle.load(f) app = FastAPI() class PenguinFeatures(BaseModel): bill_length_mm: float flipper_length_mm: float @app.post("/predict") def predict(features: PenguinFeatures): data = [[features.bill_length_mm, features.flipper_length_mm]] prediction = model.predict(data) return {"species": prediction[0]}
📸 Screenshot idea: VSCode (or your editor) with main.py open.
Step 4: Run Your FastAPI Application
Run:
uvicorn main:app --reload
✅ If successful, your terminal should show:
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
📸 Screenshot idea: terminal showing Uvicorn running.
Step 5: Test Your API with Swagger UI
Go to: http://127.0.0.1:8000/docs
You’ll see Swagger UI, which lists your API endpoints.
📸 Screenshot idea: Swagger UI page open in browser.
- Open
/predict. - Click “Try it out.”
- Enter sample values, e.g.:
-
bill_length_mm:40.0 -
flipper_length_mm:200.0- Click “Execute.”
✅ You’ll see a JSON response like:
{"species": "Adelie"}
📸 Screenshot idea: Swagger UI showing the response JSON.
🏁 Conclusion
Congrats 🎉 — you just built and deployed your first machine learning API with FastAPI! In this guide, you set up your environment, trained a simple model, created an API, and tested it with real predictions.
This is just the start — once you’re comfortable, you can:
Swap in a different dataset or ML model.
Add more features to your API.
Deploy to the cloud (AWS, GCP, Azure, or even free services like Render).
By following these steps, you now know how to share an ML model through an API so others can use it — a core skill in modern AI and data engineering.
📸 Final screenshot idea: a “success” response in Swagger UI with the penguin prediction.
Source: DEV Community.

Leave a Reply