Build a Flask REST API for ML predictions step-by-step. Integrate machine learning into your app with our simple guide.

Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
pickle or joblib to save the trained model after its development.
// Import necessary libraries
import flask
import pickle // For model deserialization
import numpy as np // For data manipulation
// Load the trained ML model
def load\_model():
with open('model.pkl', 'rb') as file:
model = pickle.load(file)
return model
// Global variable for the loaded model
model = load\_model()
// Create a Flask application instance
from flask import Flask, request, jsonify
app = Flask(**name**)
// Prediction route accepts POST requests with JSON payload
@app.route('/predict', methods=['POST'])
def predict():
// Retrieve JSON data
input_data = request.get_json()
try:
// Validate that the required input is present
features = input\_data['features']
// Convert features to numpy array for model compatibility
// Ensure that the data shape aligns with the model's expectation
features\_array = np.array(features).reshape(1, -1)
// Make prediction using the preloaded model
prediction = model.predict(features\_array)
// Return prediction as JSON response
return jsonify({'prediction': prediction.tolist()})
except Exception as e:
// Handle unexpected issues by returning an error message
return jsonify({'error': str(e)}), 400
// Optional: health check endpoint to ensure API status
@app.route('/health', methods=['GET'])
def health():
return jsonify({'status': 'API is up and running'})
// Preprocessing example - adapt it based on your model's needs:
def preprocess(features):
// Assume features need to be converted to float and normalized
try:
processed = [float(x) for x in features]
// If normalization is required, apply it here.
return processed
except Exception as e:
// Allow error propagation to be caught in predict() route
raise ValueError("Invalid input data: " + str(e))
// Integrate preprocessing into the prediction logic
@app.route('/predict', methods=['POST'])
def predict():
input_data = request.get_json()
try:
raw_features = input_data['features']
// Preprocess the raw features
features = preprocess(raw\_features)
features\_array = np.array(features).reshape(1, -1)
prediction = model.predict(features\_array)
return jsonify({'prediction': prediction.tolist()})
except Exception as e:
return jsonify({'error': str(e)}), 400
// Example: Adding basic logging for exceptions
import logging
logging.basicConfig(level=logging.INFO)
@app.errorhandler(Exception)
def handle\_exception(e):
// Log the exception details before sending a response
logging.error("Exception occurred: " + str(e))
return jsonify({'error': 'An internal error occurred.'}), 500
// Example command to run your Flask app using Gunicorn:
// gunicorn -w 4 app:app
// This starts 4 worker processes serving the application.
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.Â