create a http server with a custom route in python

To create a HTTP server with a custom route in Python, we can use the built-in http.server module. In this example, we will create a server that listens on port 8080 and has a custom route at endpoint /hello.

Here's the code:

main.py
from http.server import BaseHTTPRequestHandler, HTTPServer

# HTTPRequestHandler class
class RequestHandler(BaseHTTPRequestHandler):
  
  # GET
  def do_GET(self):
        if self.path == '/hello':
            # send response code
            self.send_response(200)

            # send headers
            self.send_header('Content-type', 'text/html')
            self.end_headers()

            # send message back to client
            message = "Hello, world!"
            # write content as utf-8 data
            self.wfile.write(bytes(message, "utf8"))
            return

        else:
            # send response code
            self.send_response(404)
            return

def run():
  print('Starting server...')

  # Server settings
  server_address = ('127.0.0.1', 8080)
  httpd = HTTPServer(server_address, RequestHandler)
  print('Running server...')
  httpd.serve_forever()

run()
897 chars
37 lines

Here we define a custom request handler RequestHandler that extends from BaseHTTPRequestHandler. We override the do_GET method to handle GET requests. Within this method, we check if the request path is '/hello', and if it is, we send a 200 status code, set the content type to HTML and send a 'Hello, world!' message to the client. If the request path is anything else, we send back a 404 status code.

To run the server, we simply call the run function. This creates an instance of the HTTPServer object on port 8080 with our custom request handler, and calls serve_forever to start listening for incoming requests.

Note that if you want to handle other HTTP methods such as POST, PUT or DELETE, you can do so by overriding the corresponding methods (do_POST, do_PUT, do_DELETE) in a similar way.

gistlibby LogSnag