
# HZN-API-003 — REST API Cookbook

**Task-shaped recipes.** Each one answers a question someone actually asks —
*„how do I get the buildings out?"*, *„how do I create an asset?"*, *„how do I
load a spreadsheet a customer just sent me?"* — with a complete, runnable call.

Reference material lives in [HZN-API-002](guide.html); the binding rules
live in HZN-API-001. **This document repeats neither.** It
is the layer that generated documentation cannot produce: which calls, in which
order, with which values.

> **Language.** English, like the guide, per
> HZN-STD-001 §10 — public interface
> documentation.

---

## 0. Read this before you copy anything

**None of these calls work today.** The `/v1` API is designed, partly decided
and not yet built — see [HZN-API-002](guide.html) Appendix C for what the
running server actually serves and epic `E-005` for the gap. This cookbook is
written now so the shape can be reviewed before it is built, not so anyone can
integrate against it this week.

**How every recipe is laid out** — the same parts, always in this order:

| Part | | |
|---|---|---|
| **What it does** | one sentence | **always** |
| **Call** | method and path, placeholders in `{braces}` | **always** |
| **Where the values come from** | which recipe supplies each placeholder — never „look it up somewhere" | when there are placeholders |
| **Request** | real values, not `<string>` | when there is a body or a header worth showing |
| **Fields** | what may be sent, and what is required | when the body has choices |
| **Response** | the actual body, as text you can copy | **always** |

The three marked *always* are enforced by the build, together with their order
(§9). A recipe without a response would force the reader to run it to find out
what comes back — which is the one thing documentation exists to prevent.

That last point is deliberate. **Responses are never screenshots.** A picture of
a response cannot be copied, searched, read aloud or diffed, and it goes stale
without anyone noticing. This is the single clearest way documentation of this
kind decays, and it is worth a rule rather than a habit.

**Object type names.** The examples use the platform's core object types
(HZN-ADR-0087). Their technical names are
**not yet fixed in any document** — see §9, open point A-11. Whatever they end
up being, the reliable source is always your own tenant contract (Recipe 1).

**Common to every call:**

```
Authorization: Bearer <token>        ← Recipe 0
Accept: application/json
Accept-Language: de-DE               ← optional, localises messages
```

---

## Recipe 0 — Get a token

**What it does.** Exchanges an integration's client credentials for a bearer
token, valid one hour.

**Call**

```
POST /v1/oauth/token
```

**Where the values come from.** `client_id` and `client_secret` are issued once
when a tenant administrator creates the service account. The secret is shown
**once** and never again.

**Request**

```bash
curl -X POST https://api.horizon.mavorest.com/v1/oauth/token \
  -H 'Content-Type: application/x-www-form-urlencoded' \
  -d 'grant_type=client_credentials' \
  -d 'client_id=hzn_c_7f3a91d0' \
  -d 'client_secret=…' \
  -d 'scope=data.read data.write meta.read files'
```

**Response**

```json
{
  "access_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6…",
  "token_type": "Bearer",
  "expires_in": 3600,
  "scope": "data.read data.write meta.read files"
}
```

> **The tenant is not a parameter.** It is bound to the credential and cannot be
> chosen per call (HZN-ADR-0084 §C). A partner
> serving fifty customers holds fifty credentials.
>
> **A fresh service account may do nothing at all.** If your first read returns
> `403 PERMISSION_DENIED`, the fix is a role assignment in the tenant — not a
> flag on the request. There is no such flag.

---

## Recipe 1 — Find out what this tenant actually has

**What it does.** Lists the object types of *this* tenant, core and
customer-defined alike.

**Do this first, and do it again after every metadata-change event.** Customers
add object types and rename fields; an integration that hardcodes what it saw on
one screen breaks on the next tenant. This is the recipe every other recipe
depends on.

**Call**

```
GET /v1/meta/object-types
```

**Response**

```json
{
  "data": [
    { "name": "building",      "label": "Gebäude",     "namespace": "core",     "recordCount": 412 },
    { "name": "room",          "label": "Raum",        "namespace": "core",     "recordCount": 8140 },
    { "name": "asset",         "label": "Anlage",      "namespace": "core",     "recordCount": 21877 },
    { "name": "workOrder",     "label": "Auftrag",     "namespace": "core",     "recordCount": 128443 },
    { "name": "cleaningRound", "label": "Rundgang",    "namespace": "customer", "recordCount": 2210 }
  ]
}
```

