Deploy your ML model with Flask using our step-by-step guide. Learn coding tips, secure deployment, and quick integration for success.

Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
model.pkl) is in the correct directory and accessible.
// Import necessary modules from Flask and Python libraries
from flask import Flask, request, jsonify // Flask serves HTTP requests, request processes incoming data, and jsonify formats response as JSON
import pickle // Pickle is used to serialize and deserialize Python objects
// Initialize the Flask app
app = Flask(**name**)
// Load the machine learning model from a pre-saved file
with open("model.pkl", "rb") as model\_file:
model = pickle.load(model\_file) // The model is now loaded and ready to make predictions
/predict) that can receive HTTP requests with input data for which you want to make predictions.
// Define an API endpoint for making predictions
@app.route("/predict", methods=["POST"])
def predict():
try:
data = request.get\_json() // Get JSON data from the request body
// Extract input features assuming data contains a key "features"
features = data["features"]
// Preprocess the input if necessary (scaling, encoding, etc.)
// For demonstration, assume that 'features' are ready to use
prediction = model.predict([features]) // Use the loaded model to predict; wrapped in a list if model expects 2D array
result = {"prediction": prediction[0]} // Extract prediction output
return jsonify(result) // Return the prediction in JSON format
except Exception as e:
// Handle potential errors and return an error message
return jsonify({"error": str(e)})
gunicorn -w 4 app:app in your terminal. Here, -w 4 specifies four worker processes, and app:app implies that your Flask instance is named app inside your file app.py.
// Note: This is a command-line instruction, not a code snippet inside Python
// Command to run the app with Gunicorn:
// gunicorn -w 4 app:app
// Extended predict endpoint with additional validation
@app.route("/predict", methods=["POST"])
def predict():
data = request.get\_json()
if not data or "features" not in data:
return jsonify({"error": "Missing 'features' in the request data"}), 400 // Return status code 400 for bad request
try:
features = data["features"]
// Optionally, insert preprocessing functions here
prediction = model.predict([features])
result = {"prediction": prediction[0]}
return jsonify(result)
except Exception as e:
return jsonify({"error": str(e)}), 500 // Return status code 500 for server errors
/predict endpoint. This helps ensure that the API works as expected.{ "features": [your, feature, values] }.
// Example: Using cURL (to be executed in a terminal environment)
// curl -X POST -H "Content-Type: application/json" -d '{"features": [1.5, 2.3, 3.1]}' http://127.0.0.1:5000/predict
// Example: Basic logging integration
import logging
logging.basicConfig(level=logging.INFO)
@app.before\_request
def log_request_info():
logging.info("Received request: " + request.method + " " + request.url)
From startups to enterprises and everything in between, see for yourself our incredible impact.
Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We’ll discuss your project and provide a custom quote at no cost.Â