Skip to content

REST API

Claude edited this page Nov 12, 2026 · 4 revisions

Checked against v0.7.6 on November 13, 2026.

REST API

Kestrel's web app is a FastAPI application (kestrel/web/app.py, build_app). Its JSON endpoints are what the tray, the scripts you write and the MCP server's equivalents share with the UI. Related pages: CLI reference, MCP server.

No endpoint submits an application, sends an email or message, or posts anywhere on your behalf. The routes that start work only queue it: their docstrings say "Queues only" or "Only enqueues" (kestrel/web/routes_control.py), and POST /api/opportunities/ingest reads a page you hand it and never crawls (kestrel/web/routes_api.py).

What the server exposes

The server has 27 JSON endpoints (/health and 26 under /api), documented below. Every other route returns HTML for the app's own pages and HTMX fragments and is not a stable API.

The JSON endpoints live in three files: kestrel/web/routes_api.py, kestrel/web/routes_control.py and kestrel/web/routes_learning.py. The HTML routes are in kestrel/web/routes_pages.py and kestrel/web/pages/*.py.

FastAPI's generated documentation is on: /docs (Swagger UI), /redoc and /openapi.json (FastAPI(..., docs_url="/docs") in app.py). The JSON handlers return plain dicts without response models, so the schema describes paths and methods but not response bodies.

Base URL and starting the server

The desktop app and kestrel serve run this server on 127.0.0.1, or on all interfaces when LAN access (server.bind_all) is on. It takes the first free port from 8765 to 8774 and falls back to an OS-assigned port if all ten are taken (kestrel/web/serve.py, PORT_LADDER). The chosen port is written to runtime.json in the data folder:

{"port": 8765, "pid": 12345}
uv run kestrel serve --no-open
curl http://127.0.0.1:8765/health

GET /health returns {"status":"ok","service":"kestrel","version":"0.7.0"}, with the version of the build you run. Use it as the readiness check. It needs no key and exposes only those three fields. The service field is the identity marker that the browser extension checks before it sends anything to a port.

Access control

There are no accounts and no API keys for a script on the same machine. Four controls apply to requests, all in kestrel/web/app.py and kestrel/web/auth.py:

Control Effect
Host check (TrustedHostMiddleware) A request whose Host header is not 127.0.0.1, localhost or [::1] gets 400 Invalid host header. This blocks DNS rebinding. When LAN access is on (server.bind_all), the allowed names become the addresses this machine answers on, never any name. A tunnel hostname listed in server.public_hostnames is also allowed.
Cross-origin guard A state-changing request (any method except GET, HEAD and OPTIONS, plus the state-changing GET /renders/new) that carries an Origin header from another site gets 403 {"detail":"cross-origin request refused"}. A request with no Origin and no Sec-Fetch-Site header, such as curl or a script, is treated as non-browser and let through.
Extension key A request whose Origin is a browser-extension scheme (chrome-extension, moz-extension, safari-web-extension) must carry the shared secret in an X-Kestrel-Key header, even on loopback. It gets 403 with an explanation when Kestrel has no secret yet or the header is missing or wrong. The scheme alone is not trusted, because it would trust every installed extension that has a localhost permission.
LAN shared key A request from a non-loopback address must carry the same secret, as the X-Kestrel-Key header or the kestrel_key cookie that GET /auth?key=... sets, or it gets 401. It fails closed: with no secret generated, every off-machine request is refused. /health and /auth are exempt. Loopback callers are exempt.

The secret is generated and rotated under Settings, LAN. Scripts on the same machine therefore need nothing extra. A script that sets its own Origin header to a non-loopback site will be refused, and one that sends an extension Origin must also send the key.

Conventions

  • Request bodies are JSON (Content-Type: application/json). POST /api/opportunities/{opp_id}/override and POST /api/learning/label also accept form data.
  • Errors from the JSON handlers are {"error": "<message>"} with a 400, 404 or 422 status. The run queue returns {"queued": false, "reason": "..."}. The guards above return {"detail": "..."}.
  • Pagination on GET /api/opportunities uses page and page_size (default 50, clamped to 1 to 200). There are no cursors.
  • Tracks are employment and consulting. Endpoints that depend on a track read ?track=, then the kestrel-track cookie, then fall back to the first enabled track (kestrel/web/deps.py, active_track).
  • Confidential mode applies. When it is on, GET /api/opportunities and GET /api/opportunities/{opp_id} replace your current employer's name with a placeholder, exactly as the UI does (kestrel/web/redact.py).
  • IDs are integers. A non-integer id returns FastAPI's standard 422 body. An id too large for SQLite's 64-bit integer returns 404 {"detail":"not found"} from a handler in app.py.

Opportunities

GET /api/opportunities

List the pipeline. Query parameters, all optional:

Parameter Meaning
track employment or consulting.
stage A stage such as new, t0_reject, t1_pass, t2_done, t3_done, error, quarantined. The full list is STAGES in kestrel/db/enums.py.
verdict One of apply, pursue, consider, pass, keep, kill.
score_min, score_max Numeric bounds on the Tier 2 score.
org Case-insensitive substring of the organization name.
source Case-insensitive substring of the source name or kind.
q Case-insensitive substring of title or organization.
needs_review 1, true or on to keep only items flagged for review.
archived 1, true or on to include hidden items beside active ones.
hidden 1, true or on to list only hidden items.
ghost_min Minimum ghost score.
sort score (default), date, first_seen, pre_score or ghost. An unknown value falls back to score.
page, page_size Page number and size.
curl "http://127.0.0.1:8765/api/opportunities?track=employment&verdict=apply&page_size=10"
{
  "total": 1,
  "page": 1,
  "pages": 1,
  "page_size": 10,
  "rows": [
    {
      "id": 1,
      "track": "employment",
      "title": "Head of IT",
      "org": "Example Co",
      "source": "Manual capture (employment)",
      "stage": "new",
      "verdict": null,
      "score": null,
      "weighted_score": null,
      "needs_review": false,
      "ghost_score": 0.2,
      "pre_score": 0.0,
      "url": "https://example.com/j/1"
    }
  ]
}

GET /api/opportunities/{opp_id}

One opportunity with its latest evaluation. Returns id, title, org, track, stage, verdict, verdict_model, score, weighted_score, needs_review, dimensions, blockers, legitimacy, dedup_members (ids of duplicates) and override (your latest override, or null). The evaluation fields are null until the item has been scored. Returns 404 {"error":"not found"} for an unknown id.

POST /api/opportunities/ingest

Add one posting from a URL and/or the text of a page you are already reading. It enters the pipeline like any scraped posting. It reads only what you give it.

Body field Meaning
url Posting URL.
text Readable text of the page.
title, org_name Optional. The title is guessed from the text or URL if omitted.
track employment (default) or consulting. Anything else becomes employment.

At least one of url or text is required, otherwise 400 {"error":"provide a url or text"}. An invalid JSON body also returns 400. The response is {"id", "title", "stage", "track"}. Posting a URL that is already stored returns that record's id rather than creating a duplicate (kestrel/ingest/manual.py).

curl -X POST http://127.0.0.1:8765/api/opportunities/ingest \
  -H "Content-Type: application/json" \
  -d '{"url":"https://example.com/j/1","text":"Head of IT\nLead IT.","org_name":"Example Co"}'

POST /api/opportunities/lookup

Ask which URLs Kestrel already knows. This backs the browser extension's seen-badge, which calls it as a board's page changes, so it is one query however many URLs you send.

Body field Meaning
urls A list of posting URLs.

The response is an object keyed by each known URL, with {"id", "score", "verdict", "stage", "ghost_score"} as the value. score and verdict are null until the item has been scored, and a URL Kestrel does not know is simply absent. An invalid JSON body returns 400 {"error":"invalid JSON body"}. It reads only the database.

POST /api/opportunities/{opp_id}/override

Record your own verdict on an item. This writes a label that the learning loop trains on. It does not change anything outside Kestrel.

Body field Meaning
mode agree (default), adjust or override. agree records the system verdict and score as yours. adjust keeps the verdict and sets your score. override sets your verdict.
reason Required when mode is override, otherwise 400 override requires a reason.
operator_verdict One of apply, pursue, consider, pass, keep, kill. Anything else is 422.
operator_score Number. A non-numeric value is ignored.
fit A fit word instead of a verdict: strong fit, good fit, maybe or not a fit. Setting it forces mode to override, so reason is then required. An unknown word is 422.

The response is {"ok": true, "override": {"operator_verdict", "operator_score", "reason", "created_at", "fit_word"}}. An unknown opportunity id returns 404. If the request carries an HX-Request header, the endpoint returns an HTML fragment instead of JSON.

curl -X POST http://127.0.0.1:8765/api/opportunities/1/override \
  -H "Content-Type: application/json" \
  -d '{"mode":"override","operator_verdict":"pass","reason":"Scope is below director level"}'

Applications

GET /api/pursuits

A read-only list of your applications, so a script can update a tracker kept elsewhere (kestrel/services/pursuit_api.py). It changes nothing. Rows come in id order.

Parameter Meaning
track employment or consulting.
status An application status.
since An ISO date or time. Keeps applications whose last change is at or after it.
limit Rows per page, 100 by default and 500 at most. Not a whole number is 400.
cursor The next_cursor of the previous page.

The response is {"rows": [...], "next_cursor": ...}, with next_cursor null on the last page. Each row has id (the Kestrel ID, the same short opaque ID the applications export ends with, which says nothing about the role or company), role, company, source, applied_at (a date), status and last_change. The shared key rules apply as for the other /api routes, and Confidential mode hides your current employer in company and in the source name. A refused query returns 400 with {"error": ...} holding one of Kestrel's own sentences; the details go to the log, never to the response.

Runs and control

Method and path Purpose
GET /api/runs Run history: {"runs":[{id, name, track, status, started_at, finished_at, counts}]}.
GET /api/runs/active Live pipeline activity: {"tasks": {<type>: {<status>: n}}, "latest_run", "quarantined"}. Task types are t1, t2, embed and scrape.
GET /api/status One payload for the tray and the sidebar: version, paused, mode, settings_mode, pending_mode, next_run, loaded_model, activity, worker, model, scan, scan_state, hosted, balance, credit and counts. balance is the sidebar's balance line (kind, label, state) or null, and credit is a list of out-of-credit notices for any online provider currently on hold.
POST /api/run/now Queue the next worker cycle in mode (local or hosted, passed as a query parameter, default the saved mode). One-shot. Returns {"queued": true, "mode": ...}. An unknown mode or an unconfigured hosted mode is 400 with a reason. A race with the worker loop is 409.
POST /api/worker/pause Pause the worker. Returns {"paused": true}.
POST /api/worker/resume Resume the worker. Returns {"paused": false}.
POST /api/scan/now Enqueue the due source scrapes. Returns {"enqueued": n}. The worker does the fetching later.
POST /api/scan/cancel Cancel pending scrapes. A scrape already running finishes its current source, and the automatic scheduler holds off for an hour. Returns {"cancelled": n}.
curl -X POST "http://127.0.0.1:8765/api/run/now?mode=local"
curl -X POST http://127.0.0.1:8765/api/scan/now
curl http://127.0.0.1:8765/api/runs/active

Page-change recorder

Method and path Purpose
POST /api/diag/page Records how a page change in the desktop window went, as a page_change line in Kestrel's own log, so the diagnostics file carries it. Returns {"ok": true}.

The body holds the two in-app paths (to, came_from) and numbers only: vt (whether the cross-fade ran), ttfb_ms, reveal_ms, hidden, what the page being left saw (out_vt, out_anims, out_htmx, out_busy_ms), and for an in-place page change (inplace) how long the page took to arrive (fetch_ms) and to swap (swap_ms). Values are clamped before they are logged. Nothing about roles or the person is in it, and it never leaves the computer. The app's own pages call it; it is not meant for scripts.

Learning loop

These endpoints read the track from ?track= or the track cookie. They back the Calibrate page.

Method and path Purpose
GET /api/learning/queue The ten most uncertain items to label: {"track", "items":[{opportunity_id, title, score, weighted, verdict, uncertainty, components}]}.
POST /api/learning/label Record a label. Body: opportunity_id (required), score, verdict, rationale, track (default employment), source (default active_learning). Returns {"ok": true, "label_id": n}. 400 without an id, 404 for an unknown opportunity.
POST /api/learning/calibration/propose Compute a weight proposal. Returns {"proposed": false, "reason": "insufficient labeled examples"} when there is too little data (or when tuning to the person's taste is switched off in Settings), otherwise the proposal with id, n_samples, previous_weights, proposed_weights, cv_mae_previous and cv_mae_proposed.
POST /api/learning/calibration/{cal_id}/accept Apply a proposal. {"accepted": true}, or 404 {"accepted": false}.
POST /api/learning/calibration/{cal_id}/reject Reject a proposal. {"rejected": true}, or 404.
POST /api/learning/train Train the reranker for the track now, inside the request. Returns track, n_labeled, promoted, criteria, metrics, reason. The Calibrate page's button does not call this: it queues a durable train_reranker task instead (see Learning loop internals).
GET /api/learning/reranker {"active": false}, or {"active": true, "version", "n_samples", "metrics", "sklearn_version"}.
GET /api/learning/outcomes Outcome analysis by score band, with sample sizes. Bands with fewer than five observations are marked "insufficient": true.

Desktop shell helpers

These exist for the tray and the desktop window. Headless kestrel serve has no shell, so they return false.

Method and path Purpose
GET /api/updates/status {"available": bool, "version": str or null}. Whether a newer version is worth advertising now. Makes no network call.
POST /api/quit Ask the desktop shell to quit. Returns {"quitting": bool}, false without a shell.
POST /api/focus Ask the desktop shell to raise its window. Returns {"focused": bool}.

UI routes

The remaining routes render the app's own pages and HTMX fragments under prefixes such as /settings, /documents, /opportunities, /pursuits and /sources. They return HTML, change between releases and are not an API. Routers are listed in _PAGE_MODULES in kestrel/web/app.py. Three routes under /api/documents/import (/read, the bare path and /accept) return HTML for the resume import dialog. To import a resume from a script, use kestrel doc import (CLI reference).

Browser extension

The repository ships a Chrome and Edge extension in extension/ (Manifest V3, "Kestrel Capture", its own version 0.1.0, with its own README.md). It is a client of three routes on this page: GET /health to confirm that a port is Kestrel, POST /api/opportunities/ingest for the toolbar and right-click capture, and POST /api/opportunities/lookup for the seen-badge on a short list of job boards. It reads the page the person is already viewing and never crawls.

What the server requires of it follows from the access controls above. Its Origin is an extension scheme, so every state-changing request must carry the shared secret from Settings, LAN as X-Kestrel-Key. The extension probes ports 8765 to 8774, the same ladder as PORT_LADDER, and sends page content only to a port whose /health says "service":"kestrel". Nothing in packaging/ or the release workflow builds or publishes the extension, so it is loaded unpacked from a checkout. The server side is covered by tests/test_serve_discovery.py and tests/test_lan_auth.py. The extension's own JavaScript has no automated tests in the repository.

Testing against the API

The test suite uses Starlette's TestClient against build_app(worker=False) (tests/test_mcp.py shows the pattern). tests/conftest.py makes the client present itself as a loopback caller with a 127.0.0.1 host, because the Host check refuses the default testserver name. Tests never call a live job board or other external service.

Clone this wiki locally