<!-- https://predictabl.tech/docs/rest-api/ -->
# REST API

The Python library is a thin layer over this API; anything it does, you can do
over HTTP.

## Basics

| | |
|---|---|
| Base URL | `https://app.predictabl.tech/pub/v1` |
| Authentication | `Authorization: Bearer pk_...` ([get a token](https://predictabl.tech/docs/authentication/)) |
| Format | JSON in and out; uploads are `multipart/form-data` |

Every response has the same envelope:

```json
{"data": { ... }, "error": null}
```

```json
{"data": null, "error": {"code": "NOT_FOUND", "message": "Run not found", "details": null}}
```

Key and access problems answer `401` or `403` with `{"detail": "..."}` instead.
[All error codes](https://predictabl.tech/docs/errors-and-limits/).

The examples below use:

```bash
export P=https://app.predictabl.tech/pub/v1
export AUTH="Authorization: Bearer $PREDICTABL_API_KEY"
```

## Score with a trained model

Any token can do these, including a **Predictions only** one.

### List your models

```bash
curl -s "$P/runs?limit=50" -H "$AUTH"
```

Each item has `id`, `state` (`SUCCEEDED` when ready), `opportunity_title` (what it
predicts) and `headline_metric`. `GET /runs/{id}` adds `kind` and `meaning`, and
`GET /runs/{id}/results` the full test results.

### Score records

```bash
curl -s -X POST "$P/runs/$MODEL_ID/predict-records" -H "$AUTH" \
  -H "Content-Type: application/json" \
  -d '{"rows": [{"tenure": 2, "Contract": "Month-to-month", "MonthlyCharges": 89.1}]}'
```

```json
{"data": {"run_id": "...", "task": "binary_classification", "target": "churned",
          "meaning": "probability that customer churned",
          "count": 1, "predictions": [{"entity_id": "0", "prediction": 0.71}]},
 "error": null}
```

At most 1,000 rows per request. Send every column you know: left-out columns
count as unknown, which makes the score less reliable. A record without an id
column gets its position as `entity_id`.

### Score from your data

```bash
curl -s -X POST "$P/runs/$MODEL_ID/predict" -H "$AUTH" \
  -H "Content-Type: application/json" \
  -d '{"since": "2026-10-01", "until": "2026-10-31", "top": 100}'
```

| Field | |
|---|---|
| `top` | How many to return, highest first (default 200, at most 2,000) |
| `since`, `until` | Event models: a date window (`YYYY-MM-DD`, inclusive) |
| `since_days` | Event models: the last N days |
| `cutoff` | Forecast models: forecast as of this date instead of the latest data |
| `entity_contains` | Only entities whose id contains this text |
| `filters` | `[{"column": "city", "op": "eq", "value": "Milano"}]`; `op` is `eq`, `ne`, `in`, `contains`, `gt`, `gte`, `lt` or `lte` |
| `include` | Extra columns to return with each prediction, under `context` |
| `calibrated` | `true` for calibrated probabilities, where the model has a calibrator |
| `new_rows` | Rows to add to the model's data for this call only, by table: `{"orders": [{...}, ...]}`. For example the coming days of a forecast (promotions, holidays), or history newer than the database. Never saved |

To fill a form or a picker: `GET /runs/{id}/record-fields` lists the fields a
record needs (`required`, `optional`), and `GET /runs/{id}/entities` the
entity ids a model knows.

The response adds `kind`, `meaning`, `count` (all that matched) and `showing`;
forecasts add `as_of`; an empty event-model result adds a `note`. See
[Make predictions](https://predictabl.tech/docs/predictions/) for what each means.

## Build a model

These need a **Full access** token. Planning and training run in the
background: start them, then poll.

### 1. Connect your data

Files:

```bash
curl -s -X POST "$P/connections/from-csv" -H "$AUTH" \
  -F name="Telco customers" -F files=@telco.csv
```

Repeat `-F files=@...` for several tables.

Or a Postgres database (read-only user recommended), then start reading it:

```bash
curl -s -X POST "$P/connections" -H "$AUTH" -H "Content-Type: application/json" \
  -d '{"name": "Sales", "kind": "postgres", "config": {"dsn": "postgresql://readonly:pw@db.acme.com/sales"}}'
curl -s -X POST "$P/connections/$DATA_ID/introspect" -H "$AUTH"
```

Then poll until `status` is `ready` (or `error`):

```bash
curl -s "$P/connections" -H "$AUTH"
```

### 2. Ask the question

```bash
curl -s -X POST "$P/connections/$DATA_ID/opportunities" -H "$AUTH" \
  -H "Content-Type: application/json" \
  -d '{"mode": "single", "user_context": "Which customers will churn?"}'
```

The answer has a `job_id`. Poll `GET /connections/$DATA_ID/opportunities/job`
until that job's `state` is `done` (or `failed`, with a `message`), then take
the new question from `GET /connections/$DATA_ID/opportunities`.

### 3. Plan

```bash
curl -s -X POST "$P/opportunities/$QUESTION_ID/spec" -H "$AUTH" \
  -H "Content-Type: application/json" -d '{}'
```

Poll `GET /opportunities/$QUESTION_ID/spec` until `spec` is no longer `null`. If
planning failed, `GET /opportunities/$QUESTION_ID` has `last_generation_error`.
The plan's `id` is what you train.

To change it in plain words: `POST /opportunities/$QUESTION_ID/spec/refine` with
`{"message": "Don't use the support_tier column"}`, then poll for a higher
`version`.

### 4. Train

```bash
curl -s -X POST "$P/runs" -H "$AUTH" -H "Content-Type: application/json" \
  -d '{"spec_id": "'"$PLAN_ID"'", "preset": "full_quality"}'
```

`preset` is `full_quality` (default) or `fast_preview` (a quick check on a
sample). Poll `GET /runs/$MODEL_ID` until `state` is `SUCCEEDED`, `FAILED` (with
`error_code`, `error_message` and `suggestions`) or `CANCELLED`. Step-by-step
progress is at `GET /runs/$MODEL_ID/events.json`; `POST /runs/$MODEL_ID/cancel`
stops it.

## Your account

```bash
curl -s "$P/account" -H "$AUTH"
```

```json
{"data": {"email": "you@example.com", "plan": "...", "llm_source": "managed",
          "credits": {"balance": ..., "costs": {...}},
          "predictions_this_month": ..., "predictions_monthly_limit": ...,
          "models_kept": ..., "models_limit": ..., "schedules": ...}, "error": null}
```

## Polling

Poll every 2 to 5 seconds. Planning usually takes one to a few minutes;
training from seconds to tens of minutes, depending on the data. Requests time
out after 15 minutes, so never hold one open waiting: start the job, then poll.
