Small server in python without dependencies
Posted on Jan 28, 2025 in blogpost
Python is a batteries-included kind of language, and so of course it comes with an HTTP server module. Today I wanted to have something small running on my computer without dependencies to test a server-side example, so I looked into how to create a minimal server using python built-ins. This is what I ended up with:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | |
First of all, since this is just for trying it out, I imported everything from http.server. Never do this in normal code.
We use HTTPServer and initialise it with the port we want to serve to and a handler class Resp that we subclass from BaseHTTPRequestHandler.
We add a do_GET method to our class, making it reply to all GET requests with that module.
I don’t know how they implemented this, but it doesn’t sound like it would be pretty.
The request handler class has an instance variable wfile which is where we’re supposed to write our response.
The response is supposed to be a bytestring, hence the b""",
and it needs to be valid HTTP so that whatever tool we use to read it does not choke on it.
Write the headers you want (including response code) and then the body.

There’s also a threading server you can use if you want concurrency, I’ve never tried it.
Extra info because I’m nice
Inside any directory with web files, you can run
python3 -m http.server 8000 # use the port you want
to serve the files to your browser. This is useful to get around restrictions that plain html files have when opened.