On this page
  1. Web Development & APIs
  2. Contents
  3. JSON REST API with http.server & sqlite3
  4. WSGI Application with wsgiref
  5. URL Encoding & Request Building (urllib)
  6. Safe HTML Rendering (html.escape)

Web Development & APIs

Prev: Popular Application Domains | Up: Popular Application Domains | Next: Data Science & Machine Learning
Rel: http, wsgiref, urllib, json, sqlite3, html
Ref: docs.python.org — http.server | docs.python.org — wsgiref
Tags: #public #python3 #tutorials #domains #web #apis #stdlib


Contents


JSON REST API with http.server & sqlite3

Python's [[stdlib_module/http|http.server]] and [[stdlib_module/sqlite3|sqlite3]] let you build a multi-threaded JSON REST API with zero external dependencies.

from http import HTTPStatus
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import sqlite3
from urllib.parse import urlparse

db = sqlite3.connect(":memory:", check_same_thread=False)
db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL)")

class ApiHandler(BaseHTTPRequestHandler):
    def _send_json(self, status: int, payload: object) -> None:
        body = json.dumps(payload).encode("utf-8")
        self.send_response(status)
        self.send_header("Content-Type", "application/json; charset=utf-8")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def do_GET(self) -> None:
        if urlparse(self.path).path == "/items":
            rows = db.execute("SELECT id, name FROM items").fetchall()
            self._send_json(HTTPStatus.OK, [{"id": r[0], "name": r[1]} for r in rows])
        else:
            self._send_json(HTTPStatus.NOT_FOUND, {"error": "Not found"})

    def do_POST(self) -> None:
        if urlparse(self.path).path != "/items":
            self._send_json(HTTPStatus.NOT_FOUND, {"error": "Not found"})
            return
        length = int(self.headers.get("Content-Length", "0"))
        data = json.loads(self.rfile.read(length))
        cur = db.execute("INSERT INTO items (name) VALUES (?)", (data["name"],))
        db.commit()
        self._send_json(HTTPStatus.CREATED, {"id": cur.lastrowid, "name": data["name"]})

# Start locally with:
# ThreadingHTTPServer(("localhost", 8000), ApiHandler).serve_forever()

WSGI Application with wsgiref

[[stdlib_module/wsgiref|wsgiref]] implements PEP 3333 (WSGI), the standard Python web server/application interface.

import json
from wsgiref.simple_server import make_server

def app(environ, start_response):
    path = environ.get("PATH_INFO", "/")
    if path == "/health":
        body = json.dumps({"status": "ok"}).encode("utf-8")
        start_response("200 OK", [("Content-Type", "application/json")])
        return [body]
    start_response("404 Not Found", [("Content-Type", "text/plain")])
    return [b"Not Found"]

# Run locally with:
# with make_server("localhost", 8000, app) as httpd:
#     httpd.serve_forever()

URL Encoding & Request Building (urllib)

Use [[stdlib_module/urllib|urllib.parse]] and urllib.request.Request to construct query strings, headers, and JSON request payloads safely.

import json
from urllib.parse import urlencode, urlunparse
from urllib.request import Request

query = urlencode({"q": "python stdlib", "page": 1})
endpoint = urlunparse(("https", "docs.python.org", "/3/search.html", "", query, ""))
print(endpoint)

body = json.dumps({"name": "widget"}).encode("utf-8")
req = Request(
    endpoint,
    data=body,
    headers={"Content-Type": "application/json", "Accept": "application/json"},
    method="POST",
)
print(req.get_method(), len(req.data))

Safe HTML Rendering (html.escape)

Escape user-supplied strings with [[stdlib_module/html|html.escape()]] before interpolating into HTML so special characters (<, >, &, ", ') are rendered literally.

import html

raw = 'Ada & "Grace" <3>'
safe_html = f"<p>Hello, {html.escape(raw, quote=True)}</p>"
print(safe_html)

Linked from

Related notes