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 8000python -m http.server 8000Then 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_GEThandles HTTP GET requestssend_responsesend_responsesets 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 coffeeWas this page helpful?
Let us know how we did
