# Sync requests

> Keep a copy of your Duty requests up to date with incremental reads using updatedSince, without reading everything again.

To keep requests in a data warehouse, a CRM or a reporting tool, read only what changed since your last run with `updatedSince`.

## The loop

1. Remember a **cursor**: the time your last successful sync **started**, in UTC.
2. Ask for the requests changed since then, page by page, at most 100 per page.
3. Upsert each one by its `number`.
4. When every page is stored, move the cursor to the start time of this run.

Starting the next window at the start of the previous run, not at its end, means a request changed while you were reading is fetched again next time instead of being missed. Upserting by `number` makes the overlap harmless.

<Tabs syncKey="code">
<TabItem label="JavaScript">

```js
const BASE_URL = 'https://api.client.service-desk.goldmaster.io/v1';
const headers = { Authorization: `Bearer ${process.env.DUTY_API_KEY}` };

export async function syncRequests(cursor, save) {
  const startedAt = new Date().toISOString();
  for (let page = 1; ; page++) {
    const params = new URLSearchParams({ updatedSince: cursor, perPage: '100', page: String(page) });
    const response = await fetch(`${BASE_URL}/tickets?${params}`, { headers });
    if (!response.ok) throw new Error(`Duty API ${response.status}: ${(await response.json()).message}`);
    const { data, pagination } = await response.json();
    for (const request of data) await save(request); // upsert by request.number
    if (page >= pagination.totalPages) break;
  }
  return startedAt; // the next cursor
}
```

</TabItem>
<TabItem label="Python">

```python
import os
from datetime import datetime, timezone

import requests

BASE_URL = "https://api.client.service-desk.goldmaster.io/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['DUTY_API_KEY']}"}

def sync_requests(cursor: str, save) -> str:
    started_at = datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
    page = 1
    while True:
        response = requests.get(
            f"{BASE_URL}/tickets",
            headers=HEADERS,
            params={"updatedSince": cursor, "perPage": 100, "page": page},
            timeout=30,
        )
        response.raise_for_status()
        body = response.json()
        for request in body["data"]:
            save(request)  # upsert by request["number"]
        if page >= body["pagination"]["totalPages"]:
            return started_at  # the next cursor
        page += 1
```

</TabItem>
</Tabs>

## The first run

For the initial load, use a cursor far in the past, such as `2020-01-01T00:00:00Z`, or narrow it with `createdFrom`. Large histories take a few minutes: 120 calls per minute read up to 12,000 requests.

## Combine with webhooks

Webhooks bring changes within seconds; a sync every hour or so catches anything your endpoint missed while it was down. Both write through the same upsert, so the result is the same whichever arrives first.

## Filters you can add

| Parameter | Example | Narrows to |
| --- | --- | --- |
| `status` | `open,in_progress` | Requests in these status codes. |
| `priority` | `high,critical` | Requests with these priorities. |
| `serviceId` | `12` | One service. |
| `contactEmail` | `ana.perez@example.com` | One requester. |
| `q` | `VPN` | Text in the number or the subject. |
| `createdFrom`, `createdTo` | `2026-12-01T00:00:00Z` | A creation window. |

See [List requests](/en/api/reference/requests/list-requests/) for every parameter.
