
# Errori e paginazione

Questa pagina tratta due aspetti che ogni integrazione deve gestire: come appare una richiesta fallita e come scorrere gli endpoint che restituiscono elenchi.

---

## Il formato dell'errore

Quando una richiesta fallisce, la risposta è sempre in formato JSON con la stessa struttura: un flag `success` impostato su `false`, un messaggio `error` leggibile dall'utente e un `error_code` numerico che corrisponde allo stato HTTP:

```json
{
  "success": false,
  "error": "Invalid cursor",
  "error_code": 400
}
```

Poiché `success` e `error_code` sono sempre presenti, è possibile basare la logica su di essi senza dover esaminare i codici di stato HTTP non elaborati, se lo si preferisce. Una risposta corretta ha sempre `success: true`.

---

## Codici di stato

| Status | `error_code` | Meaning | What to do |
|---|---|---|---|
| `200` | — | Success | Read the response data. |
| `201` | — | Resource created | Save the returned ID (e.g. `campaign_id`, `contactId`). |
| `400` | `400` | Bad request | A parameter is missing or invalid. Read the `error` message and fix the request. |
| `401` | `401` | Unauthorized | Your API key is missing or invalid. Check the key and how you are sending it — see [Authentication](authentication.md). |
| `403` | `403` | Forbidden | Your plan does not include API access. See [API Access](../integrations/api-access.md) or contact [<span data-t="supportEmail">hi@youraiconnector.com</span>](mailto:hi@youraiconnector.com). |
| `404` | `404` | Not found | The resource (e.g. a contact, campaign, or task ID) does not exist on your account. |
| `409` | `409` | Conflict | The resource already exists — for example, creating a contact whose phone number is already on your account. |
| `429` | `429` | Rate limited | You have exceeded 300 requests per minute (or the wider 1,200/minute account ceiling). Back off and retry shortly. |
| `500` | `500` | Server error | Something went wrong on our side. Retry after a short wait; email [<span data-t="supportEmail">hi@youraiconnector.com</span>](mailto:hi@youraiconnector.com) if it persists. |

Alcuni esempi di come appaiono nella pratica:

```json
{
  "success": false,
  "error_code": 401,
  "error": "Invalid API key"
}
```

```json
{
  "success": false,
  "error": "A contact with this phone number already exists",
  "error_code": 409
}
```

```json
{
  "success": false,
  "error_code": 429,
  "error": "Rate limit exceeded. Please try again later."
}
```

### Gestire correttamente gli errori

- **Controlla `success` (o il codice di stato) prima di leggere i dati.** Non dare per scontato che il corpo della risposta contenga il campo che ti aspetti.
- **Riprova `429` e `500` con un breve back-off**: attendi, poi riprova. Non riprovare `400`, `401`, `403`, `404` o `409`; continueranno a fallire finché non modificherai la richiesta.
- **Leggi il messaggio `error`.** Di solito indica esattamente quale campo è errato.

---

## Paginazione

Gli endpoint di elenco (come `GET /contacts`, `GET /campaigns` e `GET /tasks`) restituiscono i risultati in pagine, in modo che una singola chiamata non debba mai caricare l'intero account. La paginazione utilizza un cursore opaco.

Due parametri di query la controllano:

| Parametro | Descrizione |
|---|---|
| `limit` | Quanti elementi restituire per pagina. I valori predefiniti variano in base all'endpoint (spesso 50); il massimo è **100**. |
| `cursor` | Un puntatore opaco alla pagina successiva. Lascialo vuoto per la prima pagina. |

Ogni pagina include un campo `next_cursor` nella risposta:

- Se `next_cursor` è una stringa, ci sono altri risultati: passala come `cursor` nella tua prossima richiesta.
- Se `next_cursor` è `null`, hai raggiunto l'ultima pagina. Fermati.

Una singola pagina di contatti appare così:

```json
{
  "success": true,
  "contacts": [
    { "id": "abc123", "first_name": "Jane", "phone_number": "+15551234567" },
    { "id": "def456", "first_name": "John", "phone_number": "+15557654321" }
  ],
  "next_cursor": "eyJsYXN0IjoiZGVmNDU2In0"
}
```

::: note
**Nota:** Un cursore è opaco — non tentare di analizzarlo, crearlo o modificarlo. Passa sempre e solo un valore `next_cursor` che hai ricevuto da una risposta precedente.
:::


---

## Navigazione tra tutti i contatti

Per raccogliere un intero elenco, inizia senza cursore e continua a chiamare finché `next_cursor` non restituisce `null`.

**cURL**

Questo esempio scorre manualmente le prime due pagine. Esegui la prima chiamata, copia il `next_cursor` dalla sua risposta in `CURSOR`, quindi esegui la seconda chiamata. Ripeti finché `next_cursor` non è `null`.

```bash
# First page
curl "https://api.youraiconnector.com/v1/contacts?apiKey=YOUR_API_KEY&limit=100"

# Next page — paste the next_cursor from the previous response
CURSOR="eyJsYXN0IjoiZGVmNDU2In0"
curl "https://api.youraiconnector.com/v1/contacts?apiKey=YOUR_API_KEY&limit=100&cursor=$CURSOR"
```

**JavaScript**

```javascript
async function getAllContacts() {
  const all = [];
  let cursor = null;

  do {
    const url = new URL("https://api.youraiconnector.com/v1/contacts");
    url.searchParams.set("limit", "100");
    if (cursor) url.searchParams.set("cursor", cursor);

    const res = await fetch(url, {
      headers: { "X-API-Key": "YOUR_API_KEY" },
    });
    const data = await res.json();

    if (!data.success) throw new Error(data.error);

    all.push(...data.contacts);
    cursor = data.next_cursor;
  } while (cursor);

  return all;
}
```

**Python**

```python
import requests

def get_all_contacts():
    all_contacts = []
    cursor = None

    while True:
        params = {"limit": 100}
        if cursor:
            params["cursor"] = cursor

        res = requests.get(
            "https://api.youraiconnector.com/v1/contacts",
            params=params,
            headers={"X-API-Key": "YOUR_API_KEY"},
        )
        data = res.json()

        if not data["success"]:
            raise Exception(data["error"])

        all_contacts.extend(data["contacts"])
        cursor = data["next_cursor"]

        if not cursor:
            break

    return all_contacts
```

Lo stesso ciclo funziona per qualsiasi endpoint paginato: basta cambiare il percorso e il campo letto dalla risposta (`campaigns`, `tasks` e così via).

---

## Passaggi successivi

- [Autenticazione](authentication.md) — i quattro modi per inviare la tua chiave.
- [Contatti](contacts.md) — gli endpoint completi dei contatti utilizzati negli esempi sopra.
- [Chiavi API](api-keys.md) — controlla l'utilizzo del limite di frequenza in tempo reale per evitare `429`.
