/web-to-ai-ml-integrations

Build Recommendation System with Flask and React

Build a recommendation system with Flask & React—follow our simple step-by-step guide for quick integration and deployment.

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

Build Recommendation System with Flask and React

 

Building the Flask API with Integrated Recommendation Logic

 
  • Flask Overview: Flask is a lightweight Python web framework ideal for creating RESTful APIs. The API will serve recommendations computed by the recommendation engine.
  • Recommendation Engine: Build an engine using techniques such as collaborative filtering or content-based filtering. For example, compute similarity between users or items to generate recommendations. The algorithm details (e.g., cosine similarity or Pearson correlation) are implemented in Python.
  • Data Source: Use a database (SQL or NoSQL) or static data files as the data store that holds user interactions, ratings, or item features needed for the recommendation calculations.
  • API Endpoints: Expose endpoints (routes) via Flask that allow React to request recommendations based on, for instance, a user ID. The endpoint performs the recommendation logic and returns a JSON response with a list of recommended items.

// Import Flask and required modules
from flask import Flask, request, jsonify
import numpy as np  // Used for mathematical operations
import pandas as pd // For data manipulation

app = Flask(**name**)

# Dummy dataset for demonstration
data = {
    'user\_id': [1, 1, 2, 2, 3],
    'item\_id': [101, 102, 101, 103, 104],
    'rating': [5, 3, 4, 2, 5]
}
ratings\_df = pd.DataFrame(data)

def compute_recommendations(user_id):
    // Simple content-based filter using average ratings (advanced logic would be used in real projects)
    user_ratings = ratings_df[ratings_df['user_id'] == user\_id]
    if user\_ratings.empty:
        return []
    user_mean = user_ratings['rating'].mean()
    
    // Return items where rating is above user's mean rating
    recommended = ratings_df[ratings_df['rating'] > user_mean]['item_id'].unique().tolist()
    return recommended

@app.route('/api/recommendations', methods=['GET'])
def recommendations():
    // Get user_id from query parameters e.g., /api/recommendations?user_id=1
    user_id = request.args.get('user_id', type=int)
    if not user\_id:
        return jsonify({'error': 'User id missing'}), 400
    rec_items = compute_recommendations(user\_id)
    return jsonify({'user_id': user_id, 'recommendations': rec\_items})

if **name** == '**main**':
    app.run(debug=True)

 

Creating the React Frontend to Display Recommendations

 
  • React Overview: React is a JavaScript library for building user interfaces. In this guide, we focus on creating a component that calls the Flask API, receives recommendation data, and displays it.
  • Fetching Data: Use the built-in fetch API or libraries like axios to retrieve data from the Flask endpoint.
  • State Management: Use React's state to store recommendations and display updates each time new data is fetched.
  • UI Feedback: Provide error handling and loader states during data fetching to enhance user experience.

// Import React and hooks for managing state and lifecycle events
import React, { useState, useEffect } from 'react';

const RecommendationComponent = () => {
  const [recommendations, setRecommendations] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const userId = 1; // Demo user id. In real applications, this would be dynamically set.

  useEffect(() => {
    // Fetch recommendations from Flask API
    fetch(`http://localhost:5000/api/recommendations?user_id=${userId}`)
      .then(response => {
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        return response.json();
      })
      .then(data => {
        setRecommendations(data.recommendations);
        setLoading(false);
      })
      .catch(error => {
        setError(error.toString());
        setLoading(false);
      });
  }, [userId]);

  if (loading) return 
Loading recommendations...
; if (error) return
Error: {error}
; return (

Your Recommendations

    {recommendations.map(item => (
  • Item ID: {item}
  • ))}
); }; export default RecommendationComponent;

 

Integrating Flask and React

 
  • CORS Handling: When integrating a Flask API with a React frontend hosted on a different domain or port, utilize the Flask-CORS module to handle Cross-Origin Resource Sharing (CORS) issues. This enables the React app to make HTTP requests to the Flask server without errors.
  • Flask-CORS Implementation: Add the Flask-CORS configuration to the Flask application. This is straightforward:

// In your Flask app code, add the following:
from flask\_cors import CORS
CORS(app) // Enable CORS for all routes
  • Deployment: Once the app is tested locally, deploy the Flask backend on a server (like Heroku, AWS, or DigitalOcean) and serve the React application (using platforms like Vercel or Netlify). Make sure that the React app's fetch URL points to the correct, publicly accessible Flask endpoint.
  • Security and Scaling: For production, ensure secure communication (use HTTPS), proper error handling, and possibly caching of recommendations using tools like Redis for scaling.

 

Enhancing the Recommendation Engine

 
  • Algorithm Optimization: Instead of a simple average-based filter, consider implementing collaborative filtering. This can involve generating a user-item matrix from rating data and then calculating similarity scores (e.g., cosine similarity) to suggest items liked by similar users.
  • Offline Processing: For heavy computations, run the recommendation model as a batch job and store the precomputed recommendations. Use a scheduled task (cron job) or background processing with Celery in Flask.
  • Model Updates: Monitor feedback from users to adjust the recommendation algorithm. Machine learning models can be retrained periodically based on new data and user interactions.
  • Data Preprocessing: When dealing with large data sets, preprocess and clean the data using pandas or PySpark, ensuring that the data fed into the recommendation engine is consistent and accurate.

import numpy as np
import pandas as pd
from sklearn.metrics.pairwise import cosine\_similarity

// Build user-item matrix
def build_user_item_matrix(ratings_df):
    // Pivot table to build matrix; rows are users and columns are items
    return ratings_df.pivot_table(index='user_id', columns='item_id', values='rating').fillna(0)

// Compute cosine similarity between users
def user_based_collaborative_filtering(user_id, ratings\_df):
    user_item_matrix = build_user_item_matrix(ratings_df)
    similarity_matrix = cosine_similarity(user_item_matrix)
    similarity_df = pd.DataFrame(similarity_matrix, 
                                 index=user_item_matrix.index, 
                                 columns=user_item_matrix.index)
    // Find top similar users
    similar_users = similarity_df[user_id].sort_values(ascending=False)[1:4]
    // Fetch items from similar users
    recommended_items = ratings_df[ratings_df['user_id'].isin(similar_users.index)]['item_id'].unique().tolist()
    return recommended\_items
  • Integration: Replace the simple recommendation function in the Flask API with more sophisticated methods like the one above. Always ensure that the recommendation logic is efficient and scalable.

 

Testing and Debugging the System

 
  • Flask Endpoint Testing: Use tools like Postman or curl to send requests to the Flask endpoints. Validate the JSON responses to ensure they are correctly formatted and contain the expected data.
  • React Component Testing: Use React testing libraries such as Jest and React Testing Library to simulate API calls and validate that the recommendations are rendered as expected.
  • End-to-End Testing: Consider using Cypress or Selenium to simulate a user’s journey from the React front end fetching data to receiving recommendations from the Flask backend.
  • Error Logging: Implement logging in both Flask (using Python’s logging module) and React (using browser console or external services) so that errors can be diagnosed quickly.


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.