Python, create a Web (HTTP) server
Python makes it super easy to create an HTTP server, via the http
module of the standard library.
In particular, the http.server
object is the thing we’re going to use.
First, I want to mention one quick way to run an HTTP server from any folder, without writing any code:
python -m http.server --cgi 8000
This will run an HTTP server on port 8000, serving the files in the current folder. Of course it’s not an HTTP server fully featured like Nginx or Apache, but that’s often good enough for prototypes, or for your own test projects.
Let’s now use that module in our code to make it programmatically serve an “Hello, World!” string to anyone connecting on port 8000
:
from http.server import BaseHTTPRequestHandler, HTTPServer
class handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
message = "Hello, World!"
self.wfile.write(bytes(message, "utf8"))
with HTTPServer(('', 8000), handler) as server:
server.serve_forever()
After running this program locally you can try connecting using a Web browser to port http://localhost:8000.
This serves the same Hello, World!
string to anyone visiting the site on http://localhost:8000
, on GET requests to any URL, complete with a 200 response and a Content-type: text/html
header.
We write to wfile
, which contains the output stream for writing a response back to the client.
It works on GET requests because we implemented the handler do_GET
method.
You can also implement do_HEAD()
, do_POST()
and any other HTTP method:
from http.server import BaseHTTPRequestHandler, HTTPServer
class handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
message = "Hello, World! Here is a GET response"
self.wfile.write(bytes(message, "utf8"))
def do_POST(self):
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
message = "Hello, World! Here is a POST response"
self.wfile.write(bytes(message, "utf8"))
with HTTPServer(('', 8000), handler) as server:
server.serve_forever()
Python has lots of different libraries we can use to handle applications built on top a Web server, including the very popular Flask and Django.
→ I wrote 17 books to help you become a better developer, download them all at $0 cost by joining my newsletter
→ JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025