`namespace` tells you where a type came from. **Never branch on it** — the paths
are identical for `core` and `customer`.

---

## Recipe 2 — Find out what a building looks like here

**What it does.** Returns the fields of one object type, with the three flags
that decide what you may do with each in a query.

**Call**

```
GET /v1/meta/object-types/{objectType}
```

**Where the values come from.** `{objectType}` — Recipe 1.

**Response** (abridged)

```json
{
  "name": "building",
  "label": "Gebäude",
  "fields": [
    { "name": "number",         "label": "Nummer",   "type": "AutoNumber", "readOnly": true, "filterable": true, "sortable": true },
    { "name": "name",           "label": "Name",     "type": "Text",       "required": true, "filterable": true, "sortable": true },
    { "name": "grossFloorArea", "label": "BGF",      "type": "Decimal",    "filterable": true, "sortable": true },
    { "name": "site",           "label": "Liegenschaft", "type": "Reference",
      "relationship": { "target": "site", "expandable": true }, "filterable": true }
  ]
}
```

| Flag | Meaning |
|---|---|
| `filterable` | may appear in `filter` |
| `sortable` | may appear in `sort` |
| `relationship.expandable` | may appear in `expand` |

**Using a field that is not flagged gives you `400`, not a slow query.** That is
the mechanism, not an inconvenience — see [HZN-API-002](guide.html) §1.

---

## Recipe 3 — Get a list of buildings

**What it does.** Reads buildings, newest first, with a chosen field set.

**Call**

```
GET /v1/data/building
```

**Where the values come from.** Field names — Recipe 2.

**Request**

```bash
curl -H "Authorization: Bearer $TOKEN" \
  'https://api.horizon.mavorest.com/v1/data/building?fields=number,name,grossFloorArea,site&sort=-createdAt&limit=50'
```

**Fields**

| Parameter | |
|---|---|
| `fields` | field selection; the default is a core set, **not everything** |
| `sort` | up to three sortable fields, `-` reverses |
| `limit` | default 50, maximum 500 |
| `cursor` | from `page.nextCursor` of the previous response |

**Response**

```json
{
  "data": [
    { "id": "018f2b41-9c0e-7a3b-b2d1-4e6a8c0f2b11",
      "number": "GEB-0042",
      "name": "Verwaltung Nord",
      "grossFloorArea": 4210.5,
      "site": { "id": "018f2b40-…", "number": "LI-0007", "label": "Campus Nord" } }
  ],
  "page": { "nextCursor": "eyJ0IjoiMjAyNi0wOC0xOFQwOTo0NDoxMloiLCJpIjoiMDE4ZjJiNDEifQ", "hasMore": true },
  "meta": { "objectType": "building", "fieldsOmitted": [] }
}
```

**Keep following `page.nextCursor` until `hasMore` is `false`.** There is no
`offset` and there will not be one. Treat the cursor as opaque.

`fieldsOmitted` names fields dropped because of **field rights** — that is how
you tell *„empty"* from *„not visible to you"*.

---

## Recipe 4 — Get the rooms of one building

**What it does.** Filters a child type by its parent reference.

**Call**

```
GET /v1/data/room?filter=building.id eq {buildingId}
```

**Where the values come from.** `{buildingId}` — Recipe 3.

**Request**

```bash
curl -H "Authorization: Bearer $TOKEN" \
  --get 'https://api.horizon.mavorest.com/v1/data/room' \
  --data-urlencode 'filter=building.id eq 018f2b41-9c0e-7a3b-b2d1-4e6a8c0f2b11' \
  --data-urlencode 'fields=number,name,floor,usableArea' \
  --data-urlencode 'sort=number'
```

> **Reference filters reach exactly one level.** `building.id` is fine;
> `building.site.name` is not, and returns `400 QUERY_TOO_COMPLEX`. Fetch the
> buildings of the site first, then their rooms.

**Response**

