Creating a Basic HTTP Web Server in Python

Python is a versatile programming language that can be used to develop various types of applications, including web servers. In this article, we will guide you on how to create a basic HTTP web server in Python.

Step 1: Install Python

Before we begin, ensure that you have Python installed on your system. You can download the latest version of Python from the official website https://www.python.org/downloads/.

Step 2: Importing the Required Libraries

To create an HTTP server in Python, we need to use the http.server module that comes with Python’s standard library. We can import this module by adding the following line of code at the beginning of our Python file:

import http.server
import socketserver

Step 3: Defining the Request Handler

After importing the necessary modules, we need to define a request handler that will handle incoming HTTP requests. We can create a custom request handler class that extends the http.server.BaseHTTPRequestHandler class provided by the http.server module. In this class, we will define the do_GET method that will handle GET requests.

class SimpleHTTPRequestHandler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        self.wfile.write(b'Hello, world!')

This code defines a simple request handler that sends a “Hello, world!” response for all incoming GET requests.

Step 4: Starting the Server

To start the HTTP server, we need to create a socketserver.TCPServer object and pass it the IP address and port number to bind to. We can then call the serve_forever() method on this object to start the server and listen for incoming requests.

PORT = 8000

with socketserver.TCPServer(("", PORT), SimpleHTTPRequestHandler) as httpd:
    print("serving at port", PORT)
    httpd.serve_forever()

This code creates an HTTP server that listens on port 8000 and prints a message to the console indicating that the server is running.

Step 5: Testing the Server

To test the server, open your web browser and navigate to http://localhost:8000/. You should see a “Hello, world!” message displayed on the page.

Conclusion

In this article, we have shown you how to create a basic HTTP web server in Python using the http.server module. With this knowledge, you can now build more complex web applications in Python or use this simple server for testing and prototyping purposes.


See also