# HTTP

The Qualithm API is HTTPS only. A device calls it to exchange its claim code for a credential. Its
readings and commands run over [MQTT](https://docs.qualithm.com/mqtt.md).

## Find your API URL

_This part shows live data. See it at https://docs.qualithm.com/http._

This table is read from the [zones endpoint](https://docs.qualithm.com/api/zones.md) in this environment. Use the URL that
serves every zone. A zone's own URL reaches that zone only.

A device claims at the URL that serves every zone. The claim response names the URL of the device's
zone in `apiUrl`. The device sends its later requests there: its certificate request and its
renewals. Each renewal response names `apiUrl` too. Store it in place of the old one.

Use `apiUrl` only when it is an `https://` origin. A device without one sends its requests to the
URL it claimed at. When `apiUrl` gives no response or answers with a server error (5xx), send the
request once more to the URL the device claimed at. Treat any other error as final.

## Claim a device

A claim code (`qm_clm_…`) is a single-use code that adds one device to a
[scope](https://docs.qualithm.com/scopes.md#add-a-device-to-a-scope). The device sends it to the API URL and gets back its
credential. Send no API token:

```bash
curl -X POST "<your-api-url>/v1/provision/claim" \
  -H "Content-Type: application/json" \
  -d '{"code": "<your-claim-code>", "name": "Kitchen sensor"}'
```

The request body takes:

| Field     | Type    | Required | Description                                                                |
| --------- | ------- | -------- | -------------------------------------------------------------------------- |
| `code`    | string  | Yes      | The claim code, as issued.                                                 |
| `name`    | string  | No       | The device's name, up to 64 characters. Leave it out for a generated name. |
| `virtual` | boolean | No       | `true` when the device runs on a host rather than a board.                 |

A claim answers `201` with the new device in `data`:

```json
{
  "data": {
    "deviceId": "dvc_sgsina_01JAYQ4T7Z9K3M5N8P2R6S0V1W",
    "teamId": "tem_01JAYQ4T7Z9K3M5N8P2R6S0V1W",
    "scopeId": "scp_sgsina_01JAYQ4T7Z9K3M5N8P2R6S0V1W",
    "secret": "qm_dsk_…",
    "broker": { "host": "<gateway-host>", "port": 8883 },
    "apiUrl": "<zone-api-url>",
    "credential": {
      "id": "crd_sgsina_01JAYQ4T7Z9K3M5N8P2R6S0V1W",
      "deviceId": "dvc_sgsina_01JAYQ4T7Z9K3M5N8P2R6S0V1W",
      "authorityId": null,
      "kind": "token",
      "certFingerprint": null,
      "certSubject": null,
      "label": "",
      "status": "active",
      "expiresAt": "2026-11-25T09:30:00.000Z",
      "lastUsedAt": null,
      "rotatedFrom": null,
      "createdAt": "2026-10-26T09:30:00.000Z",
      "updatedAt": "2026-10-26T09:30:00.000Z"
    },
    "decisions": [
      {
        "key": "zone",
        "label": "Zone",
        "value": "Singapore (sg-sin-a)",
        "source": "scope",
        "docsUrl": "<docs-url>/zones"
      },
      {
        "key": "gateway",
        "label": "Gateway",
        "value": "<gateway-host>:8883",
        "source": "zone",
        "docsUrl": "<docs-url>/mqtt#find-your-gateway"
      },
      {
        "key": "credential",
        "label": "Credential",
        "value": "token",
        "source": "credential",
        "docsUrl": "<docs-url>/http#move-a-device-to-a-certificate"
      }
    ]
  }
}
```

- `deviceId` is the device's ID. It is the [MQTT](https://docs.qualithm.com/mqtt.md#connect-a-device) client ID and username.
- `secret` is the device's token: the MQTT password. The response is the only time you see it, so
  store it on the device.
- `broker` is the gateway for the device's zone. Connect to its `host` and `port`.
- `apiUrl` is the API URL for the device's zone. Send the device's certificate request and renewals
  there, as [Find your API URL](#find-your-api-url) describes.
- `credential` describes the token: its `id`, `kind` (`token`), `status` and `expiresAt`. It never
  holds the token itself. [Renew it](#renew-a-credential) before `expiresAt`.
- `decisions` is what the claim decided for you: at most six, each with its `value`, the `source` it
  was read from, and a `docsUrl` that explains the default. A claim that leaves out `name` also
  lists the name it generated.

A claim code works once. Once a claim succeeds, the same code returns `401`.

### When a claim fails

An error has the API's [error body](https://docs.qualithm.com/api.md#errors). Branch on its status and `code`:

| Status | `code`                | Cause                                                                             |
| ------ | --------------------- | --------------------------------------------------------------------------------- |
| `400`  | `bad_request`         | The body isn't a JSON object, the claim code is malformed, or `name` is too long. |
| `401`  | `unauthorized`        | The claim code is unknown, expired or already used. Ask for a new one.            |
| `429`  | `rate_limited`        | Too many claims from your address. Wait for `Retry-After` seconds.                |
| `500`  | `internal_error`      | The environment has no gateway for the scope's zone. Retry later.                 |
| `503`  | `backend_unavailable` | A backend is briefly unavailable. Wait for `Retry-After` seconds.                 |

A `400`, `429` or `500` leaves the code unused, so the device can retry with the same one.

## Move a device to a certificate

A token suits development. For production, the device swaps it for a client certificate whose key
never leaves its hardware. The device sends a certificate signing request (CSR) for that key to the
`apiUrl` from its claim, and authenticates with its device ID and token:

```bash
curl -X POST "<your-zone-api-url>/v1/provision/credentials/cert" \
  -u "<your-device-id>:<your-device-token>" \
  -H "Content-Type: application/json" \
  -d '{"csrPem": "<your-csr-pem>"}'
```

The body also takes an optional `label` and `expiresInDays`. The response's `data` holds the signed
`certificatePem`, the issuing `caCertificatePem`, the new `credential` (`kind` `cert`), the `broker`
to connect to and the `apiUrl` for its renewals. The certificate's subject is always the device ID,
whatever the CSR asks for. Connect with it as the [MQTT](https://docs.qualithm.com/mqtt.md#connect-a-device) page describes.

## Renew a credential

A device's token or certificate expires at the credential's `expiresAt`. Before then, the device
swaps it for a fresh one of the same kind at its [`apiUrl`](#find-your-api-url). Renew once two
thirds of the credential's lifetime has passed. The old credential stays valid until its own expiry,
so a device that loses the response can ask again. Once a credential expires, the device needs a new
claim code.

A token authenticates with its device ID and token, and sends no body:

```bash
curl -X POST "<your-zone-api-url>/v1/provision/credentials/renew" \
  -u "<your-device-id>:<your-device-token>"
```

The response's `data` holds the new token in `secret`, the new `credential`, the `broker` and the
`apiUrl`, as a [claim](#claim-a-device) does. Store `secret` in place of the old token, then
reconnect with it.

A certificate sends no `Authorization` header. It proves it holds its current key by signing a
request for a new one. Make the new key and its CSR:

```bash
openssl ecparam -name prime256v1 -genkey -noout -out next-key.pem
openssl req -new -key next-key.pem -subj "/CN=<your-device-id>" -out next.csr
```

Then sign `qualithm-renew-v1`, the current time and the CSR, one per line, with the current key. The
signature is ECDSA P-256 over SHA-256, as raw `r || s` in base64. Save this as `renew.mjs` next to
the device's current certificate (`device.crt`) and key (`device-key.pem`):

```js

const apiUrl = process.argv[2]
const certificatePem = readFileSync("device.crt", "utf8")
const csrPem = readFileSync("next.csr", "utf8")
const signedAt = new Date().toISOString()
const signature = sign("sha256", Buffer.from(`qualithm-renew-v1\n${signedAt}\n${csrPem}`), {
  key: readFileSync("device-key.pem", "utf8"),
  dsaEncoding: "ieee-p1363"
}).toString("base64")

const response = await fetch(`${apiUrl}/v1/provision/credentials/renew`, {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ certificatePem, csrPem, signedAt, signature })
})
console.log(response.status, await response.text())
```

```bash
node renew.mjs <your-zone-api-url>
```

The platform refuses a `signedAt` far from its own clock, so set the device's clock from NTP first.
The response's `data` holds the new `certificatePem`, the `caCertificatePem`, the new `credential`,
the `broker` and the `apiUrl`. Keep `next-key.pem` as the device's key from then on, with the new
certificate.

Store the `broker` and `apiUrl` from every renewal in place of the old ones.

### When a renewal fails

An error has the API's [error body](https://docs.qualithm.com/api.md#errors):

| Status | `code`         | Cause                                                                                                                      |
| ------ | -------------- | -------------------------------------------------------------------------------------------------------------------------- |
| `400`  | `bad_request`  | The CSR is unreadable or asks for the current key. Make a new key.                                                         |
| `401`  | `unauthorized` | The credential is unknown, revoked or expired, or the signature or `signedAt` is wrong. An expired one needs a claim code. |
| `409`  | `conflict`     | The credential never expires, or your own authority issued the certificate. Renew it with that authority.                  |
| `429`  | `rate_limited` | Too many renewals for the device. Wait for `Retry-After` seconds.                                                          |

## Manage devices and teams

The [API reference](https://docs.qualithm.com/api.md) lists every endpoint you call with an API token: devices, scopes,
automations, members and the rest. Each one shows its parameters, its response, its errors and a
`curl` command.

## See also

- [Devices guide](https://docs.qualithm.com/devices.md)
- [Zones](https://docs.qualithm.com/zones.md)
