Skip to content

Backend Integration (Flask <-> React)

The frontend talks to the Flask API through a single base URL and a shared request helper.

Adding a new endpoint

1) Implement the handler in server/api_endpoints/<feature>/handler.py.

2) Register a Flask route in server/app.py.

3) Call it from the frontend using frontend/src/file.js

Example integration flow

This minimal example follows the same shape as the real codebase: app.py routes the request to a feature handler, the handler calls db.py, db.py writes against tables defined in schema.sql, and the response returns to the React frontend.

1) app.py routes to a handler

# server/app.py
from api_endpoints.predictions.handler import CreatePredictionHandler

@app.route("/predict", methods=["POST"])
def predict():
    return CreatePredictionHandler(request)

2) The feature handler calls the api endpoint

# server/api_endpoints/predictions/handler.py
from flask import jsonify
from database.db import insert_prediction

def CreatePredictionHandler(request):
    payload = request.get_json(force=True)
    result = {"label": "positive", "score": 0.93, "input": payload}
    insert_prediction(payload.get("text", ""), result["label"], result["score"])
    return jsonify(result)

3) db.py writes to MySQL

# server/database/db.py
import mysql.connector

def get_db():
    return mysql.connector.connect(
        host="localhost",
        user="root",
        password="password",
        database="anote",
    )

def insert_prediction(input_text, label, score):
    db = get_db()
    cursor = db.cursor()
    cursor.execute(
        "INSERT INTO predictions (input_text, label, score) VALUES (%s, %s, %s)",
        (input_text, label, score),
    )
    db.commit()
    cursor.close()
    db.close()

4) The table exists in schema.sql

CREATE TABLE predictions (
  id INT AUTO_INCREMENT PRIMARY KEY,
  input_text TEXT,
  label VARCHAR(64) NOT NULL,
  score FLOAT NOT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

5) React calls the API and receives the response

const API_ENDPOINT = process.env.REACT_APP_API_ENDPOINT;

async function predict(text) {
  const response = await fetch(`${API_ENDPOINT}/predict`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ text }),
  });
  if (!response.ok) {
    throw new Error("Request failed");
  }
  return response.json();
}