Raspberry Pi Simple Web Server
Flask lets you turn a Raspberry Pi into a lightweight web server that can display sensor data or control GPIO pins from any browser on the network.
Why Run a Web Server on a Pi?
A Raspberry Pi with Flask installed becomes a small, self-contained web server: no separate hosting account or internet connection required, just the Pi and devices on the same local network. This is a popular way to build a dashboard for sensor readings, a page with buttons that switch a relay or LED on and off, or a simple API that another program can query — all served directly from the same board that's wired to your hardware.
- Control LEDs, relays, or motors from a button on your phone's browser
- Display live sensor readings on a page anyone on the network can open
- Flask is lightweight — a working server can be just a few lines of code
- Combines naturally with gpiozero for hardware control and smbus2/spidev for sensor data
- A solid stepping stone toward home automation dashboards or small IoT APIs
Installing Flask
Flask isn't part of the Python standard library, so install it first. It's good practice to use a virtual environment: run python3 -m venv venv, activate it with source venv/bin/activate, then install Flask with pip install flask. You can also install it system-wide with sudo apt install -y python3-flask, though a virtual environment keeps project dependencies tidy.
A Minimal Flask App
A Flask app starts with a single Flask instance. You attach URL paths to Python functions using the @app.route() decorator — whatever that function returns becomes the page content sent to the browser. Calling app.run() starts a built-in development server; by default it only listens on 127.0.0.1 (the Pi itself), so to make it reachable from your phone or laptop you must pass host="0.0.0.0", which tells Flask to listen on every network interface on the Pi.
Example
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Hello from the Raspberry Pi!"
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000)Run the script on the Pi with python3 app.py, then find the Pi's IP address by running hostname -I in another terminal (or use raspberrypi.local if your network supports mDNS/Avahi, which Raspberry Pi OS enables by default). On a phone, laptop, or any other device connected to the same Wi-Fi or Ethernet network, open a browser and visit http://<pi-ip-address>:5000/ — you should see the greeting from your Flask route.
Controlling GPIO from a Web Route
Example
from flask import Flask
from gpiozero import LED
app = Flask(__name__)
led = LED(17) # LED wired to GPIO17
@app.route("/led/on")
def led_on():
led.on()
return "LED is ON"
@app.route("/led/off")
def led_off():
led.off()
return "LED is OFF"
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000)