Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 37 ยท Networking and Servers

Serving a Web Page and JSON API from the Pi

Turn your Pi into a web server: serve sensor readings as HTML and JSON with Flask or the standard library, bind addresses and ports, and run it behind nginx.

A Pi that serves a web page is a dashboard you can open from any phone on your network. It can show the temperature of a room, a button that switches a lamp, or a JSON feed other programs read. The Pi is more than powerful enough: a Pi Zero can handle a handful of requests per second, and a Pi 4 or 5 serves a small site comfortably.

Two things matter beyond the code: how the server binds to an address and port, and how it runs permanently (see systemd services). Real Flask is not available on this website, so Flask code is read-only. The runnable stand-ins implement the same routing and JSON ideas in plain Python so you can test the logic.

The smallest server: Flask

Flask is a popular micro-framework. Install it with sudo apt install python3-flask, then save this as app.py:

Python
from flask import Flask, jsonify

app = Flask(__name__)

def read_temperature():
    with open("/sys/class/thermal/thermal_zone0/temp") as f:
        return int(f.read()) / 1000

@app.route("/")
def home():
    return f"<h1>Pi dashboard</h1><p>CPU: {read_temperature():.1f} C</p>"

@app.route("/api/temperature")
def api_temperature():
    return jsonify(cpu_c=read_temperature())

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000)

Run python3 app.py and browse to http://greenhouse.local:5000/. Two ideas here:

  • @app.route maps a URL path to a function. The return value is the response body.
  • host="0.0.0.0" listens on all interfaces, so other devices can connect. The default 127.0.0.1 listens only on the Pi itself, which is safer for testing but unreachable from your laptop.

Flask's built-in server is meant for development. For a long-running site, use gunicorn behind nginx, or at least run it as a service.

No framework: the standard library

You do not need to install anything. http.server ships with Python, and this is enough for small tools:

Python
from http.server import BaseHTTPRequestHandler, HTTPServer
import json

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == "/api/temperature":
            body = json.dumps({"cpu_c": 48.3}).encode()
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
        else:
            body = b"not found"
            self.send_response(404)
        self.end_headers()
        self.wfile.write(body)

HTTPServer(("0.0.0.0", 8000), Handler).serve_forever()

Testing routing logic here

A server is a function from a request (method and path) to a response (status, headers, body). Because this part is pure logic, you can test it without any network. The stand-in below mimics a Flask-style router with decorators and returns JSON.

Python Stand-in: a tiny router with JSON responses

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Reading query strings and POST forms

A button that toggles a lamp is a POST request. Handlers read data from the query string (?pin=17&state=on) or from a form body. Always validate: never feed user input straight to GPIO or a shell.

Python Stand-in: validate a request before acting

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

An allow-list of pins, as above, is the safe pattern. Add authentication (a token in a header, or HTTP basic auth through nginx) before anything controls a real device.

Putting nginx in front

A production setup has three layers:

flowchart LR
    A["Browser"] --> B["nginx :80"]
    B --> C["gunicorn :8000"]
    C --> D["Flask app"]
    D --> E["Sensor / SQLite"]

nginx handles connections and static files; gunicorn runs the Python app.

Terminal
sudo apt install nginx gunicorn
gunicorn --bind 127.0.0.1:8000 app:app    # app = file app.py, object app

A minimal nginx site (/etc/nginx/sites-available/pi) forwards requests:

TEXT
server {
    listen 80;
    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host $host;
    }
}

Enable it with a symlink in sites-enabled, test with sudo nginx -t, and reload with sudo systemctl reload nginx. Gunicorn now listens only on loopback, which is the safe default.

Serving live data without reloading

Browsers can poll the JSON route every few seconds. A few lines of JavaScript on the page do it:

HTML
<p id="t">...</p>
<script>
  setInterval(async () => {
    const r = await fetch("/api/temperature");
    document.getElementById("t").textContent = (await r.json()).cpu_c + " C";
  }, 5000);
</script>

For truly instant updates, use WebSockets or server-sent events, but polling every few seconds is fine for sensors.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does host="0.0.0.0" do in app.run?

    0.0.0.0 means every interface, so other devices can reach the server.
  2. 2. Why use an allow-list of GPIO pins in a web handler?

    Validating input stops a crafted request from touching pins it should not.
  3. 3. What is gunicorn's role behind nginx?

    gunicorn is the application server; nginx is the front-facing proxy.
  4. 4. Which response code means the path does not exist?

    404 is Not Found.

Summary

  • A web server maps requests to functions; Flask uses @app.route, the standard library uses http.server.
  • host="0.0.0.0" exposes the app on the network; 127.0.0.1 keeps it local.
  • Return HTML for people and JSON for programs; validate every input.
  • For permanent use run gunicorn as a service behind nginx.
  • Poll a JSON route from the page for live sensor values.

Next: MQTT: Messaging Between Devices