Skip to content

Building a Simple HTTP Server

The built-in http.server

Python includes a simple HTTP server in the standard library.

Great for:

  • local demos
  • serving static files

Not ideal for production.

Serve a folder

If you run:

python -m http.server 8000
python -m http.server 8000

Then open:

  • http://localhost:8000http://localhost:8000

Custom handler

custom_http_server.py
from http.server import BaseHTTPRequestHandler, HTTPServer
 
 
class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-Type", "text/plain")
        self.end_headers()
        self.wfile.write(b"Hello from Python HTTP server")
 
 
if __name__ == "__main__":
    server = HTTPServer(("127.0.0.1", 8000), Handler)
    print("Serving on http://127.0.0.1:8000")
    server.serve_forever()
custom_http_server.py
from http.server import BaseHTTPRequestHandler, HTTPServer
 
 
class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-Type", "text/plain")
        self.end_headers()
        self.wfile.write(b"Hello from Python HTTP server")
 
 
if __name__ == "__main__":
    server = HTTPServer(("127.0.0.1", 8000), Handler)
    print("Serving on http://127.0.0.1:8000")
    server.serve_forever()

What’s happening?

  • do_GETdo_GET handles HTTP GET requests
  • send_responsesend_response sets status code
  • headers must be sent before the body

πŸ§ͺ Try It Yourself

Exercise 1 – HTTP GET with urllib

Exercise 2 – Socket Connection

Exercise 3 – Resolve a Hostname

If this helped you, consider buying me a coffee β˜•

Buy me a coffee

Was this page helpful?

Let us know how we did