Call an HTTP API from an SIE script
Most SIE scripts that don’t use SSH talk to a REST API. This page shows the same job two ways: curl with jq in a Bash script, which needs nothing beyond two common packages, and the Python requests library, which is easier once the logic grows. For APIs that one request can answer, API Collections needs no script at all.
curl and jq
Set it up
sudo dnf install curl jq # RHEL familysudo apt install curl jq # UbuntuThe command
/bin/bash {script_path}curl-api.sh {device_ip} {device_password}The script
#!/usr/bin/env bash## Minimal SIE script with curl and jq: read a JSON config from a REST API.## Usage: curl-api.sh <host> <token>
set -o pipefail
KEYS="/var/www/html/rconfig8/current/storage/app/rconfig/scripts/keys"
fail() { echo "ERROR: $1" >&2; exit 1; }
HOST="${1:-}"; TOKEN="${2:-}"[ -n "$HOST" ] && [ -n "$TOKEN" ] || fail "usage: curl-api.sh <host> <token>"
CA_ARGS=()[ -r "$KEYS/api-ca.pem" ] && CA_ARGS=(--cacert "$KEYS/api-ca.pem")
echo "fetching config from $HOST" >&2
# The token goes in a header read from stdin, so it isn't on curl's own command line.body=$(printf 'Authorization: Bearer %s\n' "$TOKEN" \ | curl --silent --show-error --fail --max-time 30 "${CA_ARGS[@]}" \ -H @- -H 'Accept: application/json' \ "https://$HOST/api/config") \ || fail "request to $HOST failed"
# -S sorts keys at every level, so API key order can't cause false changes.config=$(printf '%s' "$body" | jq -S .) || fail "$HOST did not return JSON"[ "$config" != "null" ] && [ "$config" != "{}" ] || fail "empty config, refusing to store it"
printf '%s\n' "$config"echo "SIE-OK: curl config from $HOST" >&2curl -H @- reads headers from stdin, which keeps the token out of the process list for curl itself. It is still an argument to the script, as every {device_password} value is.
Python requests
Set it up
sudo /opt/rconfig-sie/venv/bin/pip install requestsThe command
/opt/rconfig-sie/venv/bin/python {script_path}requests-api.py {device_ip} {device_password}The script
#!/usr/bin/env python3"""Minimal SIE script with requests: read a JSON config from a REST API.
Usage: requests-api.py <host> <token>"""
import jsonimport osimport sys
import requests
KEYS = "/var/www/html/rconfig8/current/storage/app/rconfig/scripts/keys"CA_FILE = f"{KEYS}/api-ca.pem"
def fail(message): print(f"ERROR: {message}", file=sys.stderr) sys.exit(1)
def main(): if len(sys.argv) < 3: fail("usage: requests-api.py <host> <token>") host, token = sys.argv[1], sys.argv[2]
session = requests.Session() session.headers.update({"Authorization": f"Bearer {token}", "Accept": "application/json"}) verify = CA_FILE if os.path.exists(CA_FILE) else True
print(f"fetching config from {host}", file=sys.stderr) try: response = session.get(f"https://{host}/api/config", timeout=30, verify=verify) response.raise_for_status() data = response.json() except requests.RequestException as exc: fail(f"request to {host} failed: {exc}") except ValueError: fail(f"{host} did not return JSON")
if not data: fail("empty config, refusing to store it")
json.dump(data, sys.stdout, indent=2, sort_keys=True) sys.stdout.write("\n") print(f"SIE-OK: requests config from {host}", file=sys.stderr) return 0
if __name__ == "__main__": sys.exit(main())Habits that matter with any HTTP API
- Sort keys before storing.
jq -Sorsort_keys=True. API key order is not a promise. - Fail on HTTP errors.
curl --failandraise_for_status()turn a401or500into a failed run instead of a stored error page. - Check certificates. Point at a CA file in the
keysfolder for devices with private certificates. Never usecurl -korverify=Falsewith a token. - Use a read-only token. A backup never needs to write.