Examples
banshee/examples-collection/examples/api/
backup-jobs
Example: a REST API end to end, login, token in the cache, one state per backup job.
by banshee1 installation1 version
Published on October 27, 2026. First version in this collection.
// A REST API from end to end: log in once for a token, keep the token in the cache, read the list of the
// jobs of a backup server, and return one state per job.
need('protocol:http');
$user = need('protocol:http:user');
$password = need('protocol:http:password');
$base = variable('example:backup:url', 'text', array(
'label' => 'Address of the server',
'help' => 'For example https://backup.example.',
));
per('job', 'Jobs');
output('result', 'text', array('label' => 'Last result', 'per' => 'job'));
output('duration', 'number', array('label' => 'Duration of the last run', 'unit' => 'min', 'per' => 'job'));
watch.state('failed', 'Job failed', 'result', array('warning' => array('warning'), 'critical' => array('failed')));
watch.above('too-long', 'Job too long', 'duration', array('warning' => 240, 'enabled' => false));
// Log in. The account goes in Basic: the answer, {"token": "...", "expires_in": 3600}, is therefore not
// a secret by itself, but the token is. secret.mark keeps it out of every value and message; in the
// cache, a secret is kept encrypted on the poller. It is kept 50 minutes, under the hour it lives.
function login($base, $user, $password) {
$answer = http.post($base . '/api/v1/login', '', user=$user, password=$password);
if ($answer['status'] != 200) {
fail('misconfigured', 'Login refused, code ' . $answer['status']);
}
$session = json.read($answer['body']);
$token = secret.mark($session['token']);
cache.set('token', $token, 3000);
return $token;
}
if (cache.has('token')) {
$token = cache.get('token');
} else {
$token = login($base, $user, $password);
}
$answer = http.get($base . '/api/v1/jobs', headers=array('Authorization' => 'Bearer ' . $token));
// A token refused before its time, the server having restarted: log in again, once.
if ($answer['status'] == 401) {
$token = login($base, $user, $password);
$answer = http.get($base . '/api/v1/jobs', headers=array('Authorization' => 'Bearer ' . $token));
}
if ($answer['status'] != 200) {
fail('unreachable', 'Job list unreadable, code ' . $answer['status']);
}
// {"jobs": [{"name": "nightly-db", "last_result": "success", "last_duration": 812}, ...]}, in seconds.
$list = json.read($answer['body']);
foreach ($list['jobs'] as $job) {
value('result', $job['last_result'], $job['name']);
value('duration', number.round($job['last_duration'] / 60, 1), $job['name']);
}