Send a Local API request
Connect to a Gardn Unix socket and correlate one JSON response.
Send a Local API request
This guide shows how to send a ping request from a local Unix script and read its JSON response. Use the gardn CLI when it already exposes the operation you need; direct socket access is for integrations that need the JSON contract.
Prerequisites
- A running persistent Gardn session on macOS or Linux.
- Python 3.
- The Local API socket path for that session.
To target a named session, start it with --session:
gardn --session workGet the socket path from gardn status --json and provide it to the script as GARDN_SOCKET_PATH.
Send ping
import json
import os
import socket
request = {
"id": "example:ping",
"method": "ping",
"params": {},
}
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as client:
client.connect(os.environ["GARDN_SOCKET_PATH"])
client.sendall(json.dumps(request, separators=(",", ":")).encode() + b"\n")
response_line = client.makefile("rb").readline()
if not response_line:
raise RuntimeError("Gardn closed the Local API connection without a response")
response = json.loads(response_line)
if response.get("id") != request["id"]:
raise RuntimeError("Local API response id did not match the request")
if "error" in response:
raise RuntimeError(f"{response['error']['code']}: {response['error']['message']}")
print(response["result"])The result identifies the running Gardn version, the interactive client protocol version, and any advertised server capabilities.
Keep the socket open for events
events.subscribe is the one Local API method that holds the connection open. Read the first response as the subscription acknowledgement, then keep reading for event lines. See events.subscribe for the stream lifecycle, and Error semantics for transport and streaming recovery.
Last updated on