Step-by-step guide: Build a React frontend with a Python backend & ML integration for smart, scalable AI web apps.

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 dependencies for API and ML model deployment
from fastapi import FastAPI
from pydantic import BaseModel
import joblib // For loading scikit-learn models
// Define the input data schema
class PredictionRequest(BaseModel):
feature1: float
feature2: float
// Add more features as required
// Define the response schema
class PredictionResponse(BaseModel):
prediction: float
// Initialize FastAPI app
app = FastAPI()
// Load the pre-trained ML model
model = joblib.load("model.pkl") // Ensure the model is saved using joblib.dump()
// Create an endpoint for predictions
@app.post("/predict", response\_model=PredictionResponse)
async def predict(data: PredictionRequest):
// Prepare input for the ML model
features = [[data.feature1, data.feature2]] // Use same order as your training data
// Generate prediction using the loaded model
prediction = model.predict(features)[0]
// Return the prediction in JSON format
return PredictionResponse(prediction=prediction)
/predict that accepts a JSON payload, validates it against the PredictionRequest model, processes it through your ML model, and returns a prediction.
fetch API or libraries like axios to send HTTP POST requests to the Python API. Ensure your endpoints are accessible, possibly using CORS (Cross-Origin Resource Sharing) configurations on the FastAPI side.
// Example React component to interact with the ML prediction endpoint
import React, { useState } from 'react';
const MLPredictor = () => {
const [feature1, setFeature1] = useState('');
const [feature2, setFeature2] = useState('');
const [prediction, setPrediction] = useState(null);
const [error, setError] = useState(null);
const handlePredict = async () => {
try {
// Build the payload from user inputs
const payload = {
feature1: parseFloat(feature1),
feature2: parseFloat(feature2),
};
// Send a POST request to your FastAPI endpoint
const response = await fetch('http://localhost:8000/predict', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(payload)
});
if (!response.ok) {
throw new Error('Network response was not ok');
}
// Parse the JSON response
const result = await response.json();
setPrediction(result.prediction);
} catch (err) {
setError(err.message);
}
};
return (
ML Predictor
setFeature1(e.target.value)}
/>
setFeature2(e.target.value)}
/>
{prediction !== null && (
Prediction: {prediction}
)}
{error && (
Error: {error}
)}
);
};
export default MLPredictor;
// Adding CORS middleware to the FastAPI app
from fastapi.middleware.cors import CORSMiddleware
origins = [
"http://localhost:3000", // React app's default port
// Add more origins if needed
]
app.add\_middleware(
CORSMiddleware,
allow\_origins=origins,
allow\_credentials=True,
allow\_methods=["\*"],
allow\_headers=["\*"],
)
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.Â