create a http server with a specific route in python

You can create an HTTP server with a specific route in Python using the built-in http.server module. Here's an example:

main.py
from http.server import BaseHTTPRequestHandler, HTTPServer

class MyHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == '/my/route':
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            self.wfile.write(b'Hello, world!')
        else:
            self.send_error(404)

if __name__ == '__main__':
    server_address = ('', 8000)
    httpd = HTTPServer(server_address, MyHandler)
    print(f'Serving on port {server_address[1]}')
    httpd.serve_forever()
565 chars
18 lines

In this example, we create a subclass of BaseHTTPRequestHandler that overrides the do_GET method to check if the requested path is /my/route. If it is, we send a 200 response with the message "Hello, world!". If it's any other path, we send a 404 error response.

To start the server, we create an HTTPServer instance with our custom handler and call serve_forever() on it. This will start the server and keep it running indefinitely, listening for incoming requests on port 8000 (in this example).

gistlibby LogSnag