Claude Code for http.server: Python HTTP Development Server — Claude Skills 360 Blog
Blog / AI / Claude Code for http.server: Python HTTP Development Server
AI

Claude Code for http.server: Python HTTP Development Server

Published: November 19, 2028
Read time: 5 min read
By: Claude Skills 360

Python’s http.server module provides HTTP server classes for serving static files and building custom request handlers. from http.server import HTTPServer, BaseHTTPRequestHandler, SimpleHTTPRequestHandler, ThreadingHTTPServer. Create: HTTPServer((host, port), HandlerClass) — single-threaded; ThreadingHTTPServer((host, port), HandlerClass) — thread-per-request. Handler lifecycle: override do_GET, do_POST, do_PUT, do_DELETE, etc. in a BaseHTTPRequestHandler subclass — each method is called for the matching HTTP verb. Request data: self.command → method string; self.path → URL path + query; self.headershttp.client.HTTPMessage (dict-like); self.rfile.read(content_length) → POST body bytes. Response: self.send_response(200), self.send_header("Content-Type", "application/json"), self.end_headers(), self.wfile.write(body_bytes). Static serving: SimpleHTTPRequestHandler serves files from the current directory with directory listings; pass directory= kwarg to serve from a different root. CLI: python -m http.server 8080 — serves current directory. TLS: wrap with ssl.wrap_socket or use ssl.SSLContext. Claude Code generates development servers, JSON REST handlers, file upload endpoints, and test HTTP fixtures.

CLAUDE.md for http.server

## http.server Stack
- Stdlib: from http.server import HTTPServer, BaseHTTPRequestHandler
-                                 ThreadingHTTPServer, SimpleHTTPRequestHandler
- Handler: class MyHandler(BaseHTTPRequestHandler):
-              def do_GET(self):
-                  self.send_response(200)
-                  self.send_header("Content-Type", "application/json")
-                  self.end_headers()
-                  self.wfile.write(b'{"ok":true}')
- Serve:   with HTTPServer(("", 8080), MyHandler) as s: s.serve_forever()
- Static:  python -m http.server 8080 --directory /path/to/files

http.server Custom Handler Pipeline

# app/httputil.py — JSON handler, routing, static+API, upload, test fixture
from __future__ import annotations

import io
import json
import mimetypes
import os
import socket
import socketserver
import threading
import urllib.parse
from http.server import (BaseHTTPRequestHandler, HTTPServer,
                         SimpleHTTPRequestHandler, ThreadingHTTPServer)
from pathlib import Path


# ─────────────────────────────────────────────────────────────────────────────
# 1. JSON REST handler
# ─────────────────────────────────────────────────────────────────────────────

class JsonHTTPHandler(BaseHTTPRequestHandler):
    """
    Base handler for JSON REST APIs.
    Override handle_get(path, params) → dict and handle_post(path, body) → dict.
    """

    log_requests: bool = False   # class-level config

    def log_message(self, format: str, *args) -> None:
        if self.log_requests:
            super().log_message(format, *args)

    def _read_json_body(self) -> object:
        length = int(self.headers.get("Content-Length", 0))
        raw = self.rfile.read(length)
        if not raw:
            return None
        try:
            return json.loads(raw.decode("utf-8"))
        except json.JSONDecodeError:
            return None

    def _send_json(self, data: object, status: int = 200) -> None:
        body = json.dumps(data, ensure_ascii=False).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 _send_error_json(self, status: int, message: str) -> None:
        self._send_json({"error": message}, status=status)

    def _parse_path(self) -> tuple[str, dict[str, list[str]]]:
        parsed = urllib.parse.urlparse(self.path)
        params = urllib.parse.parse_qs(parsed.query)
        return parsed.path, params

    def do_GET(self) -> None:
        path, params = self._parse_path()
        try:
            result = self.handle_get(path, params)
            self._send_json(result)
        except NotImplementedError:
            self._send_error_json(404, f"GET {path} not handled")
        except Exception as e:
            self._send_error_json(500, str(e))

    def do_POST(self) -> None:
        path, _ = self._parse_path()
        body = self._read_json_body()
        try:
            result = self.handle_post(path, body)
            self._send_json(result, status=201)
        except NotImplementedError:
            self._send_error_json(404, f"POST {path} not handled")
        except Exception as e:
            self._send_error_json(500, str(e))

    def handle_get(self, path: str, params: dict) -> object:
        raise NotImplementedError

    def handle_post(self, path: str, body: object) -> object:
        raise NotImplementedError


