Skip to main content

The Server Calls You

A Python web server (the standard http.server module) is built from handler classes: subclass BaseHTTPRequestHandler and write a do_GET method. The server accepts connections and calls your method once per request — self.path and self.headers hold the request, and send_response, send_header and self.wfile build the response.

A real server calls serve_forever() on a fixed port and runs forever. The examples here pick port 0 — a random free port — and run serve_forever in a background thread, so every example starts its server, uses it and finishes by itself. They also override log_message with an empty method: the base class prints a timestamped log line for every request, and the demos want clean, stable output.


A First Handler

The smallest possible handler writes a line of text. Everything an API does — JSON, status codes, routing — happens inside this same method shape.

Hello from a handler

The handler writes into self.wfile; the client reads exactly that as the response body, with the status line chosen by send_response(200).

Prompt
Write a Python program with the smallest BaseHTTPRequestHandler subclass whose do_GET writes a hello line, serve it on a free port in a background thread, send one GET request and print the response status and body.
Output: complete Python program

Answering with JSON

An API handler does three things: choose a status code, set the Content-Type header, and write the encoded data — json.dumps builds the text, self.wfile.write sends the bytes.

Order matters: send_response first, then the headers, then end_headers, and only then the body.

A JSON endpoint

The handler dumps a dict straight into the response. The client receives valid JSON and the right content type — this is the skeleton of every endpoint in the rest of this group.

Prompt
Write a Python program with a handler that answers with a JSON user built by json.dumps and a Content-Type header, serve it on a free port in a background thread, request it and print the status, content type and JSON body.
Output: complete Python program