# Errors, pagination, and limits

These conventions apply across snapAddy API collections. Each [API reference](/api-reference/) lists the status codes, parameters, and response fields of its endpoints.

## Error responses

Most collections return a JSON object with an `errors` array. Each entry has a technical `id` and a human-readable `message`. A response can contain several entries. The first is often a generic ID for the status code, followed by a more specific one:

```json
{
  "errors": [
    { "id": "NOT_FOUND", "message": "The involved resource does not exist." },
    { "id": "NO_INVENTORY_DATA", "message": "Event does not have any inventory data." }
  ]
}
```

Base your logic on the status code and on `id` values, and look for an `id` anywhere in the array, not only in the first entry. Use `message` for logs and troubleshooting. Its wording can change.

## Status codes

| Status | Meaning and next step |
| --- | --- |
| `400` | The request is malformed, or its input can’t be processed. For example, an event export with an empty selection returns `NO_PARTICIPANTS_FOUND`. Correct the request before you send it again. |
| `401` | The API key is missing or invalid. Check the `x-api-key` header, or the bearer token for SCIM. See [Authentication](/authentication/). |
| `403` | The key is valid, but the user’s role, license, or access to the resource does not allow the operation. Check the role and access in the snapAddy dashboard. Repeating the request does not help. |
| `404` | The resource does not exist, or something the operation requires is missing. For example, an event without inventory data returns `NO_INVENTORY_DATA`, and an unknown workflow run returns `JOB_NOT_FOUND`. Check the IDs in the path. Some endpoints also return `404` while a result is not ready. |
| `409` | The request conflicts with the current state. For example, creating a digital card beyond the per-user limit returns `MAX_CARD_LIMIT_REACHED`. Read the current state, then decide whether to change the request. |
| `410` | The resource existed but is no longer available, such as an export result past its retention period. Create the resource again. |
| `422` | The input is well-formed but breaks a rule. For example, triggering a disabled DataAgents workflow returns `WORKFLOW_NOT_ENABLED`. For Contact Enrichment and Contact Person Search, `422` means request validation failed. Fix the input or the configuration it depends on. |
| `429` | A rate limit was reached. Wait for the number of seconds in `Retry-After`, then retry. |
| `5xx` | An unexpected error occurred in snapAddy or an upstream service. Retry reads with increasing delays. Before you repeat a request that creates something, check whether the first attempt succeeded. |

## Pagination

Most list endpoints accept `limit` and `offset` as query parameters. `limit` defaults to 50 and accepts 1 to 1,000. `offset` defaults to 0. A `limit` above the maximum returns `400`. The API does not reduce it to the maximum. Request the next page until a page has fewer entries than `limit`.

Offsets refer to the current data. If records are added or removed while you page, an entry can be skipped or returned twice. Where an endpoint supports sorting, use a stable sort order, and deduplicate by ID when it matters.

## Handle errors and pages in code

This example reads all contacts of an event’s [inventory data](/visitreport/inventory-data/) in pages of 500. It stops when a page has fewer entries than requested, waits for short `Retry-After` values, and reports `NO_INVENTORY_DATA` when the event has no list. Set `EVENT_ID` and use a [personal API token](/authentication/) with access to the event.

```bash
curl --fail-with-body --retry 3 \
  "https://backend.snapaddy.com/questionnaire/inventory-data/v1/$EVENT_ID/contacts?limit=500&offset=0" \
  -H "x-api-key: $SNAPADDY_API_KEY"
```

```typescript
const apiKey = process.env.SNAPADDY_API_KEY;
const eventId = process.env.EVENT_ID;
if (!apiKey || !eventId) throw new Error("Set SNAPADDY_API_KEY and EVENT_ID");

class ApiError extends Error {
  status: number;
  ids: string[];
  constructor(status: number, ids: string[]) {
    super(`Request failed (${status}) ${ids.join(", ")}`);
    this.status = status;
    this.ids = ids;
  }
}

async function getJson(url: string): Promise<any> {
  for (let attempt = 1; ; attempt++) {
    const response = await fetch(url, { headers: { "x-api-key": apiKey! } });
    if (response.ok) return response.json();
    const retryAfter = Number(response.headers.get("retry-after") ?? 60);
    if (response.status === 429 && attempt < 4 && retryAfter <= 60) {
      await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));
      continue;
    }
    const body = await response.json().catch(() => null);
    const ids = Array.isArray(body?.errors) ? body.errors.map((error: { id: string }) => error.id) : [];
    throw new ApiError(response.status, ids);
  }
}

const limit = 500;
const contacts: unknown[] = [];
try {
  for (let offset = 0; ; offset += limit) {
    const page = await getJson(
      `https://backend.snapaddy.com/questionnaire/inventory-data/v1/${encodeURIComponent(eventId)}/contacts?limit=${limit}&offset=${offset}`,
    );
    contacts.push(...page.contacts);
    if (page.contacts.length < limit) break;
  }
  console.log(`${contacts.length} contacts`);
} catch (error) {
  if (error instanceof ApiError && error.ids.includes("NO_INVENTORY_DATA")) {
    console.log("The event has no inventory data list.");
  } else {
    throw error;
  }
}
```

```python
import json
import os
import time
from urllib.error import HTTPError
from urllib.parse import quote
from urllib.request import Request, urlopen