```json
{
  "data": [
    { "id": "018f2c10-…", "number": "R-3.14", "name": "Besprechung 3.14",
      "floor": { "id": "018f2bf0-…", "label": "3. OG" }, "usableArea": 28.4 }
  ],
  "page": { "nextCursor": null, "hasMore": false },
  "meta": { "objectType": "room", "fieldsOmitted": [] }
}
```

---

## Recipe 5 — Get the open work orders due this week

**What it does.** Combines a state filter with a date range — the single most
common query an integration makes.

**Call**

```
GET /v1/data/workOrder?filter=…&sort=dueDate
```

**Where the values come from.** State keys — Recipe 8 (the state model), or
simply read them off existing records.

**Request**

```bash
curl -H "Authorization: Bearer $TOKEN" \
  --get 'https://api.horizon.mavorest.com/v1/data/workOrder' \
  --data-urlencode 'filter=state in (open,inProgress) and dueDate between 2026-08-17 and 2026-08-23' \
  --data-urlencode 'fields=number,title,state,dueDate,assignee,asset' \
  --data-urlencode 'sort=dueDate' \
  --data-urlencode 'limit=200'
```

**Operators available:** `eq` · `ne` · `lt` · `le` · `gt` · `ge` · `in` ·
`notIn` · `contains` · `startsWith` · `isNull` · `between`. Combine with `and` /
`or`, parentheses allowed, **at most three levels deep**.

There are no free-form expressions, no subqueries and no aggregates. Aggregation
belongs to reports (Recipe 17).

**Response**

```json
{
  "data": [
    { "id": "018f2c1a-7b3e-7c9d-9f10-2a4b6c8d0e12",
      "number": "AU-2026-004711",
      "title": "Lüftungsanlage prüfen",
      "state": "inProgress",
      "dueDate": "2026-08-19",
      "assignee": { "id": "018f2a…", "label": "M. Jöne" },
      "asset": { "id": "018f2b…", "number": "AN-0042", "label": "RLT-3" } }
  ],
  "page": { "nextCursor": null, "hasMore": false },
  "meta": { "objectType": "workOrder", "fieldsOmitted": ["actualCost"] }
}
```

> **Want a total?** Add `count=exact`. It is not returned by default, it is
> capped, and it never counts records you may not see.

---

## Recipe 6 — Get one work order, and find out what you may do with it

**What it does.** Reads a single record together with the actions that are
permissible **for this record and this caller right now**.

**Call**

```
GET /v1/data/workOrder/{id}
```

**Where the values come from.** `{id}` — Recipe 5.

**Response** (abridged)

```json
{
  "id": "018f2c1a-7b3e-7c9d-9f10-2a4b6c8d0e12",
  "number": "AU-2026-004711",
  "state": "inProgress",
  "version": 7,
  "actions": [
    { "name": "complete", "label": "Abschließen",
      "input": [ { "name": "completionNote", "type": "LongText", "required": true },
                 { "name": "actualHours",    "type": "Decimal",  "required": false } ] },
    { "name": "cancel", "label": "Stornieren",
      "input": [ { "name": "reason", "type": "Picklist", "picklist": "cancelReason", "required": true } ] }
  ]
}
```

**Read `actions` instead of reimplementing the state machine.** The list already
accounts for permissions, licence class and workflow conditions — three things
your copy of the state model would not know about.

Keep `version`. Recipe 10 needs it.

---

## Recipe 7 — Create an asset

**What it does.** Creates one asset. **You assign the `id`; the server assigns
the `number`.**

**Call**

```
PUT /v1/data/asset/{clientGeneratedId}
```

**Where the values come from.** `{clientGeneratedId}` — generate a **time-ordered
UUID (v7)** yourself. Not v4: random ids destroy index locality at eight-figure
record counts. `assetCategory` and `room` — Recipes 1–4.

**Request**

```bash
curl -X PUT https://api.horizon.mavorest.com/v1/data/asset/018f3a02-4d11-7c6e-8a55-1b2c3d4e5f60 \
  -H "Authorization: Bearer $TOKEN" \
  -H 'Content-Type: application/json' \
  -H 'Idempotency-Key: erp-sync-2026-08-18-000431' \
  -d '{
        "name": "Lüftungsgerät RLT-3",
        "serialNumber": "SN-123456789",
        "manufacturer": "DTwin",
        "modelName": "X1",
        "assetCategory": { "id": "018f2a90-…" },
        "room": { "id": "018f2c10-…" },
        "purchaseDate": "2023-01-01",
        "purchaseValue": { "amount": "12500.0000", "currency": "EUR" }
      }'
```

