# Pushing data into Mechbase

*Sending readings, syncing your asset tree, and running inspections from your own code.*

The analytics chapters pull data out of Mechbase. This one is the write side: how a **system integrator** pushes measurements in, keeps the asset registry in step with an upstream system, and drives an inspection from a script. Everything here uses the **Mechbase SDK** — a typed client that wraps the same API and carries the same Bearer token. The examples are Python; [Go, Swift, and Kotlin](#go-swift-and-kotlin) cover the same ground, with a few differences noted below.

If you only read one section, read **[Install and construct the client](#install-and-construct-the-client)** — every other recipe starts from the `inst` handle it builds.

## The one-paragraph version

Construct one `Mechbase` client with your API token, scope it to an installation with `for_installation(...)`, and you get a handle (`inst`) with a resource for each thing you can write:

- `inst.measurements` — push one reading (`create`) or many at once (`create_batch`).
- `inst.sections`, `inst.zones`, `inst.assets`, `inst.measurement_points` — the registry, each with an `upsert` keyed on your own external ID so a sync job is safe to re-run.
- `inst.routes` — start an inspection, respond to items, and complete it.

Every call goes to **one installation** and carries the **same Bearer token** you use for the read-only feeds in the [Analyst: Analytics & BI](analytics-bi.md) cookbook. Pick the recipe below.

> **The full API reference.** This chapter is a cookbook for the common write jobs. For the complete, always-current list of endpoints, parameters, and response shapes, browse the interactive API docs at [`app.mechbase.io/api/docs`](https://app.mechbase.io/api/docs) (a self-hosted Mechbase serves them at `<your-host>/api/docs`).

## Install and construct the client

Install the Python client:

```bash
pip install mechbase
```

Construct a client with your token. `token` is keyword-only and required; `base_url` defaults to the hosted service, so pass it only for a self-hosted installation. The client is a context manager — use `with` so it closes cleanly:

```python
from mechbase import Mechbase

with Mechbase(token="<TOKEN>") as client:     # base_url="https://mechbase.internal.acme.com" if self-hosted
    inst = client.for_installation(client.me().current_installation_id)
    # ... every recipe below runs against `inst`
```

What's happening here:

- **`Mechbase(token=...)`** — the token is sent as `Authorization: Bearer <TOKEN>` on every request. The default `base_url` is `https://app.mechbase.io`; there's also a `timeout` (seconds, default `30.0`).
- **`client.me()`** — reads the caller's profile from `GET /api/me/`. For a token scoped to one installation, its `current_installation_id` is that installation, so you don't have to hard-code the numeric ID. A token you minted yourself with `mechbase login` covers every installation you belong to; then `current_installation_id` is simply the first (and is empty if you belong to none) — so pass the ID you want straight to `for_installation(...)`.
- **`inst`** — an installation-scoped handle exposing `.assets`, `.measurement_points`, `.measurements`, `.routes`, `.sections`, and `.zones`. Everything below hangs off it.

> **Tip:** treat the token like a password. A Mechbase administrator creates it for you, scoped to your user and installation.

## Push one measurement

Send a single reading against a measurement point with `inst.measurements.create(...)`. `point_id` and `data` are required; all arguments are keyword-only, and the rest have defaults:

```python
m = inst.measurements.create(
    point_id=42,
    data={"rms": 2.3, "peak": 4.1},
    notes="hourly poll",
    idempotency_key="poll-2026-07-01T09:00Z-p42",
)
print(f"ok -> {m.uuid} sequence={m.point_sequence} status={m.status}")
```

The arguments:

- **`point_id`** — the numeric ID of the measurement point.
- **`data`** — a JSON object of the values you're recording (metric name to number).
- **`notes`** — a free-text note (default empty).
- **`session_id`** / **`timestamp`** — set these to group readings or to backdate a reading to when it was actually taken; when omitted, the server records the arrival time. A `timestamp` must carry its time zone (`2026-11-16T09:30:00Z` or `+02:00`); a bare local time is rejected with `422`.
- **`idempotency_key`** — sent as the `X-Idempotency-Key` header. Give each reading a stable key (as above) and a retry after a network blip won't create a duplicate. Reach for this whenever a poll loop might resend.
- **`file`** — pass a path or file object to attach a raw file; the call then multipart-POSTs to `/measurements/upload/` instead, with the JSON under a `payload` form field.

`create` returns a `Measurement` with `uuid`, `measurement_point_id`, `point_sequence` (the per-point running number — the same number as in the reading's web address), `data`, `status` (the resulting health state), `notes`, `created_at`, `external_id`, and `file_url`.

> **Note:** the raw API also accepts an `external_id` in the body of a single reading. With one, the write is idempotent on it: `201` the first time, `200` for a re-send, `409` if that external ID already belongs to a reading on another point. The Python `create()` exposes `idempotency_key` instead; use `create_batch` (below) to send external IDs.

## Batch upload, with result handling

Polling a hundred points one HTTP call at a time is slow. Send them together with `inst.measurements.create_batch(items)`, where `items` is a list of dicts. Reference the point by your own external ID and tag each row with an `external_id` so you can tie the outcome back to your source record:

```python
result = inst.measurements.create_batch([
    {"measurement_point_external_id": "PUMP-1-DE", "data": {"rms": 2.3}, "external_id": "r-1"},
    {"measurement_point_external_id": "PUMP-1-DE", "data": {"rms": 2.9}, "external_id": "r-2"},
])
print(f"created={result.created} duplicates={result.duplicates} errors={result.errors}")
```

`create_batch` returns a `BatchResult` with the headline counts — `created`, `duplicates`, `errors` — and a `results` list, one `BatchItemResult` per input row (in order). Each item carries `index`, `status`, `measurement_point_id`, `point_sequence`, `uuid`, your `external_id`, and a `detail` message. Walk the results to log anything that wasn't a clean insert:

```python
if result.errors:
    for item in result.results:
        if item.detail:      # a per-row message means it wasn't inserted cleanly
            print(f"row {item.index} ({item.external_id}): {item.status} — {item.detail}")
```

> **Heads-up:** the SDK forwards each item's dict through as-is — it doesn't validate the per-row shape locally. The keys shown here (`measurement_point_external_id`, `data`, `external_id`) are what the server expects; the [API docs](https://app.mechbase.io/api/docs) are the authority on the accepted fields.

## Sync your registry by external ID

To keep Mechbase's asset tree in step with an upstream CMMS or asset register, use `upsert(...)` on each registry resource. `upsert` is an idempotent `PUT` keyed on your `external_id`: run it once to create the record, run it again to update it. That means the **whole sync is safe to re-run** — no "does this already exist?" bookkeeping on your side.

Build the tree top-down, referencing each parent by its external ID:

```python
inst.sections.upsert(external_id="HALL-A", name="Hall A")
inst.zones.upsert(external_id="Z-1", name="Pump Row", section_external_id="HALL-A")
inst.assets.upsert(external_id="PUMP-1", name="Feed Pump 1", zone_external_id="Z-1",
                   equipment_type="rotating", machine_class="II")
inst.measurement_points.upsert(external_id="PUMP-1-DE", name="Drive End",
                               asset_external_id="PUMP-1", transducer_type="VB",
                               measurement_unit_code="mm/s")
```

The `upsert` fields per resource:

- **`sections`** — `name`, `external_id`.
- **`zones`** — `name`, `external_id`, plus a parent as `section_id` or `section_external_id`.
- **`assets`** — `name`, `external_id`, a parent as `zone_id`/`zone_external_id` or `section_id`/`section_external_id`, plus `equipment_type` (`rotating`, `electrical`, `static`, or `infrastructure`) and `machine_class` (ISO 10816 class `I`, `II`, `III`, or `IV`).
- **`measurement_points`** — `name`, `external_id`, a parent as `asset_id`/`asset_external_id`, plus `transducer_type`, `measurement_unit_code`, `location`, `body_segment`, `body_angle`, and `machine_class`. The `transducer_type` is a code: `VB` vibration, `US` ultrasound, `TM` temperature, `IR` thermography, `PS` pressure, `FL` flow, `BL` boolean, `EI` current, `EV` voltage, `TC` tachometer, `CT` counter, `ST` state. Leave `measurement_unit_code` out and Mechbase uses the type's default unit (`mm/s` for vibration).

> **Heads-up:** these values are checked. Free text such as `equipment_type="pump"` or `transducer_type="accel"` is rejected with `422`.

Each resource also has `list`, `get`, `create` (a plain `POST`), and `update(id, ...)` (a `PATCH`) if you'd rather not upsert.

**Deleting.** `delete` takes the **numeric ID**, not the external ID, and returns a `DeleteResult` (`deleted`, `uuid`). Pass `cascade=True` to remove children too:

```python
inst.assets.delete(1234, cascade=True)     # removes the asset and its points
```

> **Note:** because the feeds never announce hard-deletes (see the [Analyst cookbook](analytics-bi.md)), your own delete calls are the record of what you removed — log them.

## Drive a route execution

You can run an inspection route from code end to end. In the SDK narrative this is a "survey", but the actual types and methods are `RouteExecution`, `routes.start`, and `execution.complete` — there's no method literally named `survey`.

Start an execution against a route UUID. `start` returns an `Executions` handle, with `.uuid` set to the execution's UUID:

```python
from mechbase.errors import ConflictError

try:
    execution = inst.routes.start(route_uuid)
except ConflictError as e:
    # a route has at most one run in progress — join it instead
    execution = inst.routes.execution(e.body["running_execution_uuid"])
print(f"working on execution {execution.uuid}")
```

A route only ever has **one run in progress**. If someone (a technician on the phone, another script) already has one open, `start` fails with `409` — *"This route already has a running execution"* — and tells you its UUID so you can join it. (Your own run that hasn't recorded anything yet doesn't block you; it's simply replaced.) An empty run can be cancelled with `POST …/executions/<uuid>/cancel`.

On that handle you can:

- **`respond(route_item_uuid=..., data=..., notes="", photos=None, idempotency_key=None)`** — answer a defined route item. Pass `photos` to attach images (it switches to a multipart upload); pass `idempotency_key` (sent as `X-Idempotency-Key`) for safe retries. You get the item UUIDs from the route definition via `inst.routes.get(route_uuid)`, which returns a raw dict.
- **`add_field_item(label=..., item_type="pass_fail", data=None, zone_id=None, config=None, notes="")`** — author a new checklist item in the field, e.g. a fault the route didn't anticipate. `zone_id=None` makes it route-level; triage it to an asset later.
- **`triage(route_item_uuid=..., asset_id=...)`** — attach a response to a specific asset.
- **`complete()`** — finish the execution.

A field-authored item then completed:

```python
resp = execution.add_field_item(
    label="Oil leak under pump",
    item_type="pass_fail",
    zone_id=None,                                    # route-level — triage to an asset later
    data={"passed": False, "severity": "major"},
    notes="under coupling",
)
print(f"added field item -> response {resp.uuid} status={resp.status}")

final = execution.complete()
print(f"completed at {final.completed_at}")
```

`respond`, `add_field_item`, and `triage` each return an `ItemResponse` (`uuid`, `route_item_uuid`, `data`, `notes`, `status`, `created_at`). `complete` returns a `RouteExecution` (`uuid`, `route_uuid`, `status`, `started_at`, `completed_at`, `session_id`).

> **Tip:** for a long or resumable field session, reattach later with `inst.routes.execution(execution_uuid)` instead of starting a new one.

## Read, correct, and delete a reading

Every reading has a number on its point — the `point_sequence`, the same number you see in its web address (`…/measurementpoints/42/measurements/766/`). Use it to fetch or remove one reading:

```python
m = inst.measurements.get(42, 766)          # GET  …/measurement-points/42/measurements/766/
print(m.status, m.data)

inst.measurements.delete(42, 766)           # DELETE the same URL
```

Deleting removes the reading and its files, and the point's state rolls back to its newest remaining reading. The `mechbase` command-line tool does the same from a terminal: `mechbase reading show 42 766` and `mechbase reading delete 42 766`.

## Photos, files, and special point types

**Files on a reading.** To attach a file to a reading that already exists (a waveform, a report, a photo), `POST` it as multipart `file` to `/api/installations/<ID>/measurements/<MEASUREMENT_UUID>/files/`. Add a form field `uuid` that you generate, and a retry after a network failure returns the file that already landed instead of attaching a second copy. Files up to 50 MB; common image, document, data, and `.dr` / `.wav` types are accepted.

**Photos of assets and points.** `POST` an image (`file`, optional `uuid`) to `/api/installations/<ID>/assets/<ASSET_ID>/photos/` to **add** a photo to an asset's gallery, or to `/measurement-points/<POINT_ID>/photos/` to **replace** a point's reference photo. Both appear as `image_urls` when you read the asset or point back.

**Running state.** A reading sent to a **Production** point is an on/off sample, not a value: `data={"value": 1}` when the machine is running, `0` when it stops. Mechbase opens and closes running periods from them (a repeat of the current state counts as a duplicate) and totals the running hours.

**On/off signals.** A **State** point (`ST`) works the same way — `data={"value": 1}` for on, `0` for off — and is recorded as periods (a fault contact *On since 06:12*) rather than a trend.

**Shaft speed with vibration.** If your device records a tachometer alongside an accelerometer, send the pulse positions with the vibration reading as a `tach` object: `edges` (the sample indices of each pulse, strictly increasing), `fs` (the sample rate), `ppr` (pulses per revolution, default 1), and `lag` (seconds, default 0). Mechbase then works out the measured shaft speed and the 1X and 2X amplitude and phase of the reading. Send it with the `.dr` waveform on `/measurements/upload/`; a missing or unusable tach never costs you the reading. (The Python `create()` has no `tach` argument yet — include it in a `create_batch` item or post the JSON yourself.)

**Batch limits.** `create_batch` takes up to 1,000 items per request.

## Go, Swift, and Kotlin

The SDK ships Go, Swift, and Kotlin clients alongside Python in the same repository. They share the same shapes — the same client, the same installation handle, and the same resource methods — but they've grown at different paces:

| Language | Install | Notably adds | Not yet |
|---|---|---|---|
| Python 0.3.0 | `pip install mechbase` | `measurements.get` / `delete` / `spectra`, the CLI | photo uploads; `uuid` on `add_file` |
| Kotlin 0.2.6 | `com.arpedon:mechbase-sdk:0.2.6` | `addPhoto` on assets and points, `imageUrls`, idempotent `addFile` | getting / deleting one reading |
| Swift | Swift Package from `https://github.com/arpedon/mechbase-sdk` | `addPhoto`, `imageUrls`, idempotent `addFile`, `Execution.cancel()` — on `main`, newer than the last tag (0.2.2) | — |
| Go 0.2.2 | `go get github.com/arpedon/mechbase-sdk/go@v0.2.2` | the core surface | the newer features above |

Learn the shapes here, then use whichever language your integration is written in. See the repository for each language's install and examples.

<https://github.com/arpedon/mechbase-sdk>

## Quick reference

| Thing | Value |
|---|---|
| pip install | `pip install mechbase` |
| Import | `from mechbase import Mechbase` |
| Construct | `Mechbase(token="<TOKEN>", base_url=..., timeout=30.0)` |
| Default base URL | `https://app.mechbase.io` |
| Auth | `Authorization: Bearer <TOKEN>` (set for you) |
| Installation handle | `client.for_installation(client.me().current_installation_id)` |
| Push one | `inst.measurements.create(point_id=…, data={…})` |
| Push many | `inst.measurements.create_batch([{…}, …])` → `BatchResult` |
| Sync registry | `inst.assets.upsert(external_id="…", …)` (also sections / zones / measurement_points) |
| Delete | `inst.assets.delete(<numeric id>, cascade=False)` → `DeleteResult` |
| Run inspection | `inst.routes.start(uuid)` → `respond` / `add_field_item` / `triage` / `complete` |
| Route already running | `start` → `409` `ConflictError`; join `e.body["running_execution_uuid"]` |
| One reading | `inst.measurements.get(point_id, seq)` · `.delete(point_id, seq)` |
| Asset / point photos | `POST …/assets/<id>/photos/` (adds) · `…/measurement-points/<id>/photos/` (replaces) |
| Running state · on/off | `data={"value": 1 or 0}` on a Production or State point |
| Timestamps | ISO 8601 with a time zone, else `422` |
| Command line | `pipx install mechbase` → `mechbase login` |
| Reattach | `inst.routes.execution(<execution uuid>)` |
| Safe retries | `idempotency_key=…` → `X-Idempotency-Key` header |
| Languages | Python · Go · Swift · Kotlin |
| SDK repo | [github.com/arpedon/mechbase-sdk](https://github.com/arpedon/mechbase-sdk) |
| API reference | [`app.mechbase.io/api/docs`](https://app.mechbase.io/api/docs) |
