Deploying Machine Learning Models with Flask, FastAPI, or Streamlit: An In-Depth Guide
Deploying machine learning models enables your applications to make real-time predictions and decisions. This tutorial shows how to deploy…
Deploying Machine Learning Models with Flask, FastAPI, or Streamlit: An In-Depth Guide

Deploying machine learning models enables your applications to make real-time predictions and decisions. This tutorial shows how to deploy machine learning models with Flask, FastAPI, and Streamlit using unique and realistic examples. Each framework is useful for different scenarios: Flask and FastAPI are well-suited for backend applications, while Streamlit is excellent for creating interactive user interfaces.
Step 1: Prepare Your Machine Learning Model
Before deploying, we need a trained model. In this example, let’s use a predictive maintenance model for a manufacturing company. The goal is to predict when machinery will break down so that preventative maintenance can be performed.
Imagine a company has sensor data from machines (e.g., temperature, vibration, pressure, etc.). We’ll use this data to predict when a machine is likely to fail, and deploy the model using Flask, FastAPI, and Streamlit.
Here’s how you can train a simple predictive maintenance model using scikit-learn and save it for deployment.
Train the Predictive Maintenance Model
import pickle
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
# Load some sample data (simulated maintenance data)
data = pd.read_csv("machine_data.csv")
# Example features: sensor readings for a machine (e.g., temperature, vibration, pressure)
X = data[['temperature', 'vibration', 'pressure']]
y = data['failure'] # Binary: 1 = failure, 0 = no failure
# Split the data 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)
# Train the model
model = RandomForestClassifier()
model.fit(X_train, y_train)
# Save the trained model
with open("predictive_maintenance_model.pkl", "wb") as f:
pickle.dump(model, f)
Step 2: Deploy with Flask
Flask is a lightweight framework for building web APIs. It’s perfect for serving a machine learning model through an API endpoint.
Install Flask
# Install using your CLI
pip install flask
Create the Flask Application
Here’s how to deploy the predictive maintenance model using Flask:
from flask import Flask, request, jsonify
import pickle
import numpy as np
# Load the model
with open("predictive_maintenance_model.pkl", "rb") as f:
model = pickle.load(f)
# Initialize Flask app
app = Flask(__name__)
@app.route("/predict", methods=["POST"])
def predict():
try:
# Parse the input data (sensor readings)
data = request.get_json()
features = np.array(data["features"]).reshape(1, -1)
# Make predictions
prediction = model.predict(features)
result = "Failure predicted" if prediction[0] == 1 else "No failure predicted"
return jsonify({"prediction": result})
except Exception as e:
return jsonify({"error": str(e)}), 400
if __name__ == "__main__":
app.run(debug=True)
Testing the Flask API
Save the file as app.py and run it:
python app.py
Send a POST request to http://127.0.0.1:5000/predict with the machine sensor data:
curl -X POST -H "Content-Type: application/json" \
-d '{"features": [75.5, 0.7, 25.4]}' \
http://127.0.0.1:5000/predict
This will output:
{
"prediction": "No failure predicted"
}
Step 3: Deploy with FastAPI
FastAPI is another great option for serving machine learning models. It’s fast, has built-in validation, and auto-generates documentation.
Install FastAPI and Uvicorn
pip install fastapi uvicorn
Create the FastAPI Application
Here’s how to deploy the predictive maintenance model using FastAPI:
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import pickle
import numpy as np
# Load the model
with open("predictive_maintenance_model.pkl", "rb") as f:
model = pickle.load(f)
# Initialize FastAPI app
app = FastAPI()
# Define input data schema
class Features(BaseModel):
features: list[float]
@app.post("/predict")
def predict(features: Features):
try:
# Convert features to a numpy array
data = np.array(features.features).reshape(1, -1)
# Make predictions
prediction = model.predict(data)
result = "Failure predicted" if prediction[0] == 1 else "No failure predicted"
return {"prediction": result}
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
Testing and Documentation
Save as main.py and run it:
uvicorn main:app --reload
Access the Swagger UI at http://127.0.0.1:8000/docs to test the /predict endpoint interactively.
Step 4: Deploy with Streamlit
Streamlit is ideal for creating interactive apps for non-technical users. Let’s create an easy-to-use dashboard where users can input sensor readings and get predictions.
Install Streamlit
pip install streamlit
Create the Streamlit Application
Here’s how to create an interactive user interface for the predictive maintenance model using Streamlit:
import streamlit as st
import pickle
import numpy as np
# Load the model
with open("predictive_maintenance_model.pkl", "rb") as f:
model = pickle.load(f)
# Streamlit app
st.title("Predictive Maintenance Dashboard")
st.write("Enter the machine sensor readings to predict failures:")
# Input fields for sensor data
temperature = st.number_input("Temperature", value=75.5)
vibration = st.number_input("Vibration", value=0.7)
pressure = st.number_input("Pressure", value=25.4)
# Make prediction when button is clicked
if st.button("Predict"):
features = np.array([temperature, vibration, pressure]).reshape(1, -1)
prediction = model.predict(features)
result = "Failure predicted" if prediction[0] == 1 else "No failure predicted"
st.write(result)
Running the Streamlit App
Save as app.py and run it:
streamlit run app.py
This will launch an interactive web app where users can input sensor data and see predictions in real time.
Step 5: Real-World Considerations
Flask vs FastAPI vs Streamlit:
- Flask: Best for backend APIs that will be consumed by other services or systems.
- FastAPI: Ideal for high-performance APIs with automatic validation and documentation.
- Streamlit: Perfect for quick interactive web applications and dashboards where stakeholders can visualize data and predictions.
- Model Retraining: In production, periodically retrain models with fresh data to ensure predictions remain accurate.
- Security: For Flask and FastAPI applications, add authentication mechanisms (e.g., OAuth, API keys) to protect endpoints.
- Model Versioning: Use version control for your models and deploy new versions seamlessly without disrupting existing services.
Validating User Input in Production
When you deploy an ML app that collects user phone numbers — for signup, SMS alerts, or fraud detection — you’ll eventually need to validate them. Invalid numbers cause failed deliveries and poor user experience.
Here’s a simple solution I built for my own projects.
What it does
- Checks if a phone number is real (200+ countries)
- Returns carrier, timezone, and location
- Supports batch validation (up to 100 numbers at once)
Pricing
- Free: 1,500 requests/month (no credit card)
- Pro: $19 for 15,000 requests
- Ultra: $49 for 75,000 requests
Try it 👉 [Phone Validation API — Free Tier]
Open source. No hype.
I needed this for my own deployed apps. Thought others might find it useful too.
🛠️ Stop Writing Error Handlers From Scratch
If you’re building FastAPI apps, you’re probably tired of writing the same error responses over and over.
I built a library that handles it all:
- ✅
raise_400()toraise_500()helpers - ✅ Global exception handler
- ✅ Validation error formatting
- ✅ Rate limiting
Used in my production APIs on RapidAPI (8.6 popularity).
👉 [FastAPI Error Handler Library — $39]
Saves 2–3 hours per project. Commercial license included.
Conclusion
By deploying machine learning models using frameworks like Flask, FastAPI, and Streamlit, you enable users to interact with your models in real-time. Flask and FastAPI are perfect for backend services, while Streamlit provides an easy interface for non-technical users. By choosing the appropriate tool, you can make your machine learning models accessible and impactful in real-world applications like predictive maintenance in manufacturing.
📦 Resources
메타데이터
- post_id
- 30c2e1f2ee44
- slug
- deploying-machine-learning-models-with-flask-fastapi-or-streamlit-an-in-depth-guide-30c2e1f2ee44
- url
- https://medium.com/@emyasenc/deploying-machine-learning-models-with-flask-fastapi-or-streamlit-an-in-depth-guide-30c2e1f2ee44
- canonical_url
- https://medium.com/@emyasenc/deploying-machine-learning-models-with-flask-fastapi-or-streamlit-an-in-depth-guide-30c2e1f2ee44
- author_url
- https://medium.com/@emyasenc
- status
- ok
- fetched_at
- 2026-07-08 08:18:29