# ─────────────────────────────────────────────────────────────────────────────
# 2. Router-based handler
# ─────────────────────────────────────────────────────────────────────────────

Route = tuple[str, str]   # (method, path)

class RouterHandler(JsonHTTPHandler):
    """JSON handler with a simple dict-based route table."""

    routes: dict[Route, "callable"] = {}

    @classmethod
    def route(cls, method: str, path: str):
        """Decorator: @RouterHandler.route("GET", "/hello")"""
        def decorator(fn):
            cls.routes[(method.upper(), path)] = fn
            return fn
        return decorator

    def handle_get(self, path: str, params: dict) -> object:
        fn = self.routes.get(("GET", path))
        if fn is None:
            raise NotImplementedError
        return fn(self, path, params)

    def handle_post(self, path: str, body: object) -> object:
        fn = self.routes.get(("POST", path))
        if fn is None:
            raise NotImplementedError
        return fn(self, path, body)


# ─────────────────────────────────────────────────────────────────────────────
# 3. Static + API hybrid handler
# ─────────────────────────────────────────────────────────────────────────────

def make_hybrid_handler(static_dir: str | Path, api_prefix: str = "/api"):
    """
    Create a handler class that serves static files for non-API paths
    and dispatches JSON requests for paths starting with api_prefix.

    Example:
        HandlerClass = make_hybrid_handler("/var/www/public", api_prefix="/api")
        server = HTTPServer(("", 8080), HandlerClass)
    """
    static_root = str(static_dir)
    prefix = api_prefix

    class HybridHandler(SimpleHTTPRequestHandler):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, directory=static_root, **kwargs)

        def log_message(self, fmt, *args):
            pass

        def do_GET(self):
            if self.path.startswith(prefix):
                self._handle_api()
            else:
                super().do_GET()

        def _handle_api(self):
            path = self.path[len(prefix):]
            data = {"path": path, "method": "GET", "api": True}
            body = json.dumps(data).encode()
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)

    return HybridHandler


# ─────────────────────────────────────────────────────────────────────────────
# 4. Test fixture: ephemeral server
# ─────────────────────────────────────────────────────────────────────────────

class EphemeralServer:
    """
    Context manager for an ephemeral HTTP server on a random free port.
    Useful for test fixtures.

    Example:
        handler_cls.routes = {}  # reset
        @handler_cls.route("GET", "/ping")
        def ping(self, path, params): return {"pong": True}

        with EphemeralServer(handler_cls) as srv:
            import urllib.request
            resp = urllib.request.urlopen(f"http://127.0.0.1:{srv.port}/ping")
            print(json.loads(resp.read()))
    """

    def __init__(self, handler_class, threaded: bool = True):
        self.handler_class = handler_class
        self.threaded = threaded
        self.server: HTTPServer | None = None
        self.port: int | None = None
        self._thread: threading.Thread | None = None

    def __enter__(self) -> "EphemeralServer":
        with socket.socket() as s:
            s.bind(("127.0.0.1", 0))
            self.port = s.getsockname()[1]
        cls = ThreadingHTTPServer if self.threaded else HTTPServer
        self.server = cls(("127.0.0.1", self.port), self.handler_class)
        self.server.allow_reuse_address = True
        self._thread = threading.Thread(
            target=self.server.serve_forever, daemon=True
        )
        self._thread.start()
        return self

    def __exit__(self, *_):
        if self.server:
            self.server.shutdown()
            self.server.server_close()

    @property
    def base_url(self) -> str:
        return f"http://127.0.0.1:{self.port}"


