# Pagination and syncing

Page through lists with cursors, and fetch only what changed with updated_since.

## Cursor pagination

Every list is paged with a cursor. Send `limit` (1 to 200, default 50) and, for the next page, the `cursor` from the last response.

```json
{
  "data": [],
  "next_cursor": "eyJ1cGRhdGVkX2F0IjoiMjAyNi0xMi0wM1QxNDozMDowMFoifQ",
  "has_more": true
}
```

Keep requesting with `cursor=<next_cursor>` while `has_more` is `true`. Treat a cursor as opaque. A cursor Valeron did not issue returns `400 invalid_cursor`.

## Table queries

Contacts, companies, recordings, members, tasks, meetings and conversations also answer to `POST /v1/<object>/query`. It takes one shape everywhere:

```json
{
  "columns": ["name", "email", "stage"],
  "filters": [{ "field": "stage", "op": "eq", "value": "Qualified" }],
  "sort": [{ "field": "updated_at", "direction": "desc" }],
  "limit": 100,
  "cursor": null
}
```

A filter is `{ field, op, value }`. The operators are `eq`, `neq`, `contains`, `starts_with`, `in`, `gt`, `gte`, `lt`, `lte`, `is_empty` and `is_not_empty`. You can sort by up to five keys. The response is `{ columns, data, groups, next_cursor, has_more, total }`, where `columns` describes each column with its label and type. `GET /v1/fields?object=contacts` lists the columns you can ask for.

## Fetch only what changed

`GET /v1/contacts` and `GET /v1/companies` take `updated_since`, an ISO 8601 time. They return records changed at or after that moment, in the order they changed, paged by cursor. The query endpoints accept the same thing as a filter on `updated_at`.

The time is inclusive, so a record can appear in two consecutive syncs. Upsert by `id` and the repeat does no harm.

To avoid gaps, record the time before you start each run, and use it as `updated_since` for the next one:

```js title="JavaScript"
async function syncContacts(since) {
  const startedAt = new Date().toISOString();
  let cursor = null;
  do {
    const url = new URL("https://api.valeron.io/v1/contacts");
    url.searchParams.set("limit", "200");
    if (since) url.searchParams.set("updated_since", since);
    if (cursor) url.searchParams.set("cursor", cursor);
    const response = await fetch(url, {
      headers: { Authorization: `Bearer ${process.env.VALERON_API_KEY}` },
    });
    if (!response.ok) throw new Error(`Valeron returned ${response.status}`);
    const page = await response.json();
    for (const contact of page.data) await upsertIntoYourCrm(contact);
    cursor = page.has_more ? page.next_cursor : null;
  } while (cursor);
  return startedAt; // pass this as `since` next time
}
```

```python title="Python"
import os
from datetime import datetime, timezone

import requests

def sync_contacts(since=None):
    started_at = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
    cursor = None
    while True:
        params = {"limit": 200}
        if since:
            params["updated_since"] = since
        if cursor:
            params["cursor"] = cursor
        response = requests.get(
            "https://api.valeron.io/v1/contacts",
            headers={"Authorization": f"Bearer {os.environ['VALERON_API_KEY']}"},
            params=params,
        )
        response.raise_for_status()
        page = response.json()
        for contact in page["data"]:
            upsert_into_your_crm(contact)
        if not page["has_more"]:
            return started_at  # pass this as `since` next time
        cursor = page["next_cursor"]
```

Do the first run without `updated_since` to load everything. Run a full sync now and then to catch anything you missed, or use [webhooks](/docs/webhooks/) to hear about changes as they happen.
