Close

Creating an HTTP Proxy Server in Python

Jeeva
Jeeva
Apr 29, 2024 • Python, Proxy
Creating an HTTP Proxy Server in Python

An HTTP proxy server acts as an intermediary between a client and a server. It facilitates communication between the two, allowing clients to make indirect network connections to other network services. In this tutorial, we'll create a simple HTTP proxy server in Python using the http.server module.

To follow this tutorial, you should have basic knowledge of Python programming.

Setting up the HTTP Proxy Server

First, let's create a new Python file called proxy_server.py, and open it in your favorite text editor.

import http.server
import socketserver
import urllib.request

PORT = 8000

class Proxy(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        url = self.path
        try:
            response = urllib.request.urlopen(url)
            self.send_response(response.status)
            self.send_header('Content-type', response.headers['Content-type'])
            self.end_headers()
            self.wfile.write(response.read())
        except Exception as e:
            self.send_error(500, str(e))

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

In our code, we begin by importing the necessary modules: http.server, socketserver, and urllib.request. We then define the port number for our proxy server. Next, we create a class called Proxy, which inherits from http.server.SimpleHTTPRequestHandler. This class is responsible for handling incoming HTTP requests. By overriding the do_GET method, we intercept GET requests. Within the do_GET method, we extract the requested URL from self.path. Using urllib.request.urlopen(), we fetch the content from the requested URL. Finally, we send the fetched content back to the client.

To run the proxy server, simply execute the Python script:

$ python proxy_server.py

Conclusion

In this tutorial, we created a simple HTTP proxy server in Python using the http.server module. This proxy server can handle basic GET requests. For a more robust solution, you can extend this code to handle other HTTP methods, headers, and HTTPS requests. We publish new coding tutorial every week don't forget to check daily.