Building a simple HTTP server in Python
A web server can seem like a large piece of infrastructure, surrounded by reverse proxies, deployment pipelines, certificates, and monitoring dashboards. For local development, though, the essential idea is much smaller: a program listens on a network port, receives an HTTP request, and sends back a response. Python includes the tools needed to demonstrate that process without installing a separate server package.
This makes a small Python server useful for testing a front end, previewing documents, sharing files across a home network, or learning how browsers and web applications communicate. It is also a good fit for the practical style common in software teams, where a quick local service can save time before a full application exists.
The examples below use Python 3 and should work on Windows, Ubuntu, and macOS. They are suitable for a laptop in Sydney, a workstation in Melbourne, or a small project being tested over an NBN connection in regional Australia. The server is deliberately simple, which makes its behaviour easier to inspect.
Starting with Python’s built-in server
The quickest method is to open a terminal in the directory you want to publish and run:
python3 -m http.server 8000
On some Windows installations, the command is:
py -m http.server 8000
Python starts listening on port 8000 and serves files from the current directory. Open http://localhost:8000 in a browser and you will see a directory listing, unless the folder contains an index.html file. The address localhost means the request stays on the same computer; it does not travel out to the internet.
The number 8000 is the port. Standard web traffic commonly uses port 80 for HTTP and 443 for HTTPS, but ordinary users usually cannot bind to those lower ports without extra privileges. A high port such as 8000 avoids that complication and is convenient for development. Stop the process with Ctrl+C.
Changing directories before launching the command changes what the server exposes. For example:
cd ~/Projects/sample-site
python3 -m http.server 8000
On Ubuntu, the home-directory path is familiar to most developers. On Windows, use cd C:\Users\YourName\Projects\sample-site. Be careful with the folder: every readable file beneath it may be available to anyone who can reach the server.
Serving a small website
A basic directory for a test site might contain these files:
sample-site/
├── index.html
├── styles.css
└── app.js
When the browser requests /, Python looks for index.html and sends it as the response. A minimal page could be:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Local test page</title>
<link rel="stylesheet" href="/styles.css">
</head>
<body>
<h1>It works</h1>
<p>This page is being served by Python.</p>
<script src="/app.js"></script>
</body>
</html>
The server determines the content type from the file extension, so CSS is generally delivered as text/css, JavaScript as a JavaScript media type, and HTML as text/html. If a file is missing, the browser receives a 404 response. The terminal will usually show each request, including its path and status code.
This is handy for checking relative links and client-side behaviour. Opening index.html directly with a file:// URL can hide problems because browsers treat local files differently from HTTP resources. Running a local server gives the page the same request model used by a deployed website, even though it has no public domain name.
A developer testing from a café in Brisbane may see a slightly different result from opening the same file directly, particularly when JavaScript uses fetch() or makes requests to another local service. The HTTP server provides the browser with a proper origin, which is important for permissions and cross-origin rules.
Writing a request handler
The built-in static server is useful, but a custom handler shows how a web application responds to a request. Create a file named server.py:
from http.server import BaseHTTPRequestHandler, HTTPServer
class RequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/":
body = b"<h1>Hello from Python</h1>"
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
else:
body = b"Not found"
self.send_response(404)
self.send_header("Content-Type", "text/plain; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
server = HTTPServer(("127.0.0.1", 8000), RequestHandler)
print("Serving at http://127.0.0.1:8000")
server.serve_forever()
Run it with:
python3 server.py
The handler’s do_GET() method is called when the client sends an HTTP GET request. send_response() writes the status line, headers describe the response, and end_headers() marks the point where the body begins. The body must be written as bytes, which is why the examples use the b"..." notation.
127.0.0.1 is the loopback address, equivalent to localhost. Binding there means the server accepts connections from the same machine only. This is a sensible default for experiments and avoids accidentally putting a test endpoint on the local network. A browser pointed at http://127.0.0.1:8000/ should receive the HTML response.
Returning useful data
An HTTP handler becomes more interesting when it returns structured data. JSON is a common format for browser applications, command-line tools, and small internal services:
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
class RequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/api/status":
payload = {
"service": "demo",
"status": "ok",
"region": "local"
}
body = json.dumps(payload).encode("utf-8")
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)
else:
self.send_error(404, "Route not found")
server = HTTPServer(("127.0.0.1", 8000), RequestHandler)
server.serve_forever()
Visiting http://127.0.0.1:8000/api/status produces a response such as:
{"service": "demo", "status": "ok", "region": "local"}
The call to encode("utf-8") converts Python’s string into the byte sequence required by the HTTP connection. Setting Content-Length is good practice for a small response because it tells the client exactly how much data to read. send_error() provides a simple error page and status code when a route does not exist.
Path matching can be expanded with urllib.parse when a service needs query parameters. For example, /api/status?verbose=true contains a path and a query string that should be parsed rather than compared as one raw value. A custom handler can also implement do_POST() for submitted data, although request bodies require validation and careful handling.
For a lightweight utility used by a local team in Adelaide or Canberra, this pattern may be enough to test a dashboard or a script. It should not be confused with a complete web framework. Authentication, input validation, routing, database access, and production logging all need additional design.
Looking at requests from the command line
A browser hides much of the HTTP exchange. The curl command makes it visible:
curl -i http://127.0.0.1:8000/api/status
The -i option includes response headers. You may see output resembling:
HTTP/1.0 200 OK
Server: BaseHTTP/0.6 Python/3.x
Date: ...
Content-Type: application/json
Content-Length: 53
{"service": "demo", "status": "ok", "region": "local"}
This shows the status line, metadata, a blank line, and the response body. A request for an unknown route demonstrates the error path:
curl -i http://127.0.0.1:8000/missing
The terminal running Python will also record the request. These two views help separate client-side problems from server-side problems. If curl receives the expected JSON but a browser shows an error, the issue may involve JavaScript, an incorrect URL, or a cross-origin policy.
You can inspect headers without downloading the body by using:
curl -I http://127.0.0.1:8000/
To test another device on a private network, bind the server to 0.0.0.0 and find the host computer’s local IP address:
server = HTTPServer(("0.0.0.0", 8000), RequestHandler)
A phone or laptop might then connect to http://192.168.1.20:8000/, provided the firewall permits it. This can be useful on a home network, though NBN router settings and device isolation may prevent connections. It is safer to return to 127.0.0.1 when network testing is finished.
Making the server easier to use
The single-process HTTPServer is adequate for a demonstration, but it handles requests sequentially. If one handler pauses, later clients wait. Python provides ThreadingHTTPServer for a simple improvement:
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
class RequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
body = b"Hello"
self.send_response(200)
self.send_header("Content-Type", "text/plain; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
server = ThreadingHTTPServer(("127.0.0.1", 8000), RequestHandler)
server.serve_forever()
Each request can be handled in its own thread. That makes a small test service feel more responsive when a browser requests several assets at once. It does not remove the need for safe shared-state handling, and it is not a substitute for a mature application server under real traffic.
A clean shutdown can be added with a try and finally block:
try:
server.serve_forever()
except KeyboardInterrupt:
print("\nStopping server")
finally:
server.server_close()
For repeated experiments, keep the code in a virtual environment and use version control. A short README should record the Python version, start command, port, and expected routes. That is especially useful in a small Australian consultancy where a project moves between a Windows laptop, an Ubuntu workstation, and a hosted environment in Sydney.
The standard library also includes SimpleHTTPRequestHandler, which can be combined with ThreadingHTTPServer when the goal is fast static file serving rather than custom API logic. The built-in modules offer a useful middle ground: less setup than a framework, with enough control to observe the protocol directly.
Keeping a local server local
A development server is not automatically safe for public use. The simple handler does not provide HTTPS, authentication, rate limiting, robust access logs, or strong protection against hostile input. It should never be treated as a production internet-facing service merely because it can answer requests.
The distinction matters in Australia, where residential internet connections often use carrier-grade NAT. A server on a home NBN connection may not be directly reachable from the wider internet, but that should not be relied upon as a security measure. Port forwarding can expose it, and a misconfigured router or firewall may make a service visible to neighbours on the same network.
Static file serving has its own risk. If the current directory contains .env files, private keys, source code, backups, or customer documents, the directory listing may expose them. Create a dedicated public folder and bind to the loopback interface while developing. Check the exact address and port before sharing a terminal command with colleagues.
For an application that will handle real users, choose a framework and deployment stack designed for that job, then place it behind a properly configured web server or managed platform. Teams choosing a hosting region in Sydney or Melbourne may also need to consider latency, backup locations, contractual requirements, and Australian Privacy Act obligations. A local Python server remains valuable in that environment because it gives developers a small, transparent way to verify routes and responses before those larger systems are involved.