The HTTP service

The service is the reason the project has the shape it has. A Python program that calls the core directly does not need a shared library at all; a service does, because the process that answers HTTP requests must be able to run the numerical code without a compiler and without the Fortran source. That is what a shared library gives, and it is why the boundary was designed first.

The service

Two routes, on the standard library: /health for a check that the process is alive and /stats?values=2,4,4,5 for the numbers. The handler is a subclass of BaseHTTPRequestHandler, the server is ThreadingHTTPServer so that one slow request does not block the next, and the one method that has to have an upper-case name, do_GET, is the one the base class calls.

The file python/service.py:

"""A small HTTP service over the Fortran core, on the standard library only.""" from __future__ import annotations import json import sys from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from typing import Any from urllib.parse import parse_qs, urlparse import numerics def parse_values(text: str) -> list[float]: """Turn "1,2,3" into a list of floats, or raise ValueError.""" parts = [part.strip() for part in text.split(",") if part.strip()] if not parts: message = "values is empty" raise ValueError(message) return [float(part) for part in parts] def summary(values: list[float]) -> dict[str, Any]: """Return the statistics the service publishes for one series.""" return { "n": len(values), "mean": numerics.mean(values), "sd": numerics.sd(values) if len(values) > 1 else 0.0, "median": numerics.median(values), } class Handler(BaseHTTPRequestHandler): """Two routes: /health and /stats?values=1,2,3.""" def do_GET(self) -> None: # pylint: disable=invalid-name """Answer one GET request; the method name is fixed by the base class.""" parsed = urlparse(self.path) if parsed.path == "/health": self._reply(200, {"status": "ok"}) return if parsed.path == "/stats": query = parse_qs(parsed.query) try: values = parse_values(query.get("values", [""])[0]) self._reply(200, summary(values)) except (ValueError, numerics.CoreError) as error: self._reply(400, {"error": str(error)}) return self._reply(404, {"error": f"no route for {parsed.path}"}) def _reply(self, status: int, body: dict[str, Any]) -> None: payload = json.dumps(body).encode() self.send_response(status) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(payload))) self.end_headers() self.wfile.write(payload) def log_message(self, format: str, *args: Any) -> None: # pylint: disable=redefined-builtin """Keep the test output quiet; a service would log here.""" def make_server(host: str = "127.0.0.1", port: int = 8000) -> ThreadingHTTPServer: """Create a server; port 0 asks the system for a free port.""" return ThreadingHTTPServer((host, port), Handler) def main(argv: list[str]) -> int: """Run the service until interrupted.""" port = int(argv[1]) if len(argv) > 1 else 8000 server = make_server(port=port) print(f"listening on http://127.0.0.1:{server.server_port}", flush=True) try: server.serve_forever() except KeyboardInterrupt: pass finally: server.server_close() return 0 if __name__ == "__main__": sys.exit(main(sys.argv))

The JSON contract

requeststatusbody
GET /health200{"status": "ok"}
GET /stats?values=2,4,4,5200{"n": 4, "mean": 3.75, "sd": 1.2583057392117916, "median": 4.0}
GET /stats?values=2,four,5400{"error": "could not convert string to float: 'four'"}
GET /nothing404{"error": "no route for /nothing"}

Two decisions in that table are worth copying. A bad value is a 400 with a JSON body, not a traceback and not a 500: the caller sent something the service cannot use, and the message says what. And summary computes sd as zero for a one-value series instead of letting the core divide by zero, because the standard deviation of one value is undefined and the service has to answer something.

The live session

The service was started in the background and asked four questions with curl, which prints the status line and the headers as well as the body:

python3 service.py 8765 &
curl -s -i http://127.0.0.1:8765/health
curl -s -i "http://127.0.0.1:8765/stats?values=2,4,4,5"
curl -s -i "http://127.0.0.1:8765/stats?values=2,four,5"
curl -s -i "http://127.0.0.1:8765/nothing"

listening on http://127.0.0.1:8765
HTTP/1.0 200 OK
Server: BaseHTTP/0.6 Python/3.14.10
Date: Wed, 18 Nov 2026 21:19:37 GMT
Content-Type: application/json
Content-Length: 16

{"status": "ok"}
HTTP/1.0 200 OK
Server: BaseHTTP/0.6 Python/3.14.10
Date: Wed, 18 Nov 2026 21:19:37 GMT
Content-Type: application/json
Content-Length: 63

{"n": 4, "mean": 3.75, "sd": 1.2583057392117916, "median": 4.0}
HTTP/1.0 400 Bad Request
Server: BaseHTTP/0.6 Python/3.14.10
Date: Wed, 18 Nov 2026 21:19:37 GMT
Content-Type: application/json
Content-Length: 54

{"error": "could not convert string to float: 'four'"}
HTTP/1.0 404 Not Found
Server: BaseHTTP/0.6 Python/3.14.10
Date: Wed, 18 Nov 2026 21:19:37 GMT
Content-Type: application/json
Content-Length: 34

