Creating an HTTP server in Python is incredibly easy thanks to the http module in the standard library. Specifically, we’ll be using the http.server object to achieve this.

Quick Way to Run an HTTP Server

Before we dive into the code, let’s talk about a quick way to run an HTTP server without writing any code. Simply run the following command:

python -m http.server --cgi 8000

This command will start an HTTP server on port 8000, serving the files from the current folder. While this server may not have all the features of Nginx or Apache, it’s often sufficient for prototypes and personal test projects.

Creating an HTTP Server Programmatically

Now, let’s use the http.server module in Python to programmatically serve a “Hello, World!” string to anyone connecting on port 8000. Here’s the code:

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()

Once you run this program locally, you can open your web browser and visit http://localhost:8000. You’ll see the “Hello, World!” string being served on that page. This code responds to GET requests for any URL with a 200 response and a Content-type: text/html header.

Inside the do_GET method, we write to wfile, which is the output stream for sending the response back to the client.

Expanding the Functionality

To handle other HTTP methods, such as POST requests, you can implement additional methods like do_POST or do_HEAD. Here’s an example:

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()

Using Web Frameworks

Python offers various web frameworks, such as Flask and Django, that can be used to build more complex applications on top of the HTTP server. These frameworks provide additional features and abstractions to simplify web development.

Tags: Python, Web server, HTTP server, programming