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

# Keep a copy in sync

> Keep your own copy of your group’s members, events, badges and tasks up to date with one request, GET /changes, and the single-record endpoints. With worked examples for SQLite and Postgres.

A copy of your group’s data in your own database lets you join it to other things, report on it in any tool, and keep working when Scoutworks is slow to reach. Keeping that copy right is the hard part. `GET /changes` makes it one loop: ask what changed since last time, fetch each record that changed, and remove each one that went.

## How it works

`GET /changes` answers with a list of changes, each one a resource, an id, what happened and when:

```json theme={null}
{
  "data": [
    { "resource": "members", "id": "3f0c…", "change": "updated", "at": "2026-11-21T09:14:03.000Z" },
    { "resource": "events", "id": "a81e…", "change": "created", "at": "2026-11-21T09:20:41.000Z" },
    { "resource": "tasks", "id": "77b2…", "change": "deleted", "at": "2026-11-21T09:31:12.000Z" }
  ],
  "nextCursor": "eyJ2IjoxLCJzIjoi…",
  "hasMore": false
}
```

* **It carries ids, never the records.** For a `created` or `updated` change, fetch the record from `GET /{resource}/{id}`, such as `GET /members/{memberId}`. For a `deleted` change, remove your copy.
* **It needs no scope of its own.** Members, events, badge records and tasks are in it, each only for a key that holds that area’s read scope: `members:read`, `events:read`, `badges:read` or `tasks:read`. A key with only `members:read` sees member changes and nothing else.
* **It never skips a change.** Keep the `nextCursor` of the last page and send it next time. A change made while you were reading comes back on a later page or on your next run. You may see a record twice; fetching it again is harmless.

Try it with the sandbox key:

```bash theme={null}
curl "https://api-demo.scoutworks.app/api/v1/changes?since=2026-11-01T00:00:00Z&limit=20" \
  -H "Authorization: Bearer sw_test_473adcc6c7236916021f0f24559db36576a53bab071d0f0c08a025adb510b6ab"
```

## The loop

1. **The first time,** read each list in full and save every record: `GET /members`, `GET /events`, `GET /badges` and `GET /tasks`, walking every page (see [Pagination](https://developers.scoutworks.app/guides/pagination.md)). Note the time **before** you start, then call `GET /changes` with `since` set to that time.
2. **Each run after that,** call `GET /changes` with `since` set to the `nextCursor` you saved. Keep calling it with each new `nextCursor` while `hasMore` is `true`.
3. **For each change:** `deleted` → remove your copy. `created` or `updated` → fetch the record and save it over your copy with the same `id`. A fetch that answers `404` means the record went after the change was listed: remove your copy.
4. **Save the last `nextCursor`** once every change is applied, for the next run. If the run fails halfway, start again from the cursor you saved last time: nothing is lost.
5. **Once a week, do a full read** and replace your copy. A few changes leave nothing to report (a parent linked to a member, a section renamed). The [pagination guide](https://developers.scoutworks.app/guides/pagination.md#sync-only-what-changed) lists them.

The order of the changes is resource by resource, not by time. Apply each change on its own and the order does not matter.

## Python and SQLite

This script keeps `scouts.db`, a SQLite file, in step with your group. It stores each record as JSON beside its id, so it never needs changing when the API adds a field. It needs Python 3.9 or later and `requests` (`pip install requests`).

```python sync_to_sqlite.py theme={null}
import json
import os
import sqlite3
import time
from datetime import datetime, timezone

import requests

# The sandbox key reads a demo group. Set SCOUTWORKS_API_KEY to use your own.
API_KEY = os.environ.get(
    "SCOUTWORKS_API_KEY",
    "sw_test_473adcc6c7236916021f0f24559db36576a53bab071d0f0c08a025adb510b6ab",
)
BASE = os.environ.get("SCOUTWORKS_API_URL", "https://api-demo.scoutworks.app/api/v1")
RESOURCES = ["members", "events", "badges", "tasks"]

session = requests.Session()
session.headers["Authorization"] = f"Bearer {API_KEY}"
db = sqlite3.connect("scouts.db")
db.execute(
    "CREATE TABLE IF NOT EXISTS records ("
    " resource TEXT, id TEXT, body TEXT, PRIMARY KEY (resource, id))"
)
db.execute("CREATE TABLE IF NOT EXISTS sync_state (cursor TEXT)")


def get(path, params=None):
    """GET a path. Waits if rate limited; returns None for a 404."""
    while True:
        res = session.get(f"{BASE}{path}", params=params, timeout=30)
        if res.status_code == 429:
            time.sleep(res.json().get("retryAfter", 30))
            continue
        if res.status_code == 404:
            return None
        if res.status_code == 403:
            return {"forbidden": True}
        res.raise_for_status()
        return res.json()


def save(resource, record):
    db.execute(
        "INSERT OR REPLACE INTO records (resource, id, body) VALUES (?, ?, ?)",
        (resource, record["id"], json.dumps(record)),
    )


def full_read():
    """Every record of every list this key reads, replacing the copy."""
    started = datetime.now(timezone.utc).isoformat()
    for resource in RESOURCES:
        cursor = None
        first = get(f"/{resource}", {"limit": 200})
        if first is None or first.get("forbidden"):
            continue  # the key does not read this area
        db.execute("DELETE FROM records WHERE resource = ?", (resource,))
        page = first
        while True:
            for record in page["data"]:
                save(resource, record)
            cursor = page["nextCursor"]
            if not cursor:
                break
            page = get(f"/{resource}", {"limit": 200, "cursor": cursor})
    return started


def apply_changes(since):
    """Apply every change since a time or a cursor; return the next cursor."""
    while True:
        page = get("/changes", {"since": since, "limit": 200})
        for change in page["data"]:
            resource, record_id = change["resource"], change["id"]
            record = None
            if change["change"] != "deleted":
                found = get(f"/{resource}/{record_id}")
                record = found["data"] if found else None
            if record:
                save(resource, record)
            else:
                db.execute(
                    "DELETE FROM records WHERE resource = ? AND id = ?",
                    (resource, record_id),
                )
        since = page["nextCursor"]
        if not page["hasMore"]:
            return since


row = db.execute("SELECT cursor FROM sync_state").fetchone()
since = row[0] if row else full_read()
cursor = apply_changes(since)
db.execute("DELETE FROM sync_state")
db.execute("INSERT INTO sync_state (cursor) VALUES (?)", (cursor,))
db.commit()
print("Up to date:", db.execute("SELECT COUNT(*) FROM records").fetchone()[0], "records")
```

Run it as often as you like: every hour from cron or Task Scheduler is plenty. The first run reads everything; each run after that reads only what changed. To do the weekly full read, delete the `sync_state` row and run it again.

A record is stored as the API returns it, so query it with SQLite’s JSON functions:

```sql theme={null}
SELECT json_extract(body, '$.firstName') AS first_name,
       json_extract(body, '$.sections[0].name') AS section
FROM records
WHERE resource = 'members'
ORDER BY first_name;
```

## Postgres

The same loop works with Postgres. Store each record as `jsonb` and upsert on the id:

```sql theme={null}
CREATE TABLE IF NOT EXISTS scoutworks_records (
  resource   text        NOT NULL,
  id         uuid        NOT NULL,
  body       jsonb       NOT NULL,
  synced_at  timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (resource, id)
);
CREATE TABLE IF NOT EXISTS scoutworks_sync_state (cursor text NOT NULL);
```

In the Python script above, swap `sqlite3` for `psycopg` (`pip install "psycopg[binary]"`) and change three statements:

```python theme={null}
db = psycopg.connect(os.environ["DATABASE_URL"], autocommit=False)

# save()
db.execute(
    "INSERT INTO scoutworks_records (resource, id, body) VALUES (%s, %s, %s)"
    " ON CONFLICT (resource, id) DO UPDATE"
    " SET body = EXCLUDED.body, synced_at = now()",
    (resource, record["id"], json.dumps(record)),
)

# the deleted branch of apply_changes()
db.execute(
    "DELETE FROM scoutworks_records WHERE resource = %s AND id = %s",
    (resource, record_id),
)
```

Commit once at the end of a run, after the cursor is saved, so the copy and the cursor always move together. A view makes the members read like a table:

```sql theme={null}
CREATE OR REPLACE VIEW scoutworks_members AS
SELECT id,
       body->>'firstName' AS first_name,
       body->>'lastName'  AS last_name,
       body->>'status'    AS status,
       (body->>'joinedAt')::timestamptz AS joined_at
FROM scoutworks_records
WHERE resource = 'members';
```

## Switch to your group

Set `SCOUTWORKS_API_KEY` to your own key and `SCOUTWORKS_API_URL` to `https://api.scoutworks.app/api/v1`. Your key needs the read scope of each area you want to copy: `members:read`, `events:read`, `badges:read` and `tasks:read`. With `members.contacts:read` too, your copy of each member carries their date of birth and parents’ contact details: keep the file somewhere only the right people can open it.

## If something goes wrong

* **`400 invalid_request` on `since`:** send a timestamp with a time zone, such as `2026-11-01T00:00:00Z`, or a `nextCursor` exactly as you got it.
* **`403 insufficient_scope`:** the key holds none of the four read scopes.
* **The copy drifts:** run the weekly full read. If it still drifts, tell us which record, and we will look.

See [Errors](https://developers.scoutworks.app/guides/errors.md) for every code. Want to hear about changes the moment they happen, instead of asking? See [Webhooks](https://developers.scoutworks.app/guides/webhooks.md): use both, and the next sync catches any message that went astray.


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