CODE WITH MARTIN

HTTP Web Service


Introduction

This article will show you very quickly how to use Python as a web server without any 3rd party packages. This is a very simple 'hello world' example that can be expanded on whilst learning HTTP.

The Code

from http.server import BaseHTTPRequestHandler, HTTPServer

hostName = "localhost"
serverPort = 8080

class MyServer(BaseHTTPRequestHandler):
  def do_GET(self):
    self.send_response(200)
    self.send_header("Content-type", "text/html")
    self.end_headers()
    self.wfile.write(bytes("My Web Server", "utf-8"))
    self.wfile.write(bytes("

Request Path: %s

" % self.path, "utf-8")) self.wfile.write(bytes("", "utf-8")) self.wfile.write(bytes("

Hello, from my web server!

", "utf-8")) self.wfile.write(bytes("", "utf-8")) server = HTTPServer((hostName, serverPort), MyServer) print("Server started http://%s:%s" % (hostName, serverPort)) server.serve_forever()

When you run, you will see in the terminal the server started message. While the server is running, open your browser and browse to "http://localhost:8080/hello/world".

You should see a response in your browser that came from your server in lines 7-15. The URL "/hello/world" that you used in the browser can be changed to anything you want. This is simply echoed back to the browser on line 12.

Next Steps

Using this basic example, you can expand it to have your service return information from a database, that you might want to feed to a front-end application.

You could store some HTML web pages and serve these files as a response when a user browses to a specific path.

You could handle HTML form post requests from anything like a create account page or login page in a front-end application.

You could return JSON data using the Python module 'json' which makes data easily consumed by Javascript applications.

Have fun exploring the Python HTTPServer and BaseHTTPRequestHandler modules!