# API conventions

Every endpoint of the Qualithm API follows the rules on this page. The [API reference](https://docs.qualithm.com/api.md) gives
what each endpoint takes and returns. Every example starts at your [API URL](https://docs.qualithm.com/api.md#find-your-api-url)
and sends an [API token](https://docs.qualithm.com/api.md#authenticate).

## Build a path

Every path starts with the major version, `/v1`. A path to a team's resource names the team:

```text
/v1/teams/{teamId}/devices/{deviceId}
```

The API keeps no current team. Each request names the team it acts on, so the same request always
does the same thing. An API token is pinned to one team. A path that names another team answers
`404`, as if that team didn't exist.

A resource sits under its parent only when it can't exist without it: a device's credentials, an
automation's runs, a team's members. Paths nest at most two resources below the team.

```text
/v1/teams/{teamId}/devices/{deviceId}/credentials
/v1/teams/{teamId}/automations/{automationId}/runs
/v1/teams/{teamId}/members
```

A resource that can move is listed at team level, and you filter the list. A device can move between
scopes, so you read the devices in a scope with `scopeId`:

```text
/v1/teams/{teamId}/devices?scopeId={scopeId}
```

`/v1/teams/{teamId}/scopes/{scopeId}/devices` also includes the devices in every scope under it.

A few paths act for no team:

| Path                              | What it holds                                                    |
| --------------------------------- | ---------------------------------------------------------------- |
| `/v1/account/…`                   | Your own account, its settings and its team memberships.         |
| `/v1/teams`                       | The teams you belong to.                                         |
| `/v1/invites/…`                   | Accepting an invite to a team.                                   |
| `/v1/zones`, `/v1/known-problems` | Reference data, the same for every caller.                       |
| `/v1/shared/dashboard/…`          | One dashboard, read with a dashboard share link's token.         |
| `/v1/automations/trigger`         | An automation's inbound trigger, called with its trigger secret. |
| `/v1/provision/…`                 | The requests a device sends to [claim its credential](https://docs.qualithm.com/http.md).    |
| `/healthz`, `/openapi.json`       | Health and the OpenAPI document. They carry no version.          |

Path segments are kebab-case nouns, plural for a collection: `api-tokens`, `audit-events`. A path
parameter is named for its noun: `{deviceId}`, `{scopeId}`.

## Choose a method

| To                | Send     | The API answers                                |
| ----------------- | -------- | ---------------------------------------------- |
| Create a resource | `POST`   | `201` with the new resource                    |
| Read a resource   | `GET`    | `200` with the resource                        |
| Change a resource | `PATCH`  | `200` with the resource, or `204` with no body |
| Delete a resource | `DELETE` | `204` with no body                             |

Each endpoint's reference gives the status it answers.

`PATCH` takes only the fields you change. A field you leave out keeps its value. Where a field
accepts `null`, `null` clears it.

A state you can set is a field, not a route of its own. Turn an automation off with `enabled`:

```bash
curl -X PATCH "<your-api-url>/v1/teams/<your-team-id>/automations/<your-automation-id>" \
  -H "Authorization: Bearer <your-api-token>" \
  -H "Content-Type: application/json" \
  -d '{"enabled": false}'
```

Park a device the same way, with `{"parked": true}`.

Something that happens is a resource you create. `POST …/automations/{automationId}/runs` starts a
run, and `POST …/devices/{deviceId}/commands` sends a device a command. A run finishes later, so it
answers `202` with the run's `id`. Read a run's `status` from `GET …/runs`, and a command's from
`GET …/commands`.

An action route remains only for an operation that is neither a field nor a new resource. Its last
segment names the action:

```text
POST /v1/teams/{teamId}/devices/{deviceId}/credentials/{credentialId}/rotate
POST /v1/teams/{teamId}/billing/tier/preview
```

## Read an ID

Every ID is an opaque string: a three-letter kind, the zone code when the record belongs to one
zone, then a [ULID](https://github.com/ulid/spec). A ULID sorts by creation time.

```text
dvc_defraa_01JAYQ4T7Z9K3M5N8P2R6S0V1W   a device in de-fra-a
tem_01JAYQ4T7Z9K3M5N8P2R6S0V1W          a team, which belongs to no zone
```

The [API reference](https://docs.qualithm.com/api.md#ids) lists every kind. Store and compare IDs as whole strings. Never take
one apart.

An ID of the wrong kind answers `400`, naming the kind the endpoint expects. A scope ID sent where a
device ID belongs gets:

```json
{
  "message": "params.deviceId: expected a device ID (dvc_<zone>_…)",
  "code": "bad_request",
  "requestId": "0b6f0a4e-3d2c-4a51-9a7e-5c1f2e8d7b90",
  "details": [{ "field": "/params/deviceId", "message": "expected a device ID (dvc_<zone>_…)" }]
}
```

## Send and read JSON

Requests and responses are JSON with camelCase field names. A request body with a field the endpoint
doesn't define answers `400`, naming the field.

A success response holds the result in `data`:

```json
{
  "data": {
    "id": "scp_defraa_01JAYQ4T7Z9K3M5N8P2R6S0V1W",
    "teamId": "tem_01JAYQ4T7Z9K3M5N8P2R6S0V1W",
    "parentId": null,
    "name": "Warehouse",
    "zone": "de-fra-a",
    "createdAt": "2026-10-26T09:30:00.000Z",
    "updatedAt": "2026-10-26T09:30:00.000Z",
    "deviceTotal": 12
  }
}
```

`null` means a field has no value. Each type in the reference marks the fields every response
carries as required.

- **Time** is RFC 3339 in UTC, with milliseconds and `Z`, in a field ending `At`:
  `"createdAt": "2026-10-26T09:30:00.000Z"`. A month is `YYYY-MM` in a field named `month`. A
  telemetry bucket gives its start as `ts`, in milliseconds since 1970-01-01 UTC.
- **Durations and sizes** are integers with the unit in the field name: `retentionDays`,
  `bucketSeconds`.
- **Money** is an object: `amount` is an integer in the currency's minor units, such as cents, and
  `currency` is an ISO 4217 code. `{"amount": 4900, "currency": "USD"}` is 49.00 US dollars. An
  overage cap is the one exception: an integer number of cents in `capCents`.
- **Structured data** is a JSON object with its own type, never JSON text inside a string. An
  automation's `payload` holds its trigger and steps as objects.
- **Enums** are lowercase strings, such as a run's `status` of `"succeeded"`. New values can appear
  at any time. Treat a value you don't know as a fallback, never as an error.
- **Counts** are integers. **Booleans** name the state they describe: `enabled`, `parked`, `online`.
- A resource refers to another by ID: a scope's `parentId`, a device's `scopeId`. A related field is
  embedded only where every reader needs it, such as a device's `scopeName`.

## Handle an error

An error response has a stable `code` to branch on, a `message` that names what failed, and the
request's `requestId`. A request that fails validation adds `details`: each failed field as a JSON
pointer into the request, with its message.

```json
{
  "message": "query.cursor: is invalid",
  "code": "bad_request",
  "requestId": "0b6f0a4e-3d2c-4a51-9a7e-5c1f2e8d7b90",
  "details": [{ "field": "/query/cursor", "message": "is invalid" }]
}
```

Branch on `code`, never on `message`. New codes can appear at any time: treat one you don't know by
its status. The [API reference](https://docs.qualithm.com/api.md#errors) lists every code.

| Status | What it means                                                                                    |
| ------ | ------------------------------------------------------------------------------------------------ |
| `400`  | The request is malformed or invalid.                                                             |
| `401`  | The request carries no valid credential.                                                         |
| `403`  | The caller is known but lacks the permission.                                                    |
| `404`  | The resource doesn't exist or belongs to another team. The API never says which.                 |
| `409`  | The resource's current state conflicts with the request.                                         |
| `412`  | An `If-Match` version is out of date. See [Edit without overwriting](#edit-without-overwriting). |
| `429`  | Too many requests. See [Stay within rate limits](#stay-within-rate-limits).                      |
| `503`  | A backend is unavailable. Retry after the `Retry-After` header's seconds.                        |

Every response apart from a `304` carries a `Request-Id` header, and an error body repeats it as
`requestId`. Quote it when you ask for help. To trace a request through your own logs, send your own
`Request-Id` header, and the API uses it.

## Page through a list

Every list endpoint returns one page at a time, apart from `/v1/zones` and the automation template
lists, which return everything at once. `limit` sets the page size, 50 by default and 100 at most:

```bash
curl "<your-api-url>/v1/teams/<your-team-id>/devices?limit=100" \
  -H "Authorization: Bearer <your-api-token>"
```

A page holds `items` and `nextCursor`:

```json
{
  "data": {
    "items": [{ "id": "dvc_defraa_01JAYQ4T7Z9K3M5N8P2R6S0V1W", "name": "Kitchen sensor" }],
    "nextCursor": "eyJ2IjoxLCJsaXN0IjoibGlzdERldmljZXMi…"
  }
}
```

Send `nextCursor` back as `cursor` for the next page. `nextCursor` is `null` on the last page.

```bash
curl "<your-api-url>/v1/teams/<your-team-id>/devices?limit=100&cursor=<next-cursor>" \
  -H "Authorization: Bearer <your-api-token>"
```

A cursor stays valid while rows are added, so no row is skipped or read twice. A page carries no
page number and no total. A cursor from another list or another team answers `400`.

Each list's reference gives its order. Most lists are newest first, by `createdAt` then `id`.

Filters are query parameters named after the field they match, such as `scopeId` and `status`. A
time range is `from` (inclusive) to `to` (exclusive), both RFC 3339. Send the same filters with
every cursor.

## Retry without acting twice

Send an `Idempotency-Key` header with every `POST` that creates something or acts. Use a new random
value, such as a UUID, for each operation, and the same value for each retry of it:

```bash
curl -X POST "<your-api-url>/v1/teams/<your-team-id>/scopes" \
  -H "Authorization: Bearer <your-api-token>" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: <your-idempotency-key>" \
  -d '{"name": "Warehouse", "zone": "de-fra-a"}'
```

The API keeps the first response to a key for 24 hours:

- A retry with the same key and the same body, byte for byte, gets that response again, with
  `Idempotent-Replayed: true`. The request doesn't run twice.
- The same key with a different body answers `409` with `idempotency_mismatch`.
- A retry while the first request is still running answers `409` with `idempotency_in_flight`. Retry
  once it finishes.
- A `5xx` response isn't kept, so a retry runs the request again.

A key is from 1 to 255 characters. A key belongs to the team the request acts on, or to your account
on a path outside a team, or to the trigger secret on an automation trigger, and to its endpoint.
The same key on another endpoint is a new key. A `POST` sent without a key runs every time.

## Edit without overwriting

Automations, dashboards, devices, capabilities, scopes and teams each carry a version. A `GET` or
`PATCH` of one returns an `ETag` for that version. A capability has no `GET` of its own, so its
`ETag` comes from the response to a `PATCH` of it:

```bash
curl -i "<your-api-url>/v1/teams/<your-team-id>/scopes/<your-scope-id>" \
  -H "Authorization: Bearer <your-api-token>"
```

```text
ETag: W/"q3V7mXo1c9TfB2kR8nLp4a.Hk2vR9xLm0QpT4sZ"
```

Send it back as `If-Match` on a `PATCH` or `DELETE`. The change applies only if nobody changed the
resource since you read it:

```bash
curl -X PATCH "<your-api-url>/v1/teams/<your-team-id>/scopes/<your-scope-id>" \
  -H "Authorization: Bearer <your-api-token>" \
  -H "Content-Type: application/json" \
  -H 'If-Match: W/"q3V7mXo1c9TfB2kR8nLp4a.Hk2vR9xLm0QpT4sZ"' \
  -d '{"name": "Warehouse east"}'
```

When it changed, the API answers `412` with `precondition_failed` and changes nothing. Read the
resource again, apply your edit to what you read, and send it with the new `ETag`.

A request without `If-Match` isn't guarded: it applies whatever changed since you read the resource.
`If-Match: *` applies to whatever version exists.

`If-Match` checks only the resource's own fields. A field computed from other resources, such as a
scope's `deviceTotal`, can change, and an `If-Match` with your `ETag` still applies.

## Read only what changed

Every successful `GET`, apart from the event stream, carries an `ETag`. Send it back as
`If-None-Match`. When the response would be the same, the API answers `304` with no body:

```bash
curl -i "<your-api-url>/v1/teams/<your-team-id>/devices" \
  -H "Authorization: Bearer <your-api-token>" \
  -H 'If-None-Match: <etag-you-read>'
```

Send the `ETag` exactly as you received it, quotes and `W/` included. A `304` carries the `ETag`,
but no `Request-Id` or rate-limit headers.

A `304` means the whole response is unchanged, computed fields and your own permissions included.
The `ETag` from a `PATCH` covers only the version. Revalidate with the `ETag` from a `GET`.

## Keep working as the API changes

These changes ship at any time, within `/v1`:

- a new endpoint
- a new optional request field
- a new response field
- a new enum value
- a new error code

Ignore response fields you don't know, and treat an unknown enum value or error code as a fallback.
A change that would break a working client ships only in a new major version, such as `/v2`. The old
version keeps working through a deprecation period, announced in the `Deprecation` and `Sunset`
headers of its responses.

## Stay within rate limits

Every response apart from a `304` carries the `RateLimit` and `RateLimit-Policy` headers.
`RateLimit` gives the window's limit, the requests left in it, and `reset`, the seconds until it
starts again. `RateLimit-Policy` gives the limit and the window's size. A `429` adds `Retry-After`,
the seconds to wait before you retry. The [API reference](https://docs.qualithm.com/api.md#rate-limits) gives the format of
each.

An authenticated response carries `Cache-Control: no-store`, so no cache keeps a copy of it.

## Stream live events

`GET /v1/teams/{teamId}/events` streams the team's live events as
[server-sent events](https://html.spec.whatwg.org/multipage/server-sent-events.html):

```bash
curl -N "<your-api-url>/v1/teams/<your-team-id>/events" \
  -H "Authorization: Bearer <your-api-token>" \
  -H "Accept: text/event-stream"
```

Send `Accept: text/event-stream`. Without it, the API answers `406` with `not_acceptable`.

The server closes a stream from time to time. Reconnect when it does, and send the last event's ID
as `Last-Event-ID` so event IDs carry on from it. Events sent while you were disconnected aren't
replayed, so read the state you need again after you reconnect.

## See also

- [API reference](https://docs.qualithm.com/api.md)
- [HTTP](https://docs.qualithm.com/http.md)