**Fields**

| Field | Type | |
|---|---|---|
| `name` | `Text` | required |
| `serialNumber` | `Text` | optional |
| `assetCategory` | `Reference` | required by most configurations — check Recipe 2 |
| `room` | `Reference` | optional |
| `purchaseValue` | `Currency` | `{ "amount": …, "currency": … }`, ISO 4217 |
| `state` | — | **not writable.** Use an action (Recipe 11) |
| `number` | — | **not writable.** Assigned by the server |

**Response**

```json
{
  "id": "018f3a02-4d11-7c6e-8a55-1b2c3d4e5f60",
  "number": "AN-0518",
  "version": 1,
  "state": "active",
  "createdAt": "2026-08-18T09:44:12Z",
  "origin": "api"
}
```

> **Why `PUT` and not `POST`.** With a client-assigned id the call is idempotent
> by construction: a retry after a dropped connection re-addresses the same
> record instead of creating a second one. There is no `POST /v1/data/{type}` —
> exactly one way to create, and it is the one that is safe to retry.

---

## Recipe 8 — Create a ticket

**What it does.** Files a fault report from an external system — the classic
inbound integration.

**Call**

```
PUT /v1/data/ticket/{clientGeneratedId}
```

**Request**

```bash
curl -X PUT https://api.horizon.mavorest.com/v1/data/ticket/018f3a05-8e22-7b41-9c03-77aa1e2f4b90 \
  -H "Authorization: Bearer $TOKEN" \
  -H 'Content-Type: application/json' \
  -H 'Idempotency-Key: portal-2026-08-18-99823' \
  -d '{
        "title": "Heizung im Raum 3.14 kalt",
        "description": "Seit Montag früh keine Wärme.",
        "problemType": "heatingFault",
        "room": { "id": "018f2c10-…" },
        "reportedBy": { "id": "018f2a…" },
        "priority": "high"
      }'
```

**Response**

```json
{ "id": "018f3a05-8e22-7b41-9c03-77aa1e2f4b90", "number": "TI-2026-018820",
  "version": 1, "state": "new", "origin": "api" }
```

> **`problemType` and `priority` are picklist *keys*, not labels.** Labels are
> localised and customer-editable; keys are not. Fetch them with
> `GET /v1/meta/picklists/{name}`.

---

## Recipe 9 — Attach a photo

**What it does.** Uploads a file and links it to a record. **Three calls, never
base64 in the record.**

**Call**

```
POST /v1/files                  → register
…                               → chunked upload
POST /v1/files/{id}/complete    → finalise, virus scan starts
PATCH /v1/data/workOrder/{id}   → link
```

**Where the values come from.** `{id}` of the work order — Recipe 5.

**Request** — step 1

```bash
curl -X POST https://api.horizon.mavorest.com/v1/files \
  -H "Authorization: Bearer $TOKEN" \
  -H 'Content-Type: application/json' \
  -d '{ "filename": "rlt3-filter.jpg", "contentType": "image/jpeg", "size": 2317441 }'
```

**Response** — step 1

```json
{ "id": "018f3a11-…", "uploadUrl": "https://…", "chunkSize": 8388608, "state": "registered" }
```

**Then** transfer the bytes in chunks (resumable), and finalise:

```bash
curl -X POST https://api.horizon.mavorest.com/v1/files/018f3a11-…/complete \
  -H "Authorization: Bearer $TOKEN"
```

**Response** — after `complete`

```json
{ "id": "018f3a11-…", "state": "scanning" }
```

**Finally** link it:

```bash
curl -X PATCH https://api.horizon.mavorest.com/v1/data/workOrder/018f2c1a-… \
  -H "Authorization: Bearer $TOKEN" \
  -H 'If-Match: "7"' \
  -H 'Content-Type: application/json' \
  -d '{ "photo": { "fileId": "018f3a11-…" } }'
```

> **Between `complete` and `available` a download returns `409
> FILE_NOT_RELEASED`.** That is the quarantine working, not a bug in your code.
> The scan has **three** verdicts — clean, infected and *unknown* — and only
> `available` is delivered (HZN-ADR-0064).
> Poll `GET /v1/files/{id}` or wait for the event.

