Skip to content
Guides & References

Call an HTTP API from an SIE script

Two ways to read a REST API in an SIE script: curl and jq in Bash, or Python requests. Authentication, certificate checks and sorted output.

Script Integration EngineUpdated
On this page

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

Terminal window
sudo dnf install curl jq # RHEL family
sudo apt install curl jq # Ubuntu

The command

/bin/bash {script_path}curl-api.sh {device_ip} {device_password}

The script

curl-api.sh
#!/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" >&2

curl -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

Terminal window
sudo /opt/rconfig-sie/venv/bin/pip install requests

The command

/opt/rconfig-sie/venv/bin/python {script_path}requests-api.py {device_ip} {device_password}

The script

requests-api.py
#!/usr/bin/env python3
"""Minimal SIE script with requests: read a JSON config from a REST API.
Usage:
requests-api.py <host> <token>
"""
import json
import os
import 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 -S or sort_keys=True. API key order is not a promise.
  • Fail on HTTP errors. curl --fail and raise_for_status() turn a 401 or 500 into a failed run instead of a stored error page.
  • Check certificates. Point at a CA file in the keys folder for devices with private certificates. Never use curl -k or verify=False with a token.
  • Use a read-only token. A backup never needs to write.

Recipes that use HTTP APIs

Type to search.