Documentation menu
Python SDK API reference
Every Python metric, timing, argument, context and credential helper, with signatures and examples.
Select language Python (python). The operator must enable host interpreters
and allowlist Python. The RouteSpear SDK is already bundled with the script
plugin. Before each run the agent writes the module and sets PYTHONPATH
for that process. You do not install it with pip, copy SDK files or set an
environment variable on the machine. Python itself can be an enabled
managed runtime or an interpreter installed and
allowlisted by the host operator. The editor’s starter script
includes this import:
import routespear as rs
Python has the same six metric kinds and run/credential facilities as the
JavaScript SDK, using Python naming and keyword arguments. It exposes
boolean() rather than bool(), and a timed context manager rather than a
returned timer function. Its SDK does not currently provide rs.http, rs.dns
or rs.net; use Python’s standard library or packages installed on the host.
Common parameters and returns
name is a valid metric name. Numeric helpers convert
inputs to float; supply finite numbers. labels is a mapping whose keys and
values are converted to strings; omitted/empty labels are not emitted. Metric
emitters return None and immediately write and flush one JSON line to stdout.
They do not provide a success/failure result from the ingestion service.
| Method | Full signature | Behavior |
|---|---|---|
rs.emit |
emit(metric) |
Serialize a complete wire-format dict and flush it. No automatic field normalization or schema validation. |
rs.gauge |
gauge(name, value, unit="", labels=None) |
Emit a point-in-time scalar with the supplied unit. |
rs.counter |
counter(name, value, unit="count", labels=None, cumulative=False) |
Delta by default; cumulative=True marks an externally maintained running total. |
rs.duration |
duration(name, ms, labels=None) |
Emit elapsed milliseconds with kind duration, unit ms. |
rs.ratio |
ratio(name, value, labels=None) |
Emit a fraction with unit ratio; use 0–1. |
rs.boolean |
boolean(name, value, labels=None) |
Python truthiness becomes numeric 1/0, with unit bool. Pass a boolean deliberately; nonempty "false" is truthy. |
rs.distribution |
distribution(name, values, unit="", bounds=None, labels=None) |
Convert iterable values to floats, bucket them, and emit count/sum/min/max. Omitted/empty bounds select the standard buckets. |
rs.timed |
timed(name, labels=None) |
Context manager; emits a duration on leaving the block, including exceptional exits, and does not suppress the exception. |
All methods use the shared metric schema and budgets.
Helpers serialize values; the runtime validates emitted lines. For example,
float('nan') does not become a valid observation merely because Python can
serialize it.
Timing
with rs.timed("parse_ms", labels={"operation": "parse"}) as timer:
value = int("42")
elapsed_ms = timer.ms
timer.ms starts as None and is assigned elapsed milliseconds on exit.
Timing uses time.perf_counter(). If the block raises, a duration is still
emitted, but success must be measured separately. For manual timing, subtract
two time.perf_counter() values and multiply by 1000 before rs.duration.
Run helpers
| Method | Return | Empty/error behavior |
|---|---|---|
rs.args() |
Parsed JSON value | Reads stdin on first use; empty input returns {}. Invalid JSON raises a decoding error. Match your expected object/list/scalar shape. |
rs.context() |
Dict with agent, test, run |
Parses execution context; absent/malformed context falls back to empty sections and label dicts. Cached for the invocation. |
rs.target() |
String | Configured target, or "" outside a supplied target. |
rs.test_id() |
String | Check ID, or "". |
rs.timeout_ms() |
Integer | Supplied runtime budget in ms; absent/invalid numeric environment returns 0. It is a budget, not a live countdown. |
rs.secret(name) |
Credential value from the declared map | Cached file read. Undeclared/missing name raises KeyError; file or JSON errors propagate. |
See the full context schema and credential setup. The SDK does not read arbitrary shared secrets or provision a missing credential.
Complete metric example
This example processes explicit sample input so you can verify imports, args, labels and output without contacting a service. In a real check, replace the sample input with observations from the system you monitor.
Args: {"depth":12,"request_count":4,"samples_ms":[12,18,22]}.
import sys
import routespear as rs
settings = rs.args()
site = rs.context()["agent"]["labels"].get("site", "unknown")
labels = {"site": site}
with rs.timed("process_ms", labels=labels):
rs.gauge("queue_depth", settings["depth"], unit="count", labels=labels)
rs.counter("processed", settings["request_count"], labels=labels)
samples = settings["samples_ms"]
rs.distribution("sample_ms", samples, unit="ms", bounds=[10, 20, 50], labels=labels)
rs.boolean("within_limit", max(samples) < 50, labels=labels)
print("Processed supplied sample input", file=sys.stderr)
HTTP, DNS and TCP in Python
Use urllib.request/http.client, socket.getaddrinfo, or
socket.create_connection according to the task. Set finite timeouts and keep
the work inside the runtime budget. Python networking does not inherit the
built-in JavaScript engine’s policy-enforcing host API. Additional libraries
such as requests are not bundled with this SDK.
See a full authenticated Python HTTP example, including
rs.secret, elapsed milliseconds, status handling and safe logging.
Common mistakes
- Use
rs.boolean,rs.test_idandrs.timeout_ms; their JavaScript spellings are different. - Do not
print()diagnostic text to stdout. Usefile=sys.stderror logging configured for stderr. - Do not read stdin manually before
rs.args(). - Do not store a per-run counter in a module global and label it cumulative.
- Missing credentials and thrown exceptions do not mean a service was measured unhealthy; distinguish configuration failures from observed service results.
Source implementation: agent/plugins/script/internal/sdk/files/routespear.py.
These APIs describe the source shipped with this documentation, not a claim
that every deployed agent has the same version or interpreter configuration.