---

## Recipe 10 — Change a due date

**What it does.** Updates one field, safely, without overwriting someone else's
concurrent change.

**Call**

```
PATCH /v1/data/workOrder/{id}
If-Match: "{version}"
```

**Where the values come from.** `{id}` and `{version}` — Recipe 6.

**Request**

```bash
curl -X PATCH https://api.horizon.mavorest.com/v1/data/workOrder/018f2c1a-… \
  -H "Authorization: Bearer $TOKEN" \
  -H 'If-Match: "7"' \
  -H 'Content-Type: application/json' \
  -d '{ "dueDate": "2026-09-15" }'
```

Send **only** the fields you are changing.

**Response — the happy path**

```json
{ "id": "018f2c1a-…", "version": 8, "dueDate": "2026-09-15",
  "modifiedAt": "2026-08-18T10:02:55Z" }
```

**Response — somebody was faster**

```json
{
  "error": { "code": "VERSION_CONFLICT",
             "message": "Der Datensatz wurde zwischenzeitlich geändert.",
             "traceId": "018f3a20-…" },
  "current": { "id": "018f2c1a-…", "version": 9, "dueDate": "2026-09-08" },
  "conflicts": [ { "field": "dueDate", "yours": "2026-09-15", "theirs": "2026-09-08" } ]
}
```

You get the server state **with** the conflict, so you can merge field by field
instead of guessing. Omitting `If-Match` is `428`, not last-write-wins.

---

## Recipe 11 — Complete a work order

**What it does.** Moves a record through its state model. **This is the only way
a state changes.**

**Call**

```
POST /v1/data/workOrder/{id}/actions/complete
```

**Where the values come from.** The action name and its `input` schema — Recipe 6.

**Request**

```bash
curl -X POST https://api.horizon.mavorest.com/v1/data/workOrder/018f2c1a-…/actions/complete \
  -H "Authorization: Bearer $TOKEN" \
  -H 'Content-Type: application/json' \
  -H 'Idempotency-Key: mobile-2026-08-18-77120' \
  -d '{ "completionNote": "Filter getauscht, Messwerte im Rahmen.", "actualHours": 2.5 }'
```

**Response**

```json
{ "id": "018f2c1a-…", "state": "completed", "version": 9,
  "actions": [ { "name": "reopen", "label": "Wieder öffnen", "input": [] } ] }
```

> **`PATCH { "state": "completed" }` is rejected with `422
> STATE_FIELD_NOT_WRITABLE`.** Transitions are checked against the state model,
> start the workflow and write the audit trail. Going around them would go
> around all three.

---

## Recipe 12 — Import buildings from an ERP

**What it does.** Upserts up to 500 records in one call, keyed by **your**
identifiers, repeatable any number of times.

**Call**

```
POST /v1/data/building/batch
```

**Where the values come from.** `sourceSystem` — a name you choose once and keep
(`sap`, `navision`, `axxerion`). `externalKey` — your system's own id.

**Request**

```bash
curl -X POST https://api.horizon.mavorest.com/v1/data/building/batch \
  -H "Authorization: Bearer $TOKEN" \
  -H 'Content-Type: application/json' \
  -H 'Idempotency-Key: erp-nightly-2026-08-18-batch-12' \
  -d '{
        "sourceSystem": "sap",
        "operations": [
          { "op": "upsert", "externalKey": "BLD-4711",
            "data": { "name": "Verwaltung Nord", "grossFloorArea": 4210.5 } },
          { "op": "upsert", "externalKey": "BLD-4712",
            "data": { "name": "Lager Süd", "grossFloorArea": 980 } }
        ]
      }'
```

**Response — read every row**

```json
{
  "results": [
    { "index": 0, "status": 200, "id": "018f2b41-…", "created": false },
    { "index": 1, "status": 422, "error": { "code": "FIELD_VALIDATION_FAILED",
        "target": "grossFloorArea", "message": "Wert unterschreitet den zulässigen Bereich." } }
  ],
  "summary": { "total": 2, "succeeded": 1, "failed": 1 }
}
```

