Advanced · Web & APIs · Packages: standard library only

Project 21: Local REST API with http.server

Create a JSON REST API for notes (create, read, update, delete) using only http.server, with validation, proper status codes and a built-in self-test client.

What you will learn

Prerequisites

Packages and installation

Packages: standard library only.

Project structure

Folder layout
notes_api/
  main.py

Step-by-step build

  1. Plan the endpoints. GET /notes, GET /notes/<id>, POST /notes, PUT /notes/<id>, DELETE /notes/<id>.
  2. Store data in memory. Use a dictionary NOTES, a counter NEXT_ID and a Lock so threads do not clash.
  3. Write helpers. send_json() sets status, headers and the body. read_json() reads Content-Length bytes and decodes JSON.
  4. Add validation. validate() returns an error message or None. Use it before creating or changing a note.
  5. Implement the routes. Each do_METHOD method matches the path with a regular expression and answers with a JSON status.
  6. Write a client helper. call() uses http.client to send a request and print the status and body.
  7. Start on port 0. Binding to port 0 lets the OS pick a free port. Read it from server.server_address.
  8. Shut down cleanly. Call shutdown(), then server_close(), then join the thread in a finally block.

Complete source code

main.py
"""Local REST API built with http.server: a small "notes" service with a self-test."""
import http.client
import json
import re
import sys
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

# In-memory "database". A lock keeps it safe when requests run in threads.
NOTES = {}
NEXT_ID = 1
LOCK = threading.Lock()
NOTE_PATH = re.compile(r"^/notes/(\d+)$")   # matches /notes/<number>


def validate(data, partial=False):
    """Return an error message for bad note data, or None when it is fine."""
    if not isinstance(data, dict):
        return "body must be a JSON object"
    if not partial and "title" not in data:
        return "title is required"
    if "title" in data and (not isinstance(data["title"], str) or not data["title"].strip()):
        return "title must be a non-empty string"
    if "done" in data and not isinstance(data["done"], bool):
        return "done must be true or false"
    return None


class NotesHandler(BaseHTTPRequestHandler):
    server_version = "NotesAPI/1.0"

    # --- small helpers ---------------------------------------------------
    def send_json(self, status, payload):
        body = json.dumps(payload).encode("utf-8")
        self.send_response(status)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def read_json(self):
        """Read and decode the request body. Returns (data, error)."""
        length = int(self.headers.get("Content-Length", 0))
        raw = self.rfile.read(length)
        try:
            return json.loads(raw.decode("utf-8")), None
        except (ValueError, UnicodeDecodeError):
            return None, "invalid JSON"

    def log_message(self, fmt, *args):
        pass   # keep the console quiet so the demo output stays clean

    # --- routes ----------------------------------------------------------
    def do_GET(self):
        if self.path == "/notes":
            with LOCK:
                self.send_json(200, list(NOTES.values()))
            return
        match = NOTE_PATH.match(self.path)
        if match:
            note = NOTES.get(int(match.group(1)))
            if note:
                self.send_json(200, note)
            else:
                self.send_json(404, {"error": "note not found"})
            return
        self.send_json(404, {"error": "unknown path"})

    def do_POST(self):
        global NEXT_ID
        if self.path != "/notes":
            return self.send_json(404, {"error": "unknown path"})
        data, error = self.read_json()
        error = error or validate(data)
        if error:
            return self.send_json(400, {"error": error})
        with LOCK:
            note = {"id": NEXT_ID, "title": data["title"].strip(), "done": bool(data.get("done", False))}
            NOTES[NEXT_ID] = note
            NEXT_ID += 1
        self.send_json(201, note)

    def do_PUT(self):
        match = NOTE_PATH.match(self.path)
        if not match:
            return self.send_json(404, {"error": "unknown path"})
        data, error = self.read_json()
        error = error or validate(data, partial=True)
        if error:
            return self.send_json(400, {"error": error})
        with LOCK:
            note = NOTES.get(int(match.group(1)))
            if note is None:
                return self.send_json(404, {"error": "note not found"})
            note.update({k: data[k] for k in ("title", "done") if k in data})
        self.send_json(200, note)

    def do_PATCH(self):
        # PATCH is not supported: answer with the proper 405 status code.
        self.send_json(405, {"error": "method not allowed"})

    def do_DELETE(self):
        match = NOTE_PATH.match(self.path)
        if not match:
            return self.send_json(404, {"error": "unknown path"})
        with LOCK:
            removed = NOTES.pop(int(match.group(1)), None)
        if removed is None:
            self.send_json(404, {"error": "note not found"})
        else:
            self.send_json(200, {"deleted": removed["id"]})


