Run an audit with the local HTTP API
Start Sonjoo on your computer, submit an audit with POST /api/runs, then poll by runId and read the finished report. The examples run in your terminal and use save: false to keep the audit out of history.
Start Sonjoo
Section titled “Start Sonjoo”Install Sonjoo and keep this terminal open while you run the examples.
sonjoo serve --no-openThe server binds to 127.0.0.1. The examples discover the port and token from its local connection file. For a reproducible example, start the fixture in a second terminal from the Sonjoo checkout.
python3 tests/fixtures/sites.py --port 18765Run any example in another terminal. Use the fixture URL below for the expected missing-title result. You can also pass an HTTP or HTTPS URL you have permission to audit.
Save this as audit-api.sh. It uses a POSIX shell, cURL and jq. The token is passed to cURL through its input configuration.
#!/bin/shset -eu
target=${1:?Pass the URL to audit}user_home=${HOME-${USERPROFILE-.}}data_home=${SONJOO_HOME-"${user_home:-.}/.sonjoo"}connection="${data_home:-.}/serve.json"port=$(jq -er '.port | select(type == "number" and . >= 1 and . <= 65535 and floor == .)' "$connection")token=$(jq -er '.token | select(type == "string" and test("^[A-Za-z0-9_-]+$"))' "$connection")base="http://127.0.0.1:$port"
request() { printf 'header = "X-Sonjoo-Token: %s"\n' "$token" | curl --disable --config - --fail --silent --show-error --max-time 5 "$@"}
body=$(jq -n --arg url "$target" '{url: $url, save: false, categories: ["core"]}')started=$(request -H 'Content-Type: application/json' --data "$body" "$base/api/runs")run_id=$(printf '%s' "$started" | jq -er '.runId | @uri')
deadline=$(($(date +%s) + 60))while [ "$(date +%s)" -lt "$deadline" ]; do state=$(request "$base/api/runs/$run_id") status=$(printf '%s' "$state" | jq -er '.status') case "$status" in complete) report=$(request "$base/api/runs/$run_id/result") printf '%s\n' "$report" | jq -ce ' .result.categoryResults[].results[] | select(.ruleId == "core-title-present") | {ruleId, status, pageUrl: .details.pageUrl, found: .details.found}' exit ;; running) sleep 1 ;; *) printf 'Run ended with status %s\n' "$status" >&2; exit 1 ;; esacdone
printf 'Timed out waiting for run %s\n' "$run_id" >&2exit 1sh audit-api.sh 'http://127.0.0.1:18765/healthy?remove-title=1'Node.js
Section titled “Node.js”Save this as audit.mjs and use Node.js 22 or later. It exports the audit function so the TypeScript example can use the same requests. All requests are directed to the local Sonjoo server.
import { readFile } from 'node:fs/promises';import { join } from 'node:path';import { setTimeout as delay } from 'node:timers/promises';import { pathToFileURL } from 'node:url';
export async function audit(url) { if (!url) throw new Error('Pass the URL to audit.');
const home = process.env.SONJOO_HOME ?? join(process.env.HOME ?? process.env.USERPROFILE ?? '.', '.sonjoo'); const { port, token } = JSON.parse(await readFile(join(home, 'serve.json'), 'utf8')); if (!Number.isInteger(port) || port < 1 || port > 65535 || typeof token !== 'string' || !token) { throw new Error('Invalid Sonjoo connection file.'); }
const base = `http://127.0.0.1:${port}`; async function request(path, data) { const response = await fetch(base + path, { method: data === undefined ? 'GET' : 'POST', headers: { 'X-Sonjoo-Token': token, ...(data === undefined ? {} : { 'Content-Type': 'application/json' }), }, body: data === undefined ? undefined : JSON.stringify(data), redirect: 'error', signal: AbortSignal.timeout(5000), }); const payload = await response.json(); if (!response.ok) { throw new Error(payload.error?.message ?? `Request failed with HTTP ${response.status}`); } return payload; }
const { runId } = await request('/api/runs', { url, save: false, categories: ['core'] }); const runPath = `/api/runs/${encodeURIComponent(runId)}`; const deadline = Date.now() + 60000;
while (Date.now() < deadline) { const state = await request(runPath); if (state.status === 'complete') return request(`${runPath}/result`); if (state.status !== 'running') { throw new Error(state.error?.message ?? `Run ended with status ${state.status}`); } await delay(500); } throw new Error(`Timed out waiting for run ${runId}`);}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { const { result } = await audit(process.argv[2]); const finding = result.categoryResults .flatMap((category) => category.results) .find(({ ruleId }) => ruleId === 'core-title-present'); if (!finding) throw new Error('The report did not include the title check.');
const { ruleId, status, details } = finding; console.log(JSON.stringify({ ruleId, status, pageUrl: details?.pageUrl, found: details?.found }));}node audit.mjs 'http://127.0.0.1:18765/healthy?remove-title=1'TypeScript
Section titled “TypeScript”Save this as audit.mts next to audit.mjs. The types describe the fields used by this example. Use Node.js 22.18 or later to run this file with built-in TypeScript support.
import { audit } from './audit.mjs';
type Finding = { ruleId: string; status: string; details?: { pageUrl?: string; found?: boolean };};
type AuditResult = { result: { categoryResults: { results: Finding[] }[] };};
const { result } = (await audit(process.argv[2])) as AuditResult;const finding = result.categoryResults .flatMap(({ results }) => results) .find(({ ruleId }) => ruleId === 'core-title-present');if (!finding) throw new Error('The report did not include the title check.');
const { ruleId, status, details } = finding;console.log(JSON.stringify({ ruleId, status, pageUrl: details?.pageUrl, found: details?.found }));node audit.mts 'http://127.0.0.1:18765/healthy?remove-title=1'Expected evidence
Section titled “Expected evidence”Each example prints this result for the fixture. A failed rule is evidence about the page. The audit request itself can still complete successfully.
{ "ruleId": "core-title-present", "status": "fail", "pageUrl": "http://127.0.0.1:18765/healthy?remove-title=1", "found": false}Next, learn how to read run states and finding coverage or look up an API route or error.
