Build an ML Model API using Flask & Python with our step-by-step guide. Learn expert tips, code examples, and easy deployment.

Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
joblib or pickle.my\_model, save it as:
import joblibjoblib.dump(my\_model, 'model.pkl') // This writes the model to a file named model.pkl
// Import Flask to create API endpoints
from flask import Flask, request, jsonify
// For model loading
import joblib
// Create the Flask app
app = Flask(**name**)
// Load the trained model
try:
model = joblib.load('model.pkl') // 'model.pkl' contains your saved model
except Exception as e:
print("Failed to load model:", e)
// Optionally, exit or set model as None and handle in routes
model = None
// Define an API endpoint for predictions
@app.route('/predict', methods=['POST'])
def predict():
// Ensure that the model has been loaded
if model is None:
return jsonify({"error": "Model not loaded"}), 500
// Parse input JSON from the request
data = request.get\_json(force=True)
// Extract features from the JSON, for example, assuming an array of features under 'input'
features = data.get('input', None)
if features is None:
return jsonify({"error": "No input data provided"}), 400
// Optionally preprocess the features here (e.g., scaling, transforming, etc.)
try:
// Make prediction using the loaded model
prediction = model.predict([features])
// Convert prediction to a list in case it is a numpy array
prediction\_result = prediction.tolist()
except Exception as e:
return jsonify({"error": "Prediction failed", "message": str(e)}), 500
// Return the prediction in JSON format
return jsonify({"prediction": prediction\_result})
// Run the flask app
if **name** == '**main**':
// Use debug mode for development; disable in production
app.run(host='0.0.0.0', port=5000, debug=True)
curl -X POST -H "Content-Type: application/json" -d '{"input": [/_ your feature values here _/]}' http://localhost:5000/predicthttp://localhost:5000/predict to observe the prediction output.logging module can be useful for this.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.Â