> **This is the mistake to avoid.** The HTTP status is `200` and one row failed.
> **Partial success is the normal case, not the exception**
> (HZN-ADR-0085 §B). An integration that
> checks only the status code will report a clean night and lose records
> silently. Read `results[]`, collect the failures, retry those.
>
> Correcting and re-sending converges: the successful rows do nothing the second
> time. That is what `externalKey` buys you.

---

## Recipe 13 — Import a spreadsheet a customer just sent you

**What it does.** Loads a file when there is **no source system at all** — the
self-registration case.

**The problem this solves.** A spreadsheet has no system id and no stable row
identifier. Sent without an external key, the import fails *silently*: the second
run creates everything a second time and reports success.

**Call**

```
PUT  /v1/data/importPlan/{clientGeneratedId}     ← declare the plan
POST /v1/import/jobs                             ← run it
```

**Request** — the plan

```bash
curl -X PUT https://api.horizon.mavorest.com/v1/data/importPlan/018f3b01-… \
  -H "Authorization: Bearer $TOKEN" \
  -H 'Content-Type: application/json' \
  -d '{
        "planKey": "bestand-2026",
        "targets": [
          { "objectType": "building", "keyRule": ["Gebäude"],
            "mapping": { "name": "Gebäude" } },
          { "objectType": "floor",    "keyRule": ["Gebäude", "Etage"],
            "mapping": { "name": "Etage" } },
          { "objectType": "room",     "keyRule": ["Gebäude", "Etage", "Raumnummer"],
            "mapping": { "number": "Raumnummer", "usableArea": "NF in m²" } }
        ]
      }'
```

**Response**

```json
{ "id": "018f3b01-…", "number": "IP-0003", "planKey": "bestand-2026",
  "version": 1, "state": "draft", "targets": 3 }
```

Each target names a **key rule** — the columns that identify a record. From it
comes the external key, and the source system is the plan itself:

```
PUT /v1/data/room/byExternalKey/import:bestand-2026/GEB-NORD~3~3.14
```

`import:<planKey>` is a source system like `sap` is, so Recipe 12 holds
unchanged.

> **A plan without a key rule cannot be started.** Not a warning, not a default —
> a rejection. The tempting substitute, the row number, is refused because it
> fails without a sound: the customer sorts the spreadsheet, and on the next run
> every record carries another record's data
> (HZN-ADR-0089 §C).

**One row becomes four records.** A row with the columns *Liegenschaft, Gebäude,
Etage, Raumnummer* produces operations along the whole chain. Two rows in the
same building produce the same upsert on the same external key, and the second
changes nothing — **deduplicating the parents is a consequence of the key rule,
not a feature you build**.

**Filling in the mapping** is where the platform's AI assists: it proposes the
column assignment from the header, at most 20 sample rows and the tenant's own
metadata model. **The run itself never sees a model**, and the plan is writable
by hand — so the import works without any AI service available.

---

## Recipe 14 — Try an import without writing anything

**What it does.** Runs every rule against the whole file and writes nothing.
**In a migration you will run this far more often than the real thing.**

**Call**

```
POST /v1/import/jobs
```

**Request**

```bash
curl -X POST https://api.horizon.mavorest.com/v1/import/jobs \
  -H "Authorization: Bearer $TOKEN" \
  -H 'Content-Type: application/json' \
  -d '{ "planId": "018f3b01-…", "fileId": "018f3b10-…", "mode": "upsert", "dryRun": true }'
```

```json
{ "id": "018f3b20-…", "status": "queued", "createdAt": "2026-08-18T10:15:02Z" }
```

**Then poll** — or subscribe to `import.job.finished` (Recipe 16):

```bash
curl -H "Authorization: Bearer $TOKEN" \
  https://api.horizon.mavorest.com/v1/import/jobs/018f3b20-…
```

**Response**

```json
{
  "id": "018f3b20-…",
  "status": "finished",
  "dryRun": true,
  "counts": { "read": 18422, "created": 1204, "updated": 17108, "unchanged": 0, "failed": 110 },
  "errorReport": { "fileId": "018f3b21-…", "format": "csv" },
  "startedAt": "2026-08-18T10:15:09Z",
  "finishedAt": "2026-08-18T10:21:44Z"
}
```

