
# API examples

Connect a program to Horizon: sign in, read, create, change. Every example
works today. Copy it, set your own address and key, and run it.

These are the calls Horizon's own web interface uses. They can change before
the versioned API `/v1` arrives, so check **What's new** after an update.

## 1. Create a key

You need the right to manage users.

1. Open **Configuration → Access → Service accounts** and create an account,
   for example "ERP connection".
2. Copy the client ID (`hzsvc_c_…`) and the secret (`hzsvc_s_…`). The secret is
   shown only once.
3. Give the account a group under **Groups and permissions**. Without one it
   sees nothing.
4. If the program should also write, the group needs the capability **May write
   with an access token (AI, API)**.

Put the values into your environment, together with the address you open Horizon
at. The examples read them from there:

```text
HORIZON_URL=https://…
CLIENT_ID=hzsvc_c_…
CLIENT_SECRET=hzsvc_s_…
```

## 2. Get a token

The program exchanges its key for a token. A token is valid for one hour.

```bash
TOKEN=$(curl -s "$HORIZON_URL/api/service-accounts/token" \
  -d grant_type=client_credentials \
  -d client_id="$CLIENT_ID" \
  -d client_secret="$CLIENT_SECRET" | sed 's/.*"access_token":"\([^"]*\)".*/\1/')
```

Every other call carries it in the header `Authorization: Bearer …`.

## 3. Read a list

All tickets with high or very high priority. The condition is written in
[HSL](hsl-expressions.html), like a filter in Horizon.

```bash
curl -s "$HORIZON_URL/api/list?type=ticket" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"filterText": "priority in [\"hoch\", \"sehr_hoch\"]"}'
```

The answer, shortened. `values` has the same order as `columns`:

```json
{
  "columns": [
    {"field": "reference", "label": "Referenz", "dataType": "AutoNumber"},
    {"field": "title", "label": "Titel", "dataType": "Text"},
    {"field": "priority", "label": "Priorität", "dataType": "Picklist"}
  ],
  "rows": [
    {"id": 1, "version": 4, "values": ["TKT-000001", "Notleuchte im Flur flackert", "hoch"]},
    {"id": 4, "version": 1, "values": ["TKT-000004", "Kältemaschine meldet Hochdruckstörung", "sehr_hoch"]}
  ],
  "hasMore": false
}
```

Which types and fields exist is listed in the data model. Your own fields are
in the answer of `GET /api/model`.

## 4. Read one record

```bash
curl -s "$HORIZON_URL/api/record?type=ticket&id=1" \
  -H "Authorization: Bearer $TOKEN"
```

Besides the values, the answer contains the `version` of the record and, under
`transitionOffers`, the state changes you may make now.

## 5. Create a ticket

```bash
curl -s "$HORIZON_URL/api/record/new" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: monitoring-2026-000123" \
  -d '{"objectType": "ticket", "fields": {"title": "Heating on floor 2 has failed", "priority": "hoch", "building": 1}}'
```

```json
{"created": true, "id": 12, "numbers": {"reference": "TKT-000012"}}
```

The `Idempotency-Key` protects you from duplicates. If the connection breaks
and your program sends the same request again with the same key, Horizon
answers with the same ticket and does not create a second one.

## 6. Change a record

Send the `version` you read. If someone changed the record in the meantime,
Horizon answers `409` and changes nothing. Read it again and decide.

This example reads the version first and then sets the priority:

```python
import json, os, urllib.parse, urllib.request

URL = os.environ["HORIZON_URL"]


def call(path, body=None, token=None, form=False):
    data, headers = None, {}
    if body is not None:
        data = (urllib.parse.urlencode(body) if form else json.dumps(body)).encode()
        headers["Content-Type"] = "application/x-www-form-urlencoded" if form else "application/json"
    if token:
        headers["Authorization"] = f"Bearer {token}"
    with urllib.request.urlopen(urllib.request.Request(URL + path, data, headers)) as answer:
        return json.load(answer)


token = call("/api/service-accounts/token", {
    "grant_type": "client_credentials",
    "client_id": os.environ["CLIENT_ID"],
    "client_secret": os.environ["CLIENT_SECRET"],
}, form=True)["access_token"]

ticket = call("/api/record?type=ticket&id=2", token=token)
saved = call("/api/record", {
    "objectType": "ticket",
    "id": ticket["id"],
    "version": ticket["version"],
    "fields": {"priority": "sehr_hoch"},
}, token=token)
print("saved, new version", saved["version"])
```

## 7. Change the state

A state is not a normal field. It follows the allowed transitions, and Horizon
runs the automations that belong to them. `seen` is the state you saw,
`to` the new one.

```text
POST /api/state
{"objectType": "ticket", "id": 12, "seen": "neu", "to": "zugewiesen"}

→ 200 {"id": 12, "from": "neu", "to": "zugewiesen", "kind": "transition", "version": 2}
```

## 8. Keep another system up to date

This program fetches every asset that changed since yesterday, page by page.
Run it once a day and your other system stays current.

```javascript
const url = process.env.HORIZON_URL

const { access_token: token } = await (await fetch(`${url}/api/service-accounts/token`, {
  method: 'POST',
  body: new URLSearchParams({
    grant_type: 'client_credentials',
    client_id: process.env.CLIENT_ID,
    client_secret: process.env.CLIENT_SECRET,
  }),
})).json()

const assets = []
let cursor = {}
while (cursor) {
  const query = new URLSearchParams({ type: 'asset', ...cursor })
  const answer = await fetch(`${url}/api/list?${query}`, {
    method: 'POST',
    headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
    body: JSON.stringify({ filterText: 'geaendertAm >= today() minus 1 calendar days' }),
  })
  if (!answer.ok) throw new Error(`${answer.status} ${await answer.text()}`)
  const page = await answer.json()
  const fields = page.columns.map((column) => column.field)
  for (const row of page.rows) {
    assets.push(Object.fromEntries(fields.map((field, i) => [field, row.values[i]])))
  }
  cursor = page.hasMore ? page.nextCursor : null
}
console.log(`${assets.length} assets, first: ${assets[0]?.reference} ${assets[0]?.name}`)
```

If you want to know at once instead of once a day, let Horizon call you: see
[Events](events.html).

## 9. When something goes wrong

Horizon answers with a sentence that says what is wrong:

| Status | Example | What to do |
|---|---|---|
| `400` | `Gemeint ist wohl ==` … with the position in your condition | Correct the request. |
| `401` | The token is missing, expired or revoked. | Get a new token. |
| `403` | `Über einen Zugangsschlüssel darfst du nur lesen.` | Give the group the capability **May write with an access token**. |
| `409` | `Inzwischen hat jemand anderes diesen Datensatz geändert` | Read the record again, then decide. |
| `429` | Too many token exchanges: 60 per hour. | Keep the token for its hour. |

Whatever your program does is in the activity of the record, with the name of
the service account.
