Thursday, December 4, 2025

thumbnail

Connecting Flask with React: Building a Full Stack App

 Connecting Flask with React: Building a Full-Stack App


A full-stack application combines a backend (Flask) with a frontend (React). Flask handles data, APIs, and business logic, while React provides an interactive user interface.


Architecture Overview:


React Frontend

   |  HTTP requests (AJAX / Fetch / Axios)

Flask Backend (REST API)

   |  Database access (SQLAlchemy, MongoDB, etc.)

Database (PostgreSQL, MySQL, MongoDB, SQLite)


1. Setting Up the Flask Backend

Step 1: Create a virtual environment

mkdir flask-react-app

cd flask-react-app

python3 -m venv venv

source venv/bin/activate  # Linux/macOS

venv\Scripts\activate     # Windows


Step 2: Install Flask

pip install Flask flask-cors



flask-cors allows cross-origin requests from React during development.


Step 3: Create a basic API

# backend/app.py

from flask import Flask, jsonify

from flask_cors import CORS


app = Flask(__name__)

CORS(app)  # Enable CORS for all routes


@app.route('/api/hello', methods=['GET'])

def hello():

    return jsonify({"message": "Hello from Flask!"})


if __name__ == '__main__':

    app.run(debug=True)



Run Flask:


python backend/app.py



Your API is now available at http://127.0.0.1:5000/api/hello.


2. Setting Up the React Frontend

Step 1: Create a React app

npx create-react-app frontend

cd frontend


Step 2: Install Axios (optional, for API calls)

npm install axios


Step 3: Fetch data from Flask

// frontend/src/App.js

import React, { useEffect, useState } from "react";

import axios from "axios";


function App() {

  const [message, setMessage] = useState("");


  useEffect(() => {

    axios.get("http://127.0.0.1:5000/api/hello")

      .then(response => setMessage(response.data.message))

      .catch(error => console.error(error));

  }, []);


  return (

    <div>

      <h1>Flask + React Full Stack App</h1>

      <p>{message}</p>

    </div>

  );

}


export default App;



Start React:


npm start



React runs at http://localhost:3000 and fetches data from Flask.


3. Connecting Flask and React in Production


In production, you can serve the React frontend through Flask or via a separate web server.


Option A — Serve React with Flask


Build React app:


cd frontend

npm run build



Move the build folder to Flask:


# backend/app.py

from flask import Flask, send_from_directory, jsonify

import os


app = Flask(__name__, static_folder="../frontend/build")


@app.route('/api/hello', methods=['GET'])

def hello():

    return jsonify({"message": "Hello from Flask!"})


@app.route('/', defaults={'path': ''})

@app.route('/<path:path>')

def serve(path):

    if path != "" and os.path.exists(app.static_folder + '/' + path):

        return send_from_directory(app.static_folder, path)

    else:

        return send_from_directory(app.static_folder, 'index.html')


if __name__ == "__main__":

    app.run()



Now, Flask serves both the API and the React app.


Option B — Deploy Separately


React frontend: Hosted on Netlify, Vercel, or S3


Flask backend: Hosted on Heroku, AWS, or GCP


Frontend makes API calls to backend URLs (ensure CORS is enabled).


4. Best Practices


Use environment variables


React: .env file for API base URL


Flask: .env for secrets and DB credentials


Enable CORS only for allowed origins in production:


from flask_cors import CORS

CORS(app, origins=["https://your-frontend.com"])



Error handling: Return proper HTTP status codes from Flask.


JSON-only communication: Always exchange data via JSON, not HTML forms.


Authentication:


Use JWTs or OAuth for secure login across frontend and backend.


Database integration:


Use SQLAlchemy or MongoEngine for Flask to connect to SQL or NoSQL databases.


5. Summary


Flask provides a lightweight, flexible backend API.


React offers a responsive, dynamic frontend.


Communication happens via HTTP requests (Axios, Fetch).


Production can serve React via Flask or separate hosting.


Always follow best practices for CORS, environment variables, and authentication.


With this setup, you can build scalable full-stack applications using Python and JavaScript.

Learn Fullstack Python Training in Hyderabad

Read More

Integrating React with Django: A Full Stack Tutorial

Frontend and Backend Integration in Python

How to Deploy Flask Applications to DigitalOcean

Using Nginx and Gunicorn for Python Web Application Deployment

At Our Quality Thought Training Institute in Hyderabad

Get Directions

Subscribe by Email

Follow Updates Articles from This Blog via Email

No Comments

About

Search This Blog

Powered by Blogger.

Blog Archive