**The 110 failures are a file, not a JSON array** — download it with
`GET /v1/files/018f3b21-…/content`, hand it to whoever owns the data, get it
back corrected, run again. States are
`queued → running → finished | failed | cancelled`.

Cancelling a running job leaves already-written records in place. That is safe
precisely because the job is repeatable.

---

## Recipe 15 — Search across object types

**What it does.** Free-text search for humans typing words. For anything
structured, use Recipe 5.

**Call**

```
GET /v1/search?q=…&objectTypes=…
```

**Request**

```bash
curl -H "Authorization: Bearer $TOKEN" \
  --get 'https://api.horizon.mavorest.com/v1/search' \
  --data-urlencode 'q=Lüftung' \
  --data-urlencode 'objectTypes=workOrder,asset' \
  --data-urlencode 'limit=20'
```

**Response**

```json
{
  "data": [
    { "objectType": "asset",     "id": "018f2b…", "number": "AN-0042",
      "label": "RLT-3", "highlight": "…<em>Lüftung</em>sgerät RLT-3…" },
    { "objectType": "workOrder", "id": "018f2c1a-…", "number": "AU-2026-004711",
      "label": "Lüftungsanlage prüfen" }
  ],
  "page": { "nextCursor": null, "hasMore": false }
}
```

Results are filtered by your rights **at query time** — the index is not
pre-filtered per user. Search has its own quota bucket.

---

## Recipe 16 — Get told when something happens

**What it does.** Subscribes to business events instead of polling.

**Call**

```
PUT /v1/data/webhook/{clientGeneratedId}
```

**Request**

```bash
curl -X PUT https://api.horizon.mavorest.com/v1/data/webhook/018f3c01-… \
  -H "Authorization: Bearer $TOKEN" \
  -H 'Content-Type: application/json' \
  -d '{
        "url": "https://erp.example.com/hooks/horizon",
        "events": ["workOrder.completed", "workOrder.created", "import.job.finished"],
        "active": true
      }'
```

**Response** — what arrives at your endpoint

```json
{
  "event": "workOrder.completed",
  "occurredAt": "2026-08-18T10:31:07Z",
  "deliveryId": "018f3c10-…",
  "data": { "id": "018f2c1a-…", "number": "AU-2026-004711", "state": "completed" }
}
```

> **Three rules, and all three will bite you if you ignore them.**
>
> 1. **Delivery is at-least-once.** Your receiver **must** be idempotent — key
>    off `deliveryId`.
> 2. **Verify the signature** before you trust a single field.
> 3. **The payload is filtered by the recipient's rights**, so it may carry less
>    than you see in the UI. That is not a bug; fetch the record if you need more
>    and are entitled to it.
>
> Missed events are re-readable over a defined window.

---

## Recipe 17 — Run a report

**What it does.** Aggregation — the one thing the query syntax deliberately
cannot do.

**Call**

```
POST /v1/reports/{name}/runs
GET  /v1/reports/runs/{id}
```

**Request**

```bash
curl -X POST https://api.horizon.mavorest.com/v1/reports/maintenanceCostPerBuilding/runs \
  -H "Authorization: Bearer $TOKEN" \
  -H 'Content-Type: application/json' \
  -d '{ "parameters": { "from": "2026-01-01", "to": "2026-06-30" }, "format": "csv" }'
```

**Response**

```json
{ "id": "018f3d01-…", "status": "queued" }
```

Same job pattern as Recipe 14 — this is the general form for anything that
outlives a request, not an import speciality.

---

## Recipe 18 — Generate a client for one tenant

**What it does.** Produces a typed client with **this customer's** real field
names, without anyone writing a line per customer.

**Call**

```
GET /v1/openapi.json?tenant=current
```

**Why this is the recipe that replaces half a cookbook.** Horizon's object types
are per-tenant. A hand-written reference could never name a customer's own
fields — the tenant contract does, generated from metadata.

```bash
curl -H "Authorization: Bearer $TOKEN" \
  'https://api.horizon.mavorest.com/v1/openapi.json?tenant=current' \
  -o horizon-tenant.json
```

**Response.** An OpenAPI 3.1 document — the platform's endpoints, plus this
tenant's object types and fields as concrete schemas:

