/web-to-ai-ml-integrations

React Frontend with Python Backend ML Integration

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

Book a free  consultation
4.9
Clutch rating 🌟
600+
Happy partners
17+
Countries served
190+
Team members
Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

React Frontend with Python Backend ML Integration

 

Designing the Python Backend API with ML Integration

 
  • Choose a lightweight web framework: For Python, FastAPI is perfect due to its asynchronous capabilities and automatic documentation generation using Swagger. This allows the React frontend to easily test the endpoints.
  • Implement ML functionality: Load your pre-trained ML model (using libraries such as scikit-learn, TensorFlow, or PyTorch) and create functions that take input, perform processing, and return predictions.
  • Define data schemas: Use Pydantic models in FastAPI to define input and output schemas ensuring data consistency and validation.

// 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)
  • Note: The above code sets up an endpoint at /predict that accepts a JSON payload, validates it against the PredictionRequest model, processes it through your ML model, and returns a prediction.

 

Connecting the React Frontend to the Python ML API

 
  • Setting up communication: In React, use the 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.
  • Handling responses: Process the JSON responses from the Python backend and integrate them into your component’s state for rendering or further processing.

// 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;
  • Explanation: The React component creates form inputs for two features and a button that triggers the prediction. On clicking the button, it sends the user inputs to the Python API endpoint, receives the prediction, and displays it. Error handling is embedded to catch any network or processing issues.

 

Ensuring Smooth API Integration between React and Python

 
  • CORS Configuration in Python: When the React app (often running on a different port) makes a request, you must allow cross-origin requests. FastAPI has middleware to enable CORS.

// 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=["\*"],
)
  • Data Serialization: Both the Python backend and React frontend need to agree on the format of data passed around. Utilizing JSON is standard as both environments can handle it easily.
  • Error Logging and Debugging: Implement logging on both sides to record interactions. Python’s logging module and browser console logs are invaluable for debugging mismatches in data exchange.

 

Deployment Considerations for Production

 
  • Securing Endpoints: Ensure your API endpoints are secured using authentication (for example, JWT tokens) if sensitive data is involved, and validate inputs on both server and client sides to prevent malicious inputs.
  • Asynchronous Processing: For intensive ML tasks, consider asynchronous job queues such as Celery with FastAPI, so the UI remains responsive while tasks process in the background.
  • Containerization: Deployment may be streamlined using Docker. Create separate containers for your Python API and React app, then use tools like Docker Compose to orchestrate them.
  • Monitoring: Utilize monitoring tools to observe performance, API latency, and error rates to ensure a smooth user experience.

 

Final Integration Testing

 
  • Test End-to-End: Once integrated, simulate real user interactions through integrated testing frameworks like Cypress for React and API testing libraries like pytest for Python.
  • Validate Data Flow: Confirm that user inputs flow correctly from the React frontend to the Python backend, the ML model processes them accurately, and the output is properly reflected in the UI.
  • Handle Edge Cases: Test scenarios where the user provides unexpected input values, and ensure both the Python backend and React frontend handle these gracefully.


Recognized by the best

Trusted by 600+ businesses globally

From startups to enterprises and everything in between, see for yourself our incredible impact.

RapidDev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with.

They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

Arkady
CPO, Praction
Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost.

He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Donald Muir
Co-Founder, Arc
RapidDev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space.

They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Mat Westergreen-Thorne
Co-CEO, Grantify
RapidDev is an excellent developer for custom-code solutions.

We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Emmanuel Brown
Co-Founder, Church Real Estate Marketplace
Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 

This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Samantha Fekete
Production Manager, Media Production Company
The pSEO strategy executed by RapidDev is clearly driving meaningful results.

Working with RapidDev has delivered measurable, year-over-year growth. Comparing the same period, clicks increased by 129%, impressions grew by 196%, and average position improved by 14.6%. Most importantly, qualified contact form submissions rose 350%, excluding spam.

Appreciation as well to Matt Graham for championing the collaboration!

Michael W. Hammond
Principal Owner, OCD Tech

We put the rapid in RapidDev

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.Â