Call the rConfig API from Python
Python with the requests library is the easiest way to build anything more than a one-off call. This page gives a small client module you can copy into a project: it sends the token, follows pages, and turns HTTP errors into messages that say what went wrong.
Set it up
python3 -m venv .venv. .venv/bin/activatepip install requestsGive the script its address and token from the environment or your secrets manager, never in the code:
export RCONFIG_URL=https://rconfig.example.comexport RCONFIG_TOKEN=... # from your secrets managerThe client
"""A small client for the rConfig REST API."""
import os
import requests
class RconfigError(Exception): pass
class Rconfig: def __init__(self, url=None, token=None, timeout=30, verify=True): self.base = (url or os.environ["RCONFIG_URL"]).rstrip("/") + "/api" self.timeout = timeout self.session = requests.Session() self.session.headers.update({ "apitoken": token or os.environ["RCONFIG_TOKEN"], # not Authorization: Bearer "Accept": "application/json", }) self.session.verify = verify # True, or the path to your CA bundle
def request(self, method, path, **kwargs): response = self.session.request(method, f"{self.base}/{path.lstrip('/')}", timeout=self.timeout, **kwargs) if response.status_code == 401: raise RconfigError("401: token missing, wrong or created before V8.4.0") if response.status_code == 403: raise RconfigError(f"403 on {path}: the token lacks the ability this endpoint needs") if response.status_code == 404: raise RconfigError(f"404 on {path}: not found, or not visible to the token's owner") if response.status_code == 422: raise RconfigError(f"422 on {path}: {response.text}") response.raise_for_status() return response
def get(self, path, **params): return self.request("GET", path, params=params).json()
def post(self, path, json=None): return self.request("POST", path, json=json).json()
def pages(self, path, page_param="per_page", **params): """Yield every item from a paged v2 list, following every page.""" page = 1 while True: body = self.get(path, **{page_param: 100, "page": page, **params}) yield from body["data"] if body.get("next_page_url") is None: return page += 1
def test(self): """Check the token works. Needs no ability.""" return self.get("v2/apitest")Using it
from rconfig_client import Rconfig, RconfigError
rc = Rconfig()
try: rc.test()
# One device, without its stored credentials device = rc.get("v2/devices/12", with_credentials="false") print(device["device_name"], device["last_backup_status"], device["last_backup_at"])
# Every device, all pages for d in rc.pages("v2/devices", with_credentials="false"): print(d["id"], d["device_name"])
# Configs use perPage, not per_page for c in rc.pages("v2/configs", page_param="perPage", **{"filter[device_id]": 12}): print(c["id"], c["command"], c["created_at"])
except RconfigError as exc: raise SystemExit(f"rConfig API: {exc}")Habits that matter
- One
Session. It reuses the connection and keeps the token in one place. - A timeout on every request.
requestswaits forever by default. - Follow every page.
pages()does it for you; a plainget()on a list returns only the first page. - Check certificates. Pass
verify="/path/to/ca.pem"for an internal CA. Neververify=Falsewith a token.