```json
{
  "openapi": "3.1.0",
  "info": { "title": "Horizon API — Mandant Musterverwaltung", "version": "1.0.0" },
  "paths": { "/v1/data/cleaningRound": { "get": { "…": "…" } } },
  "components": { "schemas": { "cleaningRound": { "type": "object", "properties": { "…": {} } } } }
}
```

Feed that to whatever generator you use. **Regenerate when you receive a
metadata-change event** — a customer adding a field changes *their* contract,
not our API version.

The core contract without tenant types is at `GET /v1/openapi.json`, the event
contract at `GET /v1/asyncapi.json`.

---

## 8. When something goes wrong

Every error has the same shape. **Branch on `code`, never on `message`.**

```json
{ "error": { "code": "FIELD_NOT_FILTERABLE",
             "message": "Das Feld „Bemerkung\" ist nicht filterbar.",
             "target": "remark",
             "traceId": "018f3a20-6c11-7f02-9e34-5b8d0a1c2e77" } }
```

| You see | It usually means |
|---|---|
| `403 PERMISSION_DENIED` | the service account has no role — Recipe 0 |
| `404` on a record you know exists | you may not see it; existence itself can be confidential |
| `400 FIELD_NOT_FILTERABLE` | the field is not flagged — Recipe 2 |
| `400 QUERY_TOO_COMPLEX` | more than one relationship level, or nesting past three |
| `409 VERSION_CONFLICT` | somebody was faster — Recipe 10 |
| `428 PRECONDITION_REQUIRED` | you forgot `If-Match` |
| `422 STATE_FIELD_NOT_WRITABLE` | use an action — Recipe 11 |
| `409 FILE_NOT_RELEASED` | still in quarantine — Recipe 9 |
| `429 QUOTA_EXCEEDED` | back off until the announced reset, do not retry tighter |

Quote `traceId` in support requests. It ties your call to our log.

---

## 9. How these examples are kept true

A recipe that has quietly stopped working is worse than no recipe: it costs an
integrator a day before they distrust the page.

**The rule.** Every request and response body in this document is a fenced JSON
block, never an image, and every one of them is meant to be **checked against
the generated contract in the build** — the same way `ApiContractTest` already
holds the server's JSON keys and `web/src/api.ts` to the same names.

**The honest limitation.** That check cannot exist yet, because the contract it
would validate against does not exist yet (`E-005`, §0). Until then these bodies
are reviewed prose, and they carry exactly as much authority as that. What can be
built before `E-005`, and should be:

1. every fenced `json` block in this file parses;
2. every `/v1/…` path form mentioned here also appears in
   [HZN-API-002](guide.html) — so a renamed endpoint cannot leave a recipe
   behind;
3. every recipe carries its mandatory parts from §0, in order;
4. **no image** appears in either document
   (HZN-ADR-0090 §F) — the
   rule aimed squarely at how documentation of this kind usually decays.

None of the four needs the API to exist. All four fail loudly when someone edits
one document and not the other. They live in `ApiDocConsistencyTest`.

---

## 10. Open points

| ID | Point | Status |
|----|-------|--------|
| A-11 | **The technical names of the 19 core object types are not fixed anywhere.** HZN-ADR-0087 settles the model in German labels; `ADR-0059` requires English identifiers. This document is the first to need them and uses `site`, `building`, `floor`, `room`, `area`, `asset`, `ticket`, `workOrder`, `maintenancePlan`, `contact`, `document`, `organisation`, `costCentre`, `orgUnit`, `team`, `sla`, `checklist`, `contract`, `address` — **proposed, not decided** | open — new here |
| A-12 | Webhook subscriptions are shown as an ordinary object type (`webhook`, Recipe 16). Whether subscriptions are records or an `/v1/admin` resource is not decided | open — new here |
| A-13 | Where this document is published, and under which domain | open — new here, see A-6 |

Everything else is tracked in [HZN-API-002](guide.html) Appendix D.

---

## Related documents

- [HZN-API-002](guide.html) — the reference this cookbook assumes
- HZN-API-001 — the binding conventions
- HZN-ADR-0084 · HZN-ADR-0085 · HZN-ADR-0089
- HZN-ADR-0087 — the 19 core object types
- HZN-ADR-0009 §B — the contract is generated, not written

---

*Project Horizon · mavorest GmbH*
