create a http server with a specific route and a specific status code in python

To create an HTTP server with a specific route and a specific status code in Python, you can use 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'<html><body>Hello, World!</body></html>')
        else:
            self.send_error(404)

port = 8000
httpd = HTTPServer(('localhost', port), MyHandler)
print(f'Starting server on port {port}')
httpd.serve_forever()
532 chars
17 lines

In this example, we define a custom request handler class MyHandler that inherits from BaseHTTPRequestHandler. In the do_GET method, we check if the requested path is '/my/route'. If it is, we send a 200 status code with a simple HTML response, otherwise we send a 404 error.

We then create an instance of HTTPServer with our handler on port 8000 and start the server. When the server is running, you can visit http://localhost:8000/my/route in your web browser to see the "Hello, World!" message.

gistlibby LogSnag