Step-by-step guide: Call your Python ML model from a JavaScript frontend for quick, seamless integration.

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 modules
from flask import Flask, request, jsonify
import pickle // For model deserialization (if using pickle)
// Import any necessary libraries for your ML model here
app = Flask(**name**)
// Load your pre-trained ML model
// For instance, if your model is saved in a pickle file:
model = pickle.load(open("model.pkl", "rb"))
// Define an API endpoint for making predictions
@app.route('/predict', methods=['POST'])
def predict():
// Get incoming JSON data from the frontend
data = request.get\_json(force=True)
// Assume the data contains input features for the model
features = data['features']
// Perform prediction. This could be as simple as:
prediction = model.predict([features])
// Return the prediction result in JSON format
return jsonify({"prediction": prediction[0]})
if **name** == '**main**':
// Run the app on local host port 5000
app.run(host='0.0.0.0', port=5000)
// Define an asynchronous function to make a POST request to the Flask endpoint
async function callModel(features) {
try {
const response = await fetch('http://localhost:5000/predict', {
method: 'POST', // Sending a POST request
headers: {
'Content-Type': 'application/json'
},
// Convert your features into a JSON object that the API can use
body: JSON.stringify({ features: features })
});
// Get the JSON response from the server
const result = await response.json();
// Process the prediction result as needed
console.log('Prediction:', result.prediction);
} catch (error) {
// Handle errors here
console.error('Error calling prediction API:', error);
}
}
// Example usage: suppose your model expects an array of numbers
const sampleFeatures = [5.1, 3.5, 1.4, 0.2];
callModel(sampleFeatures);
flask-cors package.
// In your Flask app file, after other imports, add:
from flask\_cors import CORS
// Then, after app initialization:
CORS(app)
// This enables CORS requests for all domains.
// Alternatively, you can restrict allowed origins by passing parameters to CORS.
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.Â