{"error": "no route for /nothing"}

The numbers in the second response are the ones the Fortran test asserted and the wrapper test asserted, now arriving over a socket: 3.75 and 1.2583057392117916. The chain from the paper formula to the JSON body is three files long and each of them has a test.

Four tests against a real server

A test that calls the handler directly proves the routing but not the socket. These four start the real server on port zero, which asks the system for a free port, keep it for the class and stop it afterwards. The file python/test_service.py:

"""Tests of the HTTP service, on a server the test starts on a free port.""" from __future__ import annotations import json import threading import unittest import urllib.error import urllib.request from http.server import ThreadingHTTPServer from typing import Any import service class ServiceTests(unittest.TestCase): """One server for the class, four requests against it.""" server: ThreadingHTTPServer base: str thread: threading.Thread @classmethod def setUpClass(cls) -> None: """Start the service on port 0 and remember the port it chose.""" cls.server = service.make_server(port=0) cls.base = f"http://127.0.0.1:{cls.server.server_port}" cls.thread = threading.Thread(target=cls.server.serve_forever, daemon=True) cls.thread.start() @classmethod def tearDownClass(cls) -> None: """Stop the server and wait for its thread.""" cls.server.shutdown() cls.server.server_close() cls.thread.join() def get(self, path: str) -> tuple[int, dict[str, Any]]: """Return the status and the JSON body of one request.""" try: with urllib.request.urlopen(self.base + path, timeout=5) as response: return response.status, json.loads(response.read()) except urllib.error.HTTPError as error: body = json.loads(error.read()) code = error.code error.close() return code, body def test_health(self) -> None: """The health route answers with a status object.""" status, body = self.get("/health") self.assertEqual(status, 200) self.assertEqual(body, {"status": "ok"}) def test_stats(self) -> None: """The stats route returns the four numbers for the series.""" status, body = self.get("/stats?values=2,4,4,5") self.assertEqual(status, 200) self.assertEqual(body["n"], 4) self.assertAlmostEqual(body["mean"], 3.75, places=12) self.assertAlmostEqual(body["median"], 4.0, places=12) self.assertAlmostEqual(body["sd"], 1.2583057392117916, places=12) def test_bad_values_are_a_400(self) -> None: """A value that is not a number is a client error, not a crash.""" status, body = self.get("/stats?values=2,four,5") self.assertEqual(status, 400) self.assertIn("error", body) def test_unknown_route_is_a_404(self) -> None: """A path the service does not serve is a 404 with a JSON body.""" status, body = self.get("/nothing") self.assertEqual(status, 404) self.assertIn("error", body) if __name__ == "__main__": unittest.main()

python3 -m unittest -v test_service

test_bad_values_are_a_400 (test_service.ServiceTests.test_bad_values_are_a_400)
A value that is not a number is a client error, not a crash. ... ok
test_health (test_service.ServiceTests.test_health)
The health route answers with a status object. ... ok
test_stats (test_service.ServiceTests.test_stats)
The stats route returns the four numbers for the series. ... ok
test_unknown_route_is_a_404 (test_service.ServiceTests.test_unknown_route_is_a_404)
A path the service does not serve is a 404 with a JSON body. ... ok

----------------------------------------------------------------------
Ran 4 tests in 0.541s

OK

Port zero is the detail that makes this suite runnable on a build machine: two jobs can run it at once and neither picks 8000. shutdown() and server_close() in tearDownClass are what keep the process from hanging after the last test, and the thread is a daemon so that a failing test cannot leave it behind.

The HTTPError in get is closed before its body is used: an unclosed error response leaks a file object, and Python 3.14 warns about it. That warning is what the first version of this file printed, which is why the three lines are there.

What http.server is not

http.server is documented as not recommended for production: it speaks HTTP/1.0 in this configuration, has no TLS, no access control and no request limits, and its threading model is a thread per connection. For this project it is exactly right, because the point is to show the core behind a real socket with nothing installed; a production deployment puts the same handler behind a WSGI server or a reverse proxy, which is the next page's note about what is missing.

The Fortran part does not change when the server does. That is the property the boundary buys: the core is a library with a C interface, and whether the caller is a test, a WSGI server or a C++ program is a decision made outside it.

Exercises

  1. Add /quantile?values=...&q=0.9 to the service. Which function of the core does it call, and what does the wrapper do with a bad q?
  2. Make /stats answer 422 instead of 400 for a value that is not a number. Which line changes, and does the test still pass?
  3. Start two servers on port 0 in one process and print both ports. What does the pairing of port and thread have to be?
  4. Send a request with values= empty and one with no query at all. What does each return, and which branch of parse_values decides?

The programs on this page were built with GNU Fortran (Alpine 15.2.0) 15.2.0 and run with Python 3.14.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container. The requests were made with curl 8.14.1 in the same container.

Article author: Arthur Isaev