Step-by-step guide: Connect your ML model to a frontend using the Fetch API for seamless, smart 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 loading the ML model
app = Flask(**name**)
// Load the pre-trained ML model
model = pickle.load(open('model.pkl', 'rb'))
// Create an endpoint for predictions
@app.route('/predict', methods=['POST'])
def predict():
// Get JSON data from the request
data = request.get\_json()
// Assume the data includes a list of features
features = data['features']
// Run the prediction using the ML model
prediction = model.predict([features])
// Respond with the prediction result as JSON
return jsonify({'prediction': prediction[0]})
if **name** == '**main**':
app.run(debug=True)
// Prepare the data to be sent to the backend API
const inputFeatures = [/_ your feature values here, e.g., 5.1, 3.5, 1.4, 0.2 _/];
// Create an object containing the data
const data = {
features: inputFeatures
};
// Use fetch to send a POST request to the API endpoint
fetch('http://localhost:5000/predict', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data) // Convert the data object to a JSON string
})
.then(response => response.json()) // Parse the response as JSON
.then(result => {
// Process the prediction result returned from the server
console.log('Prediction:', result.prediction);
// Optionally, update the DOM to display the prediction
})
.catch(error => {
// Handle any errors that occur during the fetch operation
console.error('Error:', error);
});
JSON.stringify..then() method manages the asynchronous response and allows you to handle the data once it is received.<div>.
// Example: Updating the UI with the prediction result
fetch('http://localhost:5000/predict', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(result => {
document.getElementById('prediction-result').innerText = 'Prediction: ' + result.prediction;
})
.catch(error => {
console.error('Error:', error);
});
prediction-result where the prediction will be displayed.flask-cors extension..then() to process data and catch any errors with .catch().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.Â