How to Create an HTTP Server using Python

1 min readDec 19, 2022

In this document, we will learn how to create a simple HTTP server using python on our local computer. To create a simple HTTP server in Python, you can use the http.server module. This module is part of the Python Standard Library, so you don't need to install any additional libraries to use it.

Here’s an example of how to create a simple HTTP server that listens on port 8000 and serves a single HTML file:

from http.server import HTTPServer, BaseHTTPRequestHandler

class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):

def do_GET(self):
with open('index.html', 'rb') as f:

httpd = HTTPServer(('localhost', 8000), SimpleHTTPRequestHandler)

This code creates a subclass of BaseHTTPRequestHandler called SimpleHTTPRequestHandler, which defines a do_GET() method that is called when a client makes a GET request to the server. The do_GET() method sends a response with a status code of 200 (indicating that the request was successful) and then sends the contents of the file index.html to the client.

To start the server, we create an instance of HTTPServer and pass it the tuple ('localhost', 8000), which specifies the host and port to bind to. We also pass it the SimpleHTTPRequestHandler class as the second argument. Finally, we call the serve_forever() method to start the server.

This is just a basic example, and you can customize the server by adding additional methods to the SimpleHTTPRequestHandler class or by using a different request handler class. You can also add additional functionality, such as support for POST requests or handling dynamic content using templates.