Setting Up a Web Server
Next you need to set up an Internet-facing web server to process incoming confirmation and webhook HTTP requests. In this section we will set up a Python-based web server which logs all requests to the standard output for testing purposes. By looking at the logs, you will see the structure of confirmation and webhook requests and will learn how to integrate hook functionality into a larger application.
Prerequisitesโ
To set up this server, you need:
- a computer (physical server or virtual machine) with access to the public Internet
- the ability to listen to incoming requests on an open port (this most often means that you are allowed to configure firewall settings and if the machine is behind a router, you can access port forwarding settings; on cloud-based virtual machines, there are usually no additional settings required)
- to have Python 3 installed
Installing the serverโ
Assuming that the prerequisites are met, all you need to do is save the following code into a file (server.py):
#!/usr/bin/env python3
"""
Very simple HTTP server in python for logging requests
Usage::
./server.py [<port>]
"""
from http.server import BaseHTTPRequestHandler, HTTPServer
import logging
class S(BaseHTTPRequestHandler):
def _set_response(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
def do_GET(self):
logging.info("============================")
logging.info("GET request,\nPath: %s\nHeaders:\n%s\n", str(self.path), str(self.headers))
self._set_response()
self.wfile.write("GET request for {}".format(self.path).encode('utf-8'))
def do_POST(self):
content_length = int(self.headers['Content-Length']) # <--- Gets the size of data
post_data = self.rfile.read(content_length) # <--- Gets the data itself
logging.info("============================")
logging.info("POST request,\nPath: %s\nHeaders:\n%s\n\nBody:\n%s\n",
str(self.path), str(self.headers), post_data.decode('utf-8'))
self._set_response()
self.wfile.write("POST request for {}".format(self.path).encode('utf-8'))
def run(server_class=HTTPServer, handler_class=S, port=8080):
logging.basicConfig(level=logging.INFO)
server_address = ('', port)
httpd = server_class(server_address, handler_class)
logging.info('Starting httpd...\n')
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
httpd.server_close()
logging.info('Stopping httpd...\n')
if __name__ == '__main__':
from sys import argv
if len(argv) == 2:
run(port=int(argv[1]))
else:
run()
If you use Linux or another Unix-like system, make sure the file has executable permissions:
chmod +x server.py
Then start the server on a port of your choice. We will use 8888 in the examples here.
./server.py 8888
If you use Windows, you can start the server by running the python command:
python server.py 8888
Make sure to test if the server can respond to external requests by manually issuing GET or POST requests and checking the logs in the terminal.