Build a Flask web app with machine learning inference. Our step-by-step guide makes integrating ML simple and efficient.

Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
// Import necessary Python modules
from flask import Flask, request, jsonify
import pickle // For loading the pretrained model
import numpy as np // For data manipulation if required
// Initialize the Flask application
app = Flask(**name**)
// Load the pretrained ML model
// Ensure that the model file 'model.pkl' is available in your project directory
with open('model.pkl', 'rb') as model\_file:
model = pickle.load(model\_file)
// Define the /predict endpoint accepting POST requests
@app.route('/predict', methods=['POST'])
def predict():
// Extract the input JSON data from the request
data = request.get\_json(force=True)
// Expecting the JSON data to have a key "features" which is a list of values
// Example payload: { "features": [3.1, 1.2, 0.5, 2.4] }
features = data.get('features', None)
if features is None:
// Return an error response if 'features' key is missing
return jsonify({'error': 'No features provided'}), 400
try:
// Convert the input list into a NumPy array and reshape it if model expects 2D input
input\_data = np.array(features).reshape(1, -1)
except Exception as e:
// Return error response in case of conversion failure
return jsonify({'error': 'Invalid features format', 'message': str(e)}), 400
try:
// Perform prediction using the loaded model
prediction = model.predict(input\_data)
// You might also want to provide probability using model.predict\_proba if available
// probabilities = model.predict_proba(input_data) if hasattr(model, "predict\_proba") else None
// Return the prediction as JSON
return jsonify({'prediction': prediction.tolist()})
except Exception as e:
// Catch any exception during prediction and return an error message
return jsonify({'error': 'Prediction failed', 'message': str(e)}), 500
// End of the prediction endpoint
// Check if this script is executed directly and then run the Flask application
if **name** == '**main**':
// Enable debug mode for development; disable in production
app.run(debug=True)
// Sample curl command to test the inference endpoint
curl -X POST http://localhost:5000/predict -H "Content-Type: application/json" -d '{"features": [3.2, 1.5, 0.7, 2.1]}'
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.Â