def call(port, method, path, payload=None):
    """Send one request to our own server and print what happened."""
    conn = http.client.HTTPConnection("127.0.0.1", port, timeout=5)
    body = None if payload is None else (payload if isinstance(payload, bytes) else json.dumps(payload))
    conn.request(method, path, body=body, headers={"Content-Type": "application/json"})
    resp = conn.getresponse()
    text = resp.read().decode("utf-8")
    conn.close()
    print(f"{method:6} {path:<10} -> {resp.status} {text}")
    return resp.status


def serve_forever(port=8000):
    """Optional mode: python3 main.py --serve  (stop with Ctrl+C)."""
    server = ThreadingHTTPServer(("127.0.0.1", port), NotesHandler)
    print(f"Serving on http://127.0.0.1:{port}/notes  (Ctrl+C to stop)")
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        print("\nBye")
    finally:
        server.server_close()


def main():
    if "--serve" in sys.argv:
        return serve_forever()
    # Port 0 asks the operating system for any free port.
    server = ThreadingHTTPServer(("127.0.0.1", 0), NotesHandler)
    port = server.server_address[1]
    thread = threading.Thread(target=server.serve_forever, daemon=True)
    thread.start()
    print("Server started on 127.0.0.1 (ephemeral port)")
    try:
        call(port, "POST", "/notes", {"title": "Buy milk"})
        call(port, "POST", "/notes", {"title": "Learn REST", "done": False})
        call(port, "GET", "/notes")
        call(port, "GET", "/notes/2")
        call(port, "PUT", "/notes/2", {"done": True})
        call(port, "POST", "/notes", {"done": True})
        call(port, "POST", "/notes", b"{not json")
        call(port, "GET", "/notes/99")
        call(port, "DELETE", "/notes/1")
        call(port, "GET", "/notes")
        call(port, "GET", "/other")
        call(port, "PATCH", "/notes/2", {"done": False})
    finally:
        server.shutdown()        # stop serve_forever loop
        server.server_close()    # release the socket
        thread.join()
    print("Server stopped cleanly")


if __name__ == "__main__":
    main()

Code explanation

Handler methods

The server calls do_GET, do_POST and so on based on the request method. self.path holds the URL path and self.rfile the request body.

Status codes

201 means created, 400 a bad request, 404 not found and 405 method not allowed. Clients depend on these codes, so choose them carefully.

Content-Length

The server must tell the client how many bytes follow. send_json() encodes the body first so len() is correct.

Threads and the lock

ThreadingHTTPServer handles each request in its own thread. The Lock protects NOTES and NEXT_ID from simultaneous changes.

Ephemeral port self-test

serve_forever() runs in a background thread while the main thread acts as the client. shutdown() ends the loop and server_close() frees the socket.

Expected output

Server started on 127.0.0.1 (ephemeral port)
POST   /notes     -> 201 {"id": 1, "title": "Buy milk", "done": false}
POST   /notes     -> 201 {"id": 2, "title": "Learn REST", "done": false}
GET    /notes     -> 200 [{"id": 1, "title": "Buy milk", "done": false}, {"id": 2, "title": "Learn REST", "done": false}]
GET    /notes/2   -> 200 {"id": 2, "title": "Learn REST", "done": false}
PUT    /notes/2   -> 200 {"id": 2, "title": "Learn REST", "done": true}
POST   /notes     -> 400 {"error": "title is required"}
POST   /notes     -> 400 {"error": "invalid JSON"}
GET    /notes/99  -> 404 {"error": "note not found"}
DELETE /notes/1   -> 200 {"deleted": 1}
GET    /notes     -> 200 [{"id": 2, "title": "Learn REST", "done": true}]
GET    /other     -> 404 {"error": "unknown path"}
PATCH  /notes/2   -> 405 {"error": "method not allowed"}
Server stopped cleanly

Common errors and solutions

Error: OSError: Address already in use
Solution: Use port 0 for tests, or pick another port, or wait until the old server is closed.
Error: Client hangs waiting for a reply
Solution: Always send Content-Length and call end_headers() before writing the body.
Error: json.JSONDecodeError in the handler
Solution: Catch ValueError when parsing and answer with 400 instead of crashing.
Error: The program never exits after the demo
Solution: Call server.shutdown() from a different thread than serve_forever(), and join the thread.

Ideas to improve the project