Step-by-step guide to build a REST API for your ML model. Discover coding, integration, and deployment tips for smooth operations.

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 libraries for modeling and saving
import joblib
from sklearn.datasets import load\_iris
from sklearn.linear\_model import LogisticRegression
// Load dataset and train a basic logistic regression model
data = load\_iris()
X, y = data.data, data.target
model = LogisticRegression(max\_iter=200)
model.fit(X, y)
// Save the trained model to disk
joblib.dump(model, 'model.pkl') // Saves model to the file 'model.pkl'
// Import Flask for building the REST API
from flask import Flask, request, jsonify
import joblib
// Initialize the Flask application
app = Flask(**name**)
// Load the pre-saved ML model during startup for efficiency
model = joblib.load('model.pkl')
// Define a route '/predict' that listens to POST requests
@app.route('/predict', methods=['POST'])
def predict():
// Extract JSON data from POST request
data = request.get\_json(force=True)
// Validate presence of 'features' key in data
if 'features' not in data:
return jsonify({'error': 'No features provided in request'}), 400
try:
// Convert features into proper data structure for the model, e.g., list to array
features = data['features']
// Generate prediction using the loaded model
prediction = model.predict([features])
// Return the prediction as a JSON object
return jsonify({'prediction': prediction[0]})
except Exception as e:
// In case of an error, return an error response with the exception message
return jsonify({'error': str(e)}), 500
// Run the Flask app (development mode) when this script is executed
if **name** == '**main**':
app.run(debug=True)
// Example of sending a test request using curl
// Command to execute in your terminal
// curl -X POST -H "Content-Type: application/json" -d '{"features": [5.1, 3.5, 1.4, 0.2]}' http://127.0.0.1:5000/predict
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.Â