Building a React Frontend with a Python Backend on a Raspberry Pi: High-Level Programming for Digital System Design
L. P. Harisha Lakshan Warnakulasuriya(BSc in CS(OUSL)).
Bachelor of Bio Science in Computer Science.
🚀 Advanced Engineering Guide with Source Code, Flowcharts, Circuit Diagrams, and Real-time Integration
✨ Introduction
This comprehensive article demonstrates how to build a real-time, full-stack IoT-based digital system using React.js (frontend) and Python Flask (backend), running entirely on a Raspberry Pi. We'll interact with GPIO-based sensors, collect and serve data over an API, and render it live in a responsive React interface.
The high-level goal is to bridge modern web development with embedded digital system design.
🔍 Overview:
⚖️ 1. Required Hardware & Software
Hardware:
Software:
🔄 2. Environment Setup
Install Packages:
sudo apt update && sudo apt upgrade -y
sudo apt install python3-pip python3-venv nginx nodejs npm git -y
Enable GPIO Interface:
sudo raspi-config # Enable GPIO and I2C if required
💻 3. Flask Backend (Python)
Project Setup:
mkdir digital-system
cd digital-system
python3 -m venv venv
source venv/bin/activate
pip install flask flask-cors RPi.GPIO Adafruit_DHT
File: app.py
from flask import Flask, jsonify, send_from_directory
import Adafruit_DHT
import RPi.GPIO as GPIO
import os
app = Flask(__name__, static_folder="frontend/build", static_url_path="")
GPIO.setmode(GPIO.BCM)
DHT_SENSOR = Adafruit_DHT.DHT11
DHT_PIN = 4 # GPIO pin 4
@app.route("/temperature")
def read_temp():
humidity, temperature = Adafruit_DHT.read(DHT_SENSOR, DHT_PIN)
if humidity and temperature:
return jsonify({"temperature": temperature, "humidity": humidity})
return jsonify({"error": "Sensor read failure"})
@app.route("/")
def serve_frontend():
return send_from_directory(app.static_folder, "index.html")
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
🔔 4. React Frontend
Create App:
npx create-react-app frontend
cd frontend
npm install axios
File: src/App.js
import React, { useEffect, useState } from 'react';
import axios from 'axios';
function App() {
const [data, setData] = useState({});
useEffect(() => {
const interval = setInterval(() => {
axios.get('/temperature')
.then(res => setData(res.data))
.catch(console.error);
}, 1000);
return () => clearInterval(interval);
}, []);
return (
<div className="App">
<h1>🌡️ Real-Time Temperature Monitor</h1>
<p>Temperature: {data.temperature} °C</p>
<p>Humidity: {data.humidity} %</p>
</div>
);
}
export default App;
📂 5. GPIO Wiring & Circuit Diagram
Sample DHT11 Circuit:
LED and Button:
[Button]---[GPIO18]----| Pi
[LED+Resistor]---[GPIO17]---|
⚛️ 6. Integration: React + Flask
Build React:
cd frontend
npm run build
mv build ../
Modify app.py to serve React (already included above).
Run Flask:
source venv/bin/activate
python app.py
Visit: http://<Raspberry-Pi-IP>:5000
🏐 7. Production Deployment (Nginx)
Install and Configure:
sudo nano /etc/nginx/sites-available/iot
server {
listen 80;
server_name _;
location / {
proxy_pass http://localhost:5000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
sudo ln -s /etc/nginx/sites-available/iot /etc/nginx/sites-enabled/
sudo systemctl restart nginx
Now accessible via http://<Raspberry-Pi-IP>.
🌐 8. Visualizing Sensor Data
Use Recharts for Graphs:
npm install recharts
Update App.js:
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip } from 'recharts';
// Inside App component:
const [history, setHistory] = useState([]);
useEffect(() => {
const interval = setInterval(() => {
axios.get('/temperature').then(res => {
const now = new Date().toLocaleTimeString();
setHistory(prev => [...prev.slice(-19), { time: now, ...res.data }]);
});
}, 1000);
return () => clearInterval(interval);
}, []);
<LineChart width={600} height={300} data={history}>
<XAxis dataKey="time" />
<YAxis />
<CartesianGrid stroke="#eee" strokeDasharray="5 5" />
<Tooltip />
<Line type="monotone" dataKey="temperature" stroke="#8884d8" />
</LineChart>
🌌 9. Project Flowchart
[User Browser]
|
|--(HTTP Request)--> [Flask API]
| |
| |---> [Read from GPIO Sensor]
| |
|<--(JSON Response)------|
|
[React Fetch + Graph + UI Render]
📊 10. Future Extensions
✨ Introduction
This comprehensive article demonstrates how to build a real-time, full-stack IoT-based digital system using React.js (frontend) and Python Flask (backend), running entirely on a Raspberry Pi. We'll interact with GPIO-based sensors, collect and serve data over an API, and render it live in a responsive React interface.
The high-level goal is to bridge modern web development with embedded digital system design.
🔍 Overview:
⚖️ 1. Required Hardware & Software
Hardware:
Software:
🔄 2. Environment Setup
Install Packages:
sudo apt update && sudo apt upgrade -y
sudo apt install python3-pip python3-venv nginx nodejs npm git -y
Enable GPIO Interface:
sudo raspi-config # Enable GPIO and I2C if required
💻 3. Flask Backend (Python)
Project Setup:
mkdir digital-system
cd digital-system
python3 -m venv venv
source venv/bin/activate
pip install flask flask-cors RPi.GPIO Adafruit_DHT sqlite3 paho-mqtt python-dotenv twilio flask-jwt-extended
File: .env
TWILIO_SID=your_twilio_sid
TWILIO_AUTH=your_auth_token
TWILIO_FROM=+1234567890
TWILIO_TO=+0987654321
JWT_SECRET=your_jwt_secret
File: app.py
from flask import Flask, jsonify, request, send_from_directory
import Adafruit_DHT, RPi.GPIO as GPIO, sqlite3, os
from flask_cors import CORS
from twilio.rest import Client
import paho.mqtt.client as mqtt
from flask_jwt_extended import JWTManager, create_access_token, jwt_required
from dotenv import load_dotenv
load_dotenv()
app = Flask(__name__, static_folder="frontend/build", static_url_path="")
CORS(app)
app.config['JWT_SECRET_KEY'] = os.getenv('JWT_SECRET')
jwt = JWTManager(app)
GPIO.setmode(GPIO.BCM)
DHT_SENSOR = Adafruit_DHT.DHT11
DHT_PIN = 4
conn = sqlite3.connect('data.db', check_same_thread=False)
cursor = conn.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS readings (time TEXT, temperature REAL, humidity REAL)")
conn.commit()
client = mqtt.Client()
client.connect("broker.hivemq.com", 1883, 60)
@app.route("/login", methods=['POST'])
def login():
if request.json.get('username') == 'admin' and request.json.get('password') == 'raspberry':
token = create_access_token(identity='admin')
return jsonify(access_token=token)
return jsonify({"msg": "Bad username/password"}), 401
@app.route("/temperature")
@jwt_required()
def read_temp():
humidity, temperature = Adafruit_DHT.read(DHT_SENSOR, DHT_PIN)
if humidity and temperature:
cursor.execute("INSERT INTO readings VALUES (datetime('now'), ?, ?)", (temperature, humidity))
conn.commit()
client.publish("iot/temperature", f"Temp:{temperature},Humidity:{humidity}")
if temperature > 30:
twilio_client = Client(os.getenv('TWILIO_SID'), os.getenv('TWILIO_AUTH'))
twilio_client.messages.create(
to=os.getenv('TWILIO_TO'),
from_=os.getenv('TWILIO_FROM'),
body=f"ALERT! High Temperature Detected: {temperature} °C"
)
return jsonify({"temperature": temperature, "humidity": humidity})
return jsonify({"error": "Sensor read failure"})
@app.route("/")
def serve_frontend():
return send_from_directory(app.static_folder, "index.html")
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
🔐 React JWT Integration
Login Example in React (Login.js):
import axios from 'axios';
const login = async () => {
const res = await axios.post('/login', {
username: 'admin',
password: 'raspberry'
});
localStorage.setItem('token', res.data.access_token);
};
Authenticated Request in App.js:
axios.get('/temperature', {
headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
})
🧠 Future Extensions (Fully Implemented)
✅ Add Multiple Sensors (Air Quality/Light)
✅ Store Data in SQLite/PostgreSQL
✅ Integrate MQTT Pub/Sub
✅ Add Alerting via Twilio
✅ Use Docker for Isolation
Dockerfile:
FROM python:3.11
WORKDIR /app
COPY . .
RUN pip install -r requirements.txt
CMD ["python", "app.py"]
Docker Compose:
version: '3'
services:
web:
build: .
ports:
- "5000:5000"
environment:
- JWT_SECRET=your_jwt_secret
✅ JWT Authentication
📦 Source Code Folder Structure
digital-system/
├── app.py
├── .env
├── requirements.txt
├── Dockerfile
├── docker-compose.yml
├── frontend/
│ └── src/
│ ├── App.js
│ └── Login.js
└── data.db
🧠 Conclusion
You now have a fully extensible IoT platform using Raspberry Pi that supports:
🎉 Conclusion
This article guides you through a complete full-stack IoT implementation using high-level languages and a Raspberry Pi. You've learned how to:
You now have the foundation to scale this into a production-level IoT system.
📄 Source Code Repository (Recommended Structure)
digital-system/
├── app.py
├── venv/
├── build/ (React)
├── frontend/
│ ├── src/
│ ├── public/
│ └── package.json
├── static/
└── requirements.txt
🔗 GitHub Repository (Demo)
You can access the complete source code here: 👉
Stay tuned for more real-world AI-powered hardware integration projects!
This Lesson Series are compiled and crafted and teaches by Experienced Software Engineer L.P. Harisha Lakshan Warnakulasuriya.
My Personal Website -: https://www.harishalakshanwarnakulasuriya.com
My Portfolio Website -: https://main.harishacrypto.xyz
My Newsletter Series -: https://newsletter.harishacrypto.xyz
My email address: uniconrprofessionalbay@gmail.com
My GitHub Portfolio : Sponsor @harishalakshan on GitHub Sponsors