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.py897 chars37 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