> ## Documentation Index
> Fetch the complete documentation index at: https://docs.technicallyfit.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Syncing a chain

> Send the baseline and every location of a chain from your own systems in a few calls, with a dry run first.

If your central systems already hold the list of sites and the equipment on each floor, you
can push all of it with `POST /v1/locations:sync` instead of editing each location by hand.
The operator console edits the same data, so use whichever suits your team: most
organizations use the console, and a chain with its own systems uses the sync.

Read [Locations and equipment](https://docs.technicallyfit.com/guides/locations-and-equipment.md) first: the sync sets the
same baseline, locations and overrides described there.

Set these two values once in your terminal. Every example in these docs reads them, so
no example has a host or a key typed into it.

```bash theme={null}
export TF_API_BASE="https://api.technicallyfit.com"
export TF_API_KEY="tf_test_your_key_here"
```

Use a test key (it starts with `tf_test_`) while you build. Never paste a live key into a
page, a ticket or a chat.

A key needs the `locations:write` scope.

```bash curl theme={null}
curl -X POST "$TF_API_BASE/v1/locations:sync" \
  -H "X-API-Key: $TF_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "dry_run": true,
    "locations": [
      {"external_id": "downtown-01", "name": "Downtown", "time_zone": "America/New_York",
       "overrides": [{"token": "leg_press", "kind": "out_of_service", "back_in_service_on": "2026-12-01"}]}
    ]
  }'
```

```typescript TypeScript theme={null}
import { createClient } from '@technicallyfit/sdk';

const tf = createClient({ credential: process.env.TF_API_KEY ?? '', baseUrl: process.env.TF_API_BASE });

const answer = await tf.POST('/v1/locations:sync', {
  body: {
    dry_run: true,
    locations: [
      {
        external_id: 'downtown-01',
        name: 'Downtown',
        time_zone: 'America/New_York',
        overrides: [{ token: 'leg_press', kind: 'out_of_service', back_in_service_on: '2026-12-01' }],
      },
    ],
  },
});
console.log(answer.applied, answer.totals.teammates_to_replan);
```

```python Python theme={null}
import os

from technicallyfit import Client

tf = Client(os.environ["TF_API_KEY"], base_url=os.environ.get("TF_API_BASE"))

answer = tf.sync_locations({
    "dry_run": True,
    "locations": [
        {"external_id": "downtown-01", "name": "Downtown", "time_zone": "America/New_York",
         "overrides": [{"token": "leg_press", "kind": "out_of_service", "back_in_service_on": "2026-12-01"}]}
    ]
})
print(answer["applied"], answer["totals"]["teammates_to_replan"])
```

```json 200 theme={null}
{
  "applied": false,
  "baseline": {"changed": false, "added": [], "removed": []},
  "locations": {"created": 0, "updated": 1, "unchanged": 0, "archived": 0},
  "changes": [
    {"external_id": "downtown-01", "action": "updated",
     "effective_inventory": {"added": [], "removed": ["leg_press"]},
     "teammates_to_replan": 42}
  ],
  "totals": {"locations_with_inventory_change": 1, "teammates_to_replan": 42}
}
```

```json 422 theme={null}
{
  "error": {
    "code": "validation_failed",
    "message": "The request body is not valid.",
    "request_id": "4b8e2d61c7a94f03b5e1d2c3a4f50617",
    "details": {
      "fields": [
        {
          "path": "locations[0].overrides[0].token",
          "code": "unknown_equipment",
          "message": "We do not know this equipment.",
          "suggestions": [{"token": "leg_press", "name": "Leg press"}]
        }
      ]
    }
  }
}
```

A sync is a dry run until you send `"dry_run": false`, and a request is written whole or not
at all. Only a location whose equipment changes sends a webhook.

```mermaid theme={null}
flowchart TD
  B["Your systems: the baseline and up to 100 locations"] --> S["POST /v1/locations:sync"]
  S --> V{"Every field valid?"}
  V -- No --> E["validation_failed<br/>Every failing field listed, nothing written"]
  V -- Yes --> M{"dry_run"}
  M -- "true, the default" --> A["applied false<br/>Exactly what applying would change, with totals"]
  A -- "Totals look right, send the same body with dry_run false" --> S
  M -- false --> W["applied true<br/>Written in one transaction"]
  W --> C{"A location's equipment changed?"}
  C -- No --> N["Nothing sent, nobody re-planned"]
  C -- Yes --> H["location.inventory_changed for that location<br/>With a count of the teammates homed there"]
```

## The request

One request sets the baseline and creates or updates up to 100 locations:

```bash curl theme={null}
curl -X POST "$TF_API_BASE/v1/locations:sync" \
  -H "X-API-Key: $TF_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "dry_run": true,
    "baseline": {"items": [{"token": "leg_press", "count": 2}, {"token": "dumbbell"}, {"token": "hack_squat"}]},
    "locations": [
      {"external_id": "downtown-01", "name": "Downtown", "time_zone": "America/New_York", "region": "north-east",
       "overrides": [{"token": "hack_squat", "kind": "missing"},
                     {"token": "leg_press", "kind": "out_of_service", "back_in_service_on": "2026-12-01"}]},
      {"external_id": "uptown-02", "name": "Uptown", "time_zone": "America/New_York"}
    ]
  }'
```

```typescript TypeScript theme={null}
import { createClient } from '@technicallyfit/sdk';

const tf = createClient({ credential: process.env.TF_API_KEY ?? '', baseUrl: process.env.TF_API_BASE });

const answer = await tf.POST('/v1/locations:sync', {
  body: {
    dry_run: true,
    baseline: { items: [{ token: 'leg_press', count: 2 }, { token: 'dumbbell' }, { token: 'hack_squat' }] },
    locations: [
      {
        external_id: 'downtown-01',
        name: 'Downtown',
        time_zone: 'America/New_York',
        region: 'north-east',
        overrides: [
          { token: 'hack_squat', kind: 'missing' },
          { token: 'leg_press', kind: 'out_of_service', back_in_service_on: '2026-12-01' },
        ],
      },
      { external_id: 'uptown-02', name: 'Uptown', time_zone: 'America/New_York' },
    ],
  },
});
console.log(answer.totals);
```

```python Python theme={null}
import os

from technicallyfit import Client

tf = Client(os.environ["TF_API_KEY"], base_url=os.environ.get("TF_API_BASE"))

answer = tf.sync_locations({
    "dry_run": True,
    "baseline": {"items": [{"token": "leg_press", "count": 2}, {"token": "dumbbell"}, {"token": "hack_squat"}]},
    "locations": [
        {"external_id": "downtown-01", "name": "Downtown", "time_zone": "America/New_York", "region": "north-east",
         "overrides": [{"token": "hack_squat", "kind": "missing"},
                       {"token": "leg_press", "kind": "out_of_service", "back_in_service_on": "2026-12-01"}]},
        {"external_id": "uptown-02", "name": "Uptown", "time_zone": "America/New_York"}
    ]
})
print(answer["totals"])
```

| Field | What it does |
| - | - |
| `dry_run` | `true` by default: the answer says what would change and nothing is written. Send `false` to apply. |
| `baseline` | Replaces the whole baseline, as `PUT /v1/inventory/baseline` does. Leave it out to keep the baseline as it is. |
| `locations` | Up to 100 locations, each created or replaced by its `external_id`, as `PUT /v1/locations/{location_external_id}` does. `name` and `time_zone` are required; a field you leave out is cleared. |
| `locations[].overrides` | Every override of that location, as `PUT /v1/locations/{location_external_id}/overrides` does. Leave it out to keep the location's overrides; send `[]` to clear them. |
| `archive_missing` | `false` by default. `true` archives every active location that is not in this request. |

### Overrides as differences

Send a location's overrides only where it differs from the baseline. A site that has
exactly the baseline sends no overrides at all. When you later change the baseline, every
location follows it, and each keeps its own overrides: an item a location marked `missing`
stays out, and an item it `added` stays in.

### Locations you leave out

A location that is not in the request is left exactly as it is. A sync never archives a
location unless the request sends `"archive_missing": true`, and then it archives every
active location the request does not list. Use it only when one request lists every
location of the organization. With more than 100 locations, archive closed sites one at a
time with `DELETE /v1/locations/{location_external_id}`.

An archived location that a sync lists again becomes active, as a `PUT` does.

## The answer

A dry run and an apply answer in the same shape; `applied` tells them apart. The dry run
answers exactly what applying the same body would change.

```json 200 theme={null}
{
  "applied": false,
  "baseline": {"changed": true, "added": ["hack_squat"], "removed": []},
  "locations": {"created": 1, "updated": 1, "unchanged": 98, "archived": 0},
  "changes": [
    {"external_id": "downtown-01", "action": "updated",
     "effective_inventory": {"added": [], "removed": ["leg_press"]},
     "teammates_to_replan": 42},
    {"external_id": "uptown-02", "action": "created",
     "effective_inventory": {"added": ["dumbbell", "hack_squat", "leg_press"], "removed": []},
     "teammates_to_replan": 0}
  ],
  "totals": {"locations_with_inventory_change": 2, "teammates_to_replan": 42}
}
```

| Field | What it holds |
| - | - |
| `baseline` | Whether the baseline changes, and the equipment it gains and loses. A change to counts or attributes alone shows `changed` with empty lists. |
| `locations` | What happens to the locations in the request, and to those archived because the request left them out. |
| `changes` | Every location whose own record or equipment changes. A baseline change can reach locations that are not in the request: they show `action` `unchanged` with the equipment they gain or lose. |
| `changes[].effective_inventory` | The equipment the location gains and loses today. Counts, attributes and notes never appear here. |
| `changes[].teammates_to_replan` | How many teammates homed at the location would get a new plan. It is a count, never a list of people. |
| `totals` | The locations whose equipment changes, and the teammates who would get a new plan, across the whole request. |

Only locations whose equipment changes re-plan anyone. A change to a name, a count or a
note re-plans nobody. The count is the same one the applied sync reports in each location's
`location.inventory_changed` webhook (`teammates_affected`): the teammates homed there now.
Re-planning itself is not switched on yet; see
[Locations and equipment](https://docs.technicallyfit.com/guides/locations-and-equipment.md#when-a-locations-equipment-changes).

When the same body is applied with `"dry_run": false`, each location whose equipment
changed sends its own webhook:

```json location.inventory_changed theme={null}
{
  "id": "7c1f3a52-9d84-4e6b-a2f0-5b9e8d7c6a41",
  "type": "location.inventory_changed",
  "mode": "test",
  "created_at": "2026-11-24T15:02:11Z",
  "data": {
    "location": {"external_id": "downtown-01"},
    "inventory_revision": 7,
    "cause": "sync",
    "added": [],
    "removed": ["leg_press"],
    "changed_at": "2026-11-24T15:02:10Z",
    "teammates_affected": 42
  }
}
```

## All or nothing

A request is applied whole or not at all. If one location is invalid, nothing is written,
and the error lists every failing field at once, in the [error format](https://docs.technicallyfit.com/guides/errors.md).
Each field's `path` points into your request, so `locations[3].overrides[0].token` is the
first override of the fourth location you sent. An unknown equipment name carries
`suggestions`, the closest known equipment.

| Code | When | What to do |
| - | - | - |
| `validation_failed` | A field is invalid, a location is listed twice, or the request has more than 100 locations. | Fix the fields named in `details.fields` and send the request again. |
| `forbidden` | The key does not have `locations:write`. | Use a key with that scope. |
| `payload_too_large` | The body is over 2 MB. | Send fewer locations per request. |
| `rate_limit_exceeded` | The key is over a rate limit. | Wait for `Retry-After`, then send the same request again. |

## Syncing more than 100 locations

Split the list into batches of 100. The sync is idempotent by `external_id`: sending the
same batch again changes nothing, with no new revision, webhook or new plan. So a batch
that failed on the network, or answered `rate_limit_exceeded` or a server error, can be sent again
as it is.

Send the baseline in a call of its own (`"locations": []`), then the locations in batches
without it. Run the whole thing as a dry run first, look at the totals, then apply it.

```typescript TypeScript theme={null}
type Location = {
  external_id: string;
  name: string;
  time_zone: string;
  region?: string;
  overrides?: { token: string; kind: string; back_in_service_on?: string }[];
};
type Baseline = { items: { token: string; count?: number }[] };

const base = process.env.TF_API_BASE!;
const key = process.env.TF_API_KEY!;

async function syncBatch(body: object, attempts = 5): Promise<any> {
  for (let attempt = 1; ; attempt += 1) {
    const response = await fetch(`${base}/v1/locations:sync`, {
      method: "POST",
      headers: { "X-API-Key": key, "Content-Type": "application/json" },
      body: JSON.stringify(body),
    });
    if (response.ok) return response.json();
    const retry = response.status === 429 || response.status >= 500;
    if (!retry || attempt === attempts) throw new Error(await response.text());
    const wait = Number(response.headers.get("retry-after") ?? 2 ** attempt);
    await new Promise((resolve) => setTimeout(resolve, wait * 1000));
  }
}

export async function syncChain(baseline: Baseline, locations: Location[], apply: boolean) {
  const totals = { locations_with_inventory_change: 0, teammates_to_replan: 0 };
  const bodies: object[] = [{ dry_run: !apply, baseline, locations: [] }];
  for (let start = 0; start < locations.length; start += 100)
    bodies.push({ dry_run: !apply, locations: locations.slice(start, start + 100) });
  for (const body of bodies) {
    const answer = await syncBatch(body);
    totals.locations_with_inventory_change += answer.totals.locations_with_inventory_change;
    totals.teammates_to_replan += answer.totals.teammates_to_replan;
  }
  return totals;
}

// Dry run first, then apply.
// console.log(await syncChain(baseline, locations, false));
// console.log(await syncChain(baseline, locations, true));
```

```python Python theme={null}
import os
import time

import requests

BASE = os.environ["TF_API_BASE"]
KEY = os.environ["TF_API_KEY"]


def sync_batch(body, attempts=5):
    for attempt in range(1, attempts + 1):
        response = requests.post(
            f"{BASE}/v1/locations:sync",
            headers={"X-API-Key": KEY},
            json=body,
            timeout=60,
        )
        if response.ok:
            return response.json()
        retry = response.status_code == 429 or response.status_code >= 500
        if not retry or attempt == attempts:
            response.raise_for_status()
        time.sleep(float(response.headers.get("Retry-After", 2**attempt)))


def sync_chain(baseline, locations, apply):
    totals = {"locations_with_inventory_change": 0, "teammates_to_replan": 0}
    bodies = [{"dry_run": not apply, "baseline": baseline, "locations": []}]
    for start in range(0, len(locations), 100):
        bodies.append({"dry_run": not apply, "locations": locations[start : start + 100]})
    for body in bodies:
        answer = sync_batch(body)
        for name in totals:
            totals[name] += answer["totals"][name]
    return totals


# Dry run first, then apply.
# print(sync_chain(baseline, locations, apply=False))
# print(sync_chain(baseline, locations, apply=True))
```

A dry run writes nothing, so each dry-run batch compares with what is stored now. The
baseline call's dry run lists every location a baseline change reaches; the location
batches after it still see the old baseline until you apply.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.