Knowing how to create a simple http server comes in very handy, especially when working on projects where your application has to be accessed by a remote device. It’s not very difficult to create an http server with Python, so let’s dive straight into it.
Python is a very good language to do this, because it runs on Windows, Mac OS X and Linux, which makes your little web server very universal. Especially in a development environment.
To get started, create a new Python script with the following contents:
from http.server import BaseHTTPRequestHandler, HTTPServer
# HTTPRequestHandler class
# Send response status code
# Send headers
# Send message back to client
message = "Hello world!"
# Write content as utf-8 data
# Server settings
# Choose port 8080, for port 80, which is normally used for a http server, you need root access
server_address = ('127.0.0.1', 8081)
httpd = HTTPServer(server_address, testHTTPServer_RequestHandler)
When you run the script, the server will start on port 8081. If you want to use port 80, for example, you’ll have to run your application with root permissions, so that’s why I’m going with port 8081.
Whenever the server gets a GET request, it’ll run the do_GET function, and return a 200 (success) status code header, as well as the text/html content type header to the client system. Along with an hello world message.
To test the http server, open your web browser and type “http://localhost:8081”, you’ll see this: