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

# Keeping a copy

> How to keep an exact copy of transactions, accounts, categories, budgets and recurring payments: the change feed GET /v1/changes and a Google Sheets recipe.

To keep your own copy of the data, say in a spreadsheet, a database or your own app, read the change feed
`GET /v1/changes`. It returns everything that changed after your cursor, deletions included, in the order the changes
were saved. So the copy never misses a row and never keeps a deleted one.

> [!TIP]
>
> Webhooks tell you about a change right away; the change feed is certain: whatever happened to a delivery, the next
> read catches up. They work well together: a webhook event just reminds you to read the feed.

## How to read it

**1. First read without a cursor**

`GET /v1/changes` without `cursor` returns every object of the space as an `upsert`, in pages of up to `limit`
(100, at most 500). That is your first copy: you don’t need to read the lists separately.

**2. Keep next\_cursor**

Every page has a `next_cursor`. Keep it, even when `items` is empty.

**3. Read to the end**

While `has_more` is `true`, ask for the next page right away with `cursor=<next_cursor>`.

**4. Next time**

Ask with the last `next_cursor`: only what changed since then arrives. Read as often as you like, within the
[limits](https://docs.degroshi.com/en/developers/limits.md).

In the [SDKs](https://docs.degroshi.com/en/developers/sdks.md#keeping-a-copy), `changes.iterate()` does this: it reads every page itself and
keeps the cursor.

```bash curl theme={null}
curl "https://api.degroshi.com/v1/changes?types=transaction&limit=500" \
  -H "X-API-Key: dg_pat_YOUR_KEY" \
  -H "X-Space-ID: YOUR_SPACE_ID"
```

```json Response theme={null}
{
  "success": true,
  "data": {
    "items": [
      { "type": "transaction", "id": "0f3c9a1e-5b2d-4c7e-8a6f-1d2e3f4a5b6c", "op": "upsert", "data": { "id": "0f3c9a1e-5b2d-4c7e-8a6f-1d2e3f4a5b6c", "amount": "-642.3", "description": "Groceries" } },
      { "type": "transaction", "id": "7c9e6679-7425-40de-944b-e07fc1f90ae7", "op": "delete" }
    ],
    "next_cursor": "eyJjIjoiZXlKMklqb3hMQ0p6SWpvaU...",
    "has_more": false
  }
}
```

## What arrives

Each item of `items` is one object:

* `type`: what kind of object it is (table below).
* `id`: its `id`.
* `op`: `upsert` when the object is new or changed, or `delete` when it was deleted or you can no longer see it.
* `data`: for an `upsert`, the object as it is now, in the same shape as in its list. A `delete` has no `data`.

| `type` | Same as in | Token permission |
| - | - | - |
| `transaction` | `GET /v1/transactions`; a transaction’s tags change it too | `transactions:read` |
| `account` | `GET /v1/accounts`; a new balance changes the account too | `accounts:read` |
| `category` | `GET /v1/categories`, without children | `categories:read` |
| `budget` | `GET /v1/budgets`; category limits change the budget too | `budgets:read` |
| `recurring_transaction` | `GET /v1/recurring-transactions` | `recurring:read` |

`types` picks what to read: `types=transaction,account` or several `types=`. Without it you get everything the token
may read. A type the token has no permission for simply doesn’t arrive, and a token with none of these permissions
gets 403.

An object that changed several times arrives once per page, in its latest state. It may arrive again on a later page,
so replace the copy’s row by `id` rather than adding a new one.

The feed carries no rates or totals. Analytics, net worth and the days of recurring payments
(`/v1/recurring-transactions/occurrences`) are computed by the server each time, so read them again. Read sources
(`/v1/sources`) from their list, and webhook events from the [event log](https://docs.degroshi.com/en/developers/webhooks.md#catching-up).

## When a cursor can’t continue

Sometimes a cursor can’t be continued. The API then answers 410 with the code `CHANGES_RESYNC_REQUIRED`, and
`details.reason` says why:

| `reason` | What happened |
| - | - |
| `epoch_changed` | Your access to the space’s accounts changed, for example the owner shared or hid an account |
| `cursor_expired` | The cursor is more than 180 days old |
| `types_changed` | The cursor was read with other `types` |
| `other_space` | The cursor belongs to another space |
| `malformed_cursor` | The cursor is damaged |

Then read the feed again without a cursor and replace the whole copy.

## Recipe: Google Sheets every hour

The spreadsheet pulls the changes itself every hour. This is a pull, not a webhook: an Apps Script web app answers
with a 302 redirect, so webhook deliveries would count as failed.

**1. The sheet**

Create a sheet named “Операції” with a header row: `id`, date, description, amount, account, category. (Or
rename the sheet in the code.)

**2. The key**

Create an [API key](https://docs.degroshi.com/en/developers/authentication.md) with the `transactions:read` permission for one space. In the
spreadsheet open “Extensions” › “Apps Script”, add the script property `DEGROSHI_KEY` in the project settings and
paste the key there. Keep the key out of the code.

**3. The code**

Paste the code below and run `syncTransactions` once to grant access. The first run copies every transaction.

**4. Every hour**

In the triggers section, add a time-driven trigger for `syncTransactions` that runs every hour.

```js Apps Script theme={null}
const API = "https://api.degroshi.com/v1/changes?types=transaction&limit=500";

function syncTransactions() {
  const props = PropertiesService.getScriptProperties();
  const sheet = SpreadsheetApp.getActive().getSheetByName("Операції");
  let cursor = props.getProperty("DEGROSHI_CURSOR") || "";
  let hasMore = true;
  while (hasMore) {
    const url = cursor ? API + "&cursor=" + encodeURIComponent(cursor) : API;
    const response = UrlFetchApp.fetch(url, {
      headers: { "X-API-Key": props.getProperty("DEGROSHI_KEY") },
      muteHttpExceptions: true,
    });
    if (response.getResponseCode() === 410) {
      // The cursor can't continue: start the copy over.
      if (sheet.getLastRow() > 1) sheet.deleteRows(2, sheet.getLastRow() - 1);
      cursor = "";
      continue;
    }
    if (response.getResponseCode() !== 200) throw new Error(response.getContentText());
    const page = JSON.parse(response.getContentText()).data;
    applyChanges(sheet, page.items);
    cursor = page.next_cursor;
    props.setProperty("DEGROSHI_CURSOR", cursor);
    hasMore = page.has_more;
  }
}

function applyChanges(sheet, items) {
  const ids = sheet.getRange(1, 1, sheet.getLastRow(), 1).getValues().map((row) => row[0]);
  for (const item of items) {
    const at = ids.indexOf(item.id);
    if (item.op === "delete") {
      if (at > 0) {
        sheet.deleteRow(at + 1);
        ids.splice(at, 1);
      }
      continue;
    }
    const t = item.data;
    const row = [t.id, t.transaction_date.slice(0, 10), t.description, Number(t.amount), t.account_name, t.category_name || ""];
    if (at > 0) {
      sheet.getRange(at + 1, 1, 1, row.length).setValues([row]);
    } else {
      sheet.appendRow(row);
      ids.push(t.id);
    }
  }
}
```

> [!NOTE]
>
> An amount in the API is a string with an exact decimal number ("-642.3"). `Number()` turns it into a number for the
> sheet’s formulas. For bookkeeping where every cent matters, keep the string.


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