class ApiError(Exception):
    def __init__(self, status, ids):
        super().__init__(f"Request failed ({status}) {', '.join(ids)}")
        self.status = status
        self.ids = ids


def get_json(url):
    for attempt in range(1, 5):
        request = Request(url, headers={"x-api-key": os.environ["SNAPADDY_API_KEY"]})
        try:
            with urlopen(request, timeout=20) as response:
                return json.load(response)
        except HTTPError as error:
            retry_after = int(error.headers.get("Retry-After", "60"))
            if error.code == 429 and attempt < 4 and retry_after <= 60:
                time.sleep(retry_after)
                continue
            try:
                ids = [entry["id"] for entry in json.loads(error.read())["errors"]]
            except (ValueError, KeyError, TypeError):
                ids = []
            raise ApiError(error.code, ids) from error


limit = 500
base = f"https://backend.snapaddy.com/questionnaire/inventory-data/v1/{quote(os.environ['EVENT_ID'], safe='')}/contacts"
contacts = []
try:
    offset = 0
    while True:
        page = get_json(f"{base}?limit={limit}&offset={offset}")
        contacts.extend(page["contacts"])
        if len(page["contacts"]) < limit:
            break
        offset += limit
    print(f"{len(contacts)} contacts")
except ApiError as error:
    if "NO_INVENTORY_DATA" not in error.ids:
        raise
    print("The event has no inventory data list.")
```

With `--retry`, cURL repeats a request that returns `429` after the `Retry-After` period, however long it is. The TypeScript and Python examples wait up to 60 seconds and report the error for longer delays.

## Background jobs

Exports and DataAgents workflow triggers run in the background. A successful request returns `201` and a job `id` before the work is done. [Poll the job](/platform/jobs/#poll-a-job) with `GET /job-management/jobs/{id}` until its `state` is `completed`, `failed`, or `canceled`, and increase the delay between polls for long-running jobs. A [bulk workflow trigger](/data-agents/workflows/) returns `201` with an empty body instead. Track its jobs as a group.

Each successful request creates a separate job. If a request times out, check the [job list](/platform/jobs/) before you send it again, so you don’t start the same work twice.

## Signed download URLs

Some responses contain a signed `url` instead of the file itself, for example the result of a finished [event export](/visitreport/exports/) or a file attached to a contact item. A signed URL is valid for 10 minutes and authorizes the download by itself:

- Download the file without the `x-api-key` header, so your API key is only sent to `backend.snapaddy.com`.
- Don’t store signed URLs or write them to logs. Store the job or contact item ID instead.
- If a URL has expired, call the endpoint again to get a new one.

An export result can be retrieved for 30 days after the job finishes. After that, the result endpoint returns `410` and you need to start a new export.

## Rate limits

snapAddy limits how often requests can be made, to keep the service responsive for all customers.

**Rate limits** count requests per user for each endpoint and HTTP method. Limits differ between endpoints, so read them from the response headers instead of hard-coding a value. Responses from rate-limited endpoints include these headers:

| Header | Content |
| --- | --- |
| `X-RateLimit-Limit` | Requests allowed in the current window |
| `X-RateLimit-Remaining` | Requests left in the current window |
| `X-RateLimit-Reset` | When the window resets, as a Unix timestamp in seconds |

When the limit is reached, the API returns `429` with a `Retry-After` header in seconds and this body:

```json
{ "error": "RATE_LIMIT_EXCEEDED" }
```

To stay within the limits:

- Read `X-RateLimit-Remaining` and slow down before it reaches zero.
- Spread batch work over time instead of sending it in bursts.
- After a `429`, wait for `Retry-After` before you retry. Don’t retry other `4xx` responses without changing the request.
- Cache results you read often, such as lists of events or users.