# ─────────────────────────────────────────────────────────────────────────────
# Demo
# ─────────────────────────────────────────────────────────────────────────────

if __name__ == "__main__":
    import tempfile
    import urllib.request
    print("=== http.server demo ===")

    # ── Set up RouterHandler routes ───────────────────────────────────────────
    RouterHandler.routes = {}

    @RouterHandler.route("GET", "/")
    def index(self, path, params):
        return {"message": "hello from http.server", "path": path}

    @RouterHandler.route("GET", "/echo")
    def echo(self, path, params):
        name = params.get("name", ["world"])[0]
        return {"echo": name}

    @RouterHandler.route("POST", "/add")
    def add(self, path, body):
        a = body.get("a", 0) if body else 0
        b = body.get("b", 0) if body else 0
        return {"result": a + b}

    # ── EphemeralServer test ──────────────────────────────────────────────────
    with EphemeralServer(RouterHandler) as srv:
        print(f"\n  Server on {srv.base_url}")

        # GET /
        resp = urllib.request.urlopen(f"{srv.base_url}/")
        data = json.loads(resp.read())
        print(f"\n--- GET / ---")
        print(f"  {data}")

        # GET /echo?name=cmath
        resp = urllib.request.urlopen(f"{srv.base_url}/echo?name=stdlib")
        data = json.loads(resp.read())
        print(f"\n--- GET /echo?name=stdlib ---")
        print(f"  {data}")

        # POST /add
        body = json.dumps({"a": 40, "b": 2}).encode()
        req = urllib.request.Request(
            f"{srv.base_url}/add",
            data=body,
            headers={"Content-Type": "application/json"},
            method="POST",
        )
        resp = urllib.request.urlopen(req)
        data = json.loads(resp.read())
        print(f"\n--- POST /add {{a:40, b:2}} ---")
        print(f"  {data}")

        # 404
        try:
            urllib.request.urlopen(f"{srv.base_url}/missing")
        except urllib.error.HTTPError as e:
            err = json.loads(e.read())
            print(f"\n--- GET /missing ---")
            print(f"  status={e.code}  {err}")

    # ── Hybrid static+API server (demo only, not blocking) ────────────────────
    print("\n--- make_hybrid_handler ---")
    with tempfile.TemporaryDirectory() as tmp:
        (Path(tmp) / "index.html").write_text(
            "<html><body>Hello</body></html>"
        )
        HandlerClass = make_hybrid_handler(tmp)
        print(f"  Created hybrid handler for static dir {tmp}")
        print(f"  API prefix: /api")

    print("\n=== done ===")

For the Flask / FastAPI (PyPI) alternatives — Flask’s @app.route("/path") and FastAPI’s @app.get("/path") provide automatic request parsing, response serialization, middleware, CORS, authentication, OpenAPI docs, and production WSGI/ASGI compatibility — use Flask or FastAPI for any production web service; use http.server for local development servers, zero-dependency test fixtures in unit tests, ad hoc file serving with python -m http.server, and embedded control planes in tools that cannot add third-party packages. For the waitress / gunicorn (PyPI) alternatives — production-grade WSGI servers that serve Flask/FastAPI apps with worker pools, graceful restarts, and request queuing — never use http.server.HTTPServer or ThreadingHTTPServer in production; they have no backpressure, no graceful shutdown, and no path sanitization hardening — development and testing use only. The Claude Skills 360 bundle includes http.server skill sets covering JsonHTTPHandler with _send_json()/_read_json_body()/do_GET()/do_POST(), RouterHandler with @route decorator dispatch, make_hybrid_handler() static+API factory, and EphemeralServer context manager for test fixtures. Start with the free tier to try HTTP server patterns and http.server pipeline code generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free