Script API¶
Everything you use from a routing script lives under the http namespace:
Import it that way. The module is siphon.http; the bare name http is the
standard library's package (http.client, http.server), which stays
importable from a script and from anything the script imports.
The namespace gives you three decorators for registering handlers —
@http.route, @http.middleware, @http.on_startup — and three objects your
handlers work with — http.Request, http.Response, and http.Client.
Handlers may be sync or async. Prefer async for anything that awaits I/O (an
outbound http.Client call, a cache lookup); it keeps the loop free.
Decorators¶
@http.route(path, methods=None, listeners=None)¶
Registers a handler for a route. The handler receives a single
Request and must return a Response —
returning anything else (including None) is a script error and produces a
500.
@http.route("/orders/{id}", methods=["GET", "DELETE"])
async def order(req):
oid = req.path_params["id"]
if req.method == "DELETE":
return http.Response(status=204)
return http.Response(
status=200,
headers={"Content-Type": "application/json"},
body=f'{{"id": "{oid}"}}'.encode(),
)
pathis a pattern with named segments:/users/{id}, or a catch-all/static/{*rest}. Params are extracted, URL-decoded, and exposed onreq.path_params.methodsis a list of HTTP method strings; the default is["GET"]. Methods are upper-cased for you. A route with several methods dispatches to the same handler — branch onreq.method.listenersis a list of listener names (servers[].nameinhttp.yaml, or thelistenvalue of an entry without a name). The route is served on those listeners only and answers404on any other. The default serves it on every listener. See Routes on one listener.
def or async def
A request runs through its middlewares and handler in one job on siphon's
Python executor. def stages run there, one after the other, and so does
an async def stage that never awaits. From the first stage that can
await, the rest of the chain runs as one coroutine on siphon's asyncio
pool, bounded by siphon's coroutine timeout, and holds no executor worker
while it waits. Awaiting I/O (http.Client, a cache lookup) is what
async def is for; a handler that does not await costs the same either
way.
@http.middleware¶
Registers a request guard. Middlewares run in registration order before the
matched route handler, each receiving the Request:
- Return a
Responseto short-circuit — the route handler is not called. - Return
Noneto continue to the next middleware (or the route handler).
@http.middleware
async def require_token(req):
if req.header("authorization") != "Bearer s3cr3t":
return http.Response(status=401, body=b"unauthorized")
return None # None → continue to the route handler
Typical uses: authentication, IP allow-listing, rate limiting, request logging.
Request guard, not a wrapper
Middleware today is a request guard — it runs before the route and can
only short-circuit. The wrap-around (req, call_next) form that also
rewrites the response is a roadmap item; until then, do
post-processing inside the route handler.
@http.on_startup¶
Registers a startup hook. It runs once, to completion, after the script loads and before any listener accepts. Use it to preload data, warm caches, or open shared clients.
No @http.on_shutdown yet
A script-level teardown hook (the counterpart to @http.on_startup) for
cleanup that must run in Python on the way down — deregister from a
service registry (e.g. a SIP gateway DELETE-ing itself from the trunk
registry), flush a
write buffer, close a pool opened at startup, release a lease, emit a final
metric. It can't just be a signal handler: Python's signal module only
works on the main thread and siphon runs handlers on worker threads, so a
script can't catch SIGTERM itself — only siphon can hand it a callback. On
the roadmap: it needs a siphon-side shutdown signal exposed to
addon tasks. Until then a registered handler is not invoked (the runtime
warns loudly rather than failing silently); do must-run-on-exit cleanup in
Rust or via your orchestrator (k8s preStop / grace period).
http.Request¶
The inbound request, passed as the only argument to handlers and middleware.
| Attribute | Type | Description |
|---|---|---|
method |
str |
"GET", "PUT", … |
path |
str |
Request path. |
path_params |
dict[str, str] |
Values extracted from the matched route, URL-decoded. |
query_params |
dict[str, str] |
Parsed query string. |
headers |
dict |
Lowercase-keyed headers. |
client |
str |
Remote address as "ip:port": the socket peer, or the left-most X-Forwarded-For entry when the socket peer is a trusted proxy. |
peer |
str |
The TCP peer of the connection as "ip:port". Never taken from a header, so it is the host that completed the TLS handshake even behind a trusted proxy. |
host |
str \| None |
The host the client addressed: the :authority of an HTTP/2 request, or else the Host header. An HTTP/2 request need not have a Host header, so read the name here. |
listener |
Listener |
The listener the request arrived on. See below. |
tls |
TlsInfo \| None |
The TLS session of the connection, None on a cleartext listener. See below. |
| Method | Returns | Description |
|---|---|---|
req.body() |
bytes |
The buffered request body. |
req.header(name) |
str \| None |
A single header, case-insensitive. |
@http.route("/items", methods=["GET"])
async def list_items(req):
limit = int(req.query_params.get("limit", "100"))
...
req.listener¶
| Attribute | Type | Description |
|---|---|---|
name |
str |
servers[].name, or the listen value of an entry without a name. |
address |
str |
The local end of the connection as "ip:port". On a listener bound to 0.0.0.0 this is the address the client reached. |
port |
int |
The local port. |
tls |
bool |
Whether the listener terminates TLS. |
req.tls¶
| Attribute | Type | Description |
|---|---|---|
version |
str |
"TLSv1.3" or "TLSv1.2". |
cipher_suite |
str |
The negotiated suite by its name in the IANA TLS Cipher Suite Registry, e.g. "TLS_AES_128_GCM_SHA256". |
cipher_suite_id |
int |
Its registry value, e.g. 0x1301. |
cipher_suite_bytes |
bytes |
The value as its two octets, e.g. b"\x13\x01". |
server_name |
str \| None |
The name the client asked for (SNI). |
alpn |
str \| None |
The negotiated application protocol, "h2" or "http/1.1"; None when the client offered none. |
peer_verified |
bool |
Whether the client presented a certificate chain that verified against the listener's client_ca. Always True on a listener with client_ca, False without. |
peer_certificate |
PeerCertificate \| None |
The client's own certificate. |
peer_certificates |
list[PeerCertificate] |
The chain as presented, the client's certificate first. |
A PeerCertificate has subject (an RFC 4514 string,
"CN=naf.example.com,O=Example,C=XX"), issuer (in the same form),
subject_alt_names (a list of
(kind, value) tuples with kind "dns", "uri", "email" or "ip"),
fingerprint_sha256 (64 lowercase hexadecimal digits) and der (the
certificate, bytes).
ALLOWED = {"naf.example.com"}
@http.route("/internal/keys", methods=["POST"], listeners=["internal"])
async def keys(req):
certificate = req.tls.peer_certificate if req.tls else None
names = {value for kind, value in certificate.subject_alt_names
if kind == "dns"} if certificate else set()
if not names & ALLOWED:
return http.Response(status=403)
suite = req.tls.cipher_suite_bytes # e.g. for a key bound to the suite
...
The subject and the alternative names are read from a certificate rustls has already verified; siphon-http compares nothing itself. Which names are allowed is the script's decision.
http.Response¶
The outbound response your handler returns.
| Parameter | Default | Description |
|---|---|---|
status |
200 |
HTTP status code. |
headers |
None |
Response headers as a dict. |
body |
None |
bytes or str (UTF-8 encoded). |
resp.headers is a mutable dict[str, str], created on its first read and
returned as the same dict on subsequent reads. Lookups are case-sensitive, as
with any Python dict. In-place changes (resp.headers["x"] = "y", del, and
update) affect the response sent by a handler. Assigning resp.headers = {...}
replaces the headers; previously returned dicts no longer affect the response.
Construction and assignment require string keys and values. If in-place mutation
leaves a non-string key or value, returning that response produces HTTP 500 and
logs the invalid header.
A Response also exposes a .body property and .raise_for_status() — most
useful on the responses you get back from an http.Client call.
http.Client¶
An outbound HTTP client wrapping a pooled reqwest::Client. Two construction
modes:
http.Client("api") # named — looks up clients.api in http.yaml
http.Client(base_url="https://example.com", # inline
verify="/path/ca.crt",
cert=("/path/c.crt", "/path/c.key"))
http.Client(resolve={"hooks.example.com": ["192.0.2.10:443"]}, # connect here, verify the name
redirects=False)
Named clients share the pool configured under clients.<name> in
http.yaml; prefer them for anything hot. Inline
clients are handy for one-offs.
Constructor keyword arguments:
| Argument | Description |
|---|---|
name |
Positional. Look up clients.<name> from config. |
base_url |
Base URL; relative request paths are joined onto it. |
verify |
Path to a CA bundle (every certificate in it) to verify the server certificate, beside the built-in roots. |
verify_only |
Trust verify only, not the built-in roots. |
cert |
Client-cert identity for mTLS — a combined PEM or a (cert, key) pair. |
timeout_ms |
Per-request timeout in milliseconds. |
http2_prior_knowledge |
Start cleartext connections in h2c. |
redirects |
Default None. False or 0 returns every 3xx as received; an int follows at most that many hops; True follows up to 10. Takes precedence over follow_redirects. |
resolve |
Default None. A dict of host name to an "IP:port" string or a list of them. Requests to that host connect to exactly those addresses and never use DNS, while the SNI, the certificate check and Host keep the host name (the port of the URL is used, not the one in the address). A malformed entry raises ValueError at construction. |
follow_redirects |
Default True. False returns a 3xx as received, Location included, instead of following it. |
All request methods are coroutines returning a Response:
| Method | Signature |
|---|---|
get |
await c.get(path, *, headers=None) |
post |
await c.post(path, *, body=None, headers=None) |
put |
await c.put(path, *, body=None, headers=None) |
patch |
await c.patch(path, *, body=None, headers=None) |
delete |
await c.delete(path, *, headers=None) |
The client supports the async with lifecycle (__aenter__ / __aexit__);
resp.raise_for_status() raises on a 4xx/5xx.
A note on state¶
Python handlers may run across threads (that is what lets siphon scale on free-threaded CPython). Keep mutable runtime state out of module globals — put it in Rust (a siphon primitive) or an external store. The REST API cookbook uses a process-local dict purely for illustration and calls this out.
Testing your scripts¶
You can unit-test HTTP scripts without binding a real listener. The
siphon-sip SDK (pip install
siphon-sip) mocks the http namespace — the @http.route / @http.middleware
/ @http.on_startup decorators and the Request / Response / Client types —
and ships an HttpTestHarness that dispatches mock requests through the
middleware chain into your route handlers. Outbound http.Client calls are
recorded and answered from canned responses, so a route that calls upstream is
testable in isolation:
from siphon_sdk.http_testing import HttpTestHarness
from siphon_sdk.http import MockResponse
def test_user_proxy():
harness = HttpTestHarness()
# canned upstream response for the outbound http.Client call
harness.add_response(MockResponse(status=200, body=b'{"name":"alice"}'))
harness.load_script("examples/rest_api.py")
resp = harness.request("GET", "/users/42")
assert resp.status == 200
# assert on what the script sent upstream
assert harness.sent_requests[0]["path"] == "/v1/users/42"
The mock also gives IDEs and LLMs the full type hints and docstrings for the
namespace, which helps when authoring scripts. It tracks this crate's runtime
surface — CI (scripts/check_sdk_parity.py) fails if they drift.
Roadmap¶
@http.on_shutdown— a script-level teardown hook run once on graceful shutdown (SIGTERM/SIGINT), the counterpart to@http.on_startup. For cleanup that must run in Python before the process exits: deregister from a service registry (a SIP gatewayDELETE-ing itself from the trunk registry — see the trunk registry example), flush a write buffer, close a pool opened at startup, release a lease, emit a final metric. It can't be a plain signal handler — Python'ssignalmodule only works on the main thread and siphon runs handlers on worker threads, so only siphon (which owns the signal) can hand the script a callback. Needs a siphon-side shutdown signal exposed to addon tasks; until then a registered handler is not invoked (the runtime warns loudly). Connection draining is separate — leave it to k8s readiness + grace period.- Response-rewriting middleware — the wrap-around
(req, call_next)form. Today middleware is a request guard; post-process inside the route handler. - Body streaming for large upload/download — v1 buffers whole bodies, capped.
- Live route reload on script hot-reload.