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

# Contatti

> Cerca contatti, verifica numeri di telefono e recupera immagini del profilo prima di inviare messaggi.

# Contatti

L'API Contatti ti permette di verificare i numeri di telefono su WhatsApp, recuperare informazioni sui contatti e ottenere le immagini del profilo. Questo e particolarmente utile per validare i numeri prima di inviare messaggi e arricchire i dati dei tuoi contatti.

Tutti gli endpoint dei contatti sono associati a un'istanza specifica:

```
/api/instances/{instanceId}/contacts/...
```

***

## Verificare se un numero esiste

Verifica se un numero di telefono e registrato su WhatsApp prima di inviare un messaggio. Questo previene consegne fallite e chiamate API inutili.

<CodeGroup>
  ```bash cURL theme={null}
  curl "https://api.wappfy.io/api/instances/inst_abc123/contacts/check?phone=5511999998888" \
    -H "X-Api-Key: YOUR_API_KEY"
  ```

  ```javascript Node.js theme={null}
  const response = await fetch(
    "https://api.wappfy.io/api/instances/inst_abc123/contacts/check?phone=5511999998888",
    {
      headers: { "X-Api-Key": "YOUR_API_KEY" },
    }
  );

  const { data } = await response.json();
  if (data.exists) {
    console.log(`Number exists on WhatsApp: ${data.chat_id}`);
  } else {
    console.log("Number is not on WhatsApp");
  }
  ```
</CodeGroup>

**Risposta (numero esistente):**

```json theme={null}
{
  "data": {
    "exists": true,
    "phone": "5511999998888",
    "chat_id": "5511999998888@s.whatsapp.net"
  }
}
```

**Risposta (numero inesistente):**

```json theme={null}
{
  "data": {
    "exists": false,
    "phone": "5511999998888",
    "chat_id": null
  }
}
```

<Tip>
  Usa questo endpoint per validare i numeri prima di inviare messaggi. Risparmia sulla quota messaggi e previene gli eventi webhook `message.failed`.
</Tip>

***

## Ottenere tutti i contatti

Recupera l'elenco completo dei contatti dell'account WhatsApp connesso.

<CodeGroup>
  ```bash cURL theme={null}
  curl https://api.wappfy.io/api/instances/inst_abc123/contacts \
    -H "X-Api-Key: YOUR_API_KEY"
  ```

  ```javascript Node.js theme={null}
  const response = await fetch(
    "https://api.wappfy.io/api/instances/inst_abc123/contacts",
    {
      headers: { "X-Api-Key": "YOUR_API_KEY" },
    }
  );

  const { data } = await response.json();
  console.log(`Total contacts: ${data.length}`);
  ```
</CodeGroup>

**Risposta:**

```json theme={null}
{
  "data": [
    {
      "id": "5511999998888@s.whatsapp.net",
      "name": "Maria Silva",
      "short_name": "Maria",
      "push_name": "Mari",
      "is_business": false
    },
    {
      "id": "5511888887777@s.whatsapp.net",
      "name": "Carlos Oliveira",
      "short_name": "Carlos",
      "push_name": "Carlos",
      "is_business": true
    }
  ]
}
```

### Campi del contatto

| Campo         | Descrizione                                                                             |
| ------------- | --------------------------------------------------------------------------------------- |
| `id`          | L'ID WhatsApp del contatto (numero di telefono + `@s.whatsapp.net`).                    |
| `name`        | Nome del contatto salvato nella rubrica del telefono. Puo essere `null` se non salvato. |
| `short_name`  | Nome abbreviato dalla rubrica.                                                          |
| `push_name`   | Il nome che il contatto ha impostato per se stesso su WhatsApp.                         |
| `is_business` | Se si tratta di un account WhatsApp Business.                                           |

<Note>
  Il campo `name` proviene dalla rubrica del tuo telefono. Se il contatto non e salvato, sara disponibile solo il `push_name` (impostato dal contatto stesso).
</Note>

***

## Ottenere informazioni su un contatto

Recupera informazioni dettagliate su un contatto specifico.

<CodeGroup>
  ```bash cURL theme={null}
  curl "https://api.wappfy.io/api/instances/inst_abc123/contacts/5511999998888@s.whatsapp.net" \
    -H "X-Api-Key: YOUR_API_KEY"
  ```

  ```javascript Node.js theme={null}
  const response = await fetch(
    "https://api.wappfy.io/api/instances/inst_abc123/contacts/5511999998888@s.whatsapp.net",
    {
      headers: { "X-Api-Key": "YOUR_API_KEY" },
    }
  );

  const { data } = await response.json();
  console.log(`Contact: ${data.push_name || data.name}`);
  ```
</CodeGroup>

**Risposta:**

```json theme={null}
{
  "data": {
    "id": "5511999998888@s.whatsapp.net",
    "name": "Maria Silva",
    "short_name": "Maria",
    "push_name": "Mari",
    "is_business": false
  }
}
```

***

## Ottenere l'immagine del profilo

Recupera l'URL dell'immagine del profilo WhatsApp di un contatto.

<CodeGroup>
  ```bash cURL theme={null}
  curl "https://api.wappfy.io/api/instances/inst_abc123/contacts/5511999998888@s.whatsapp.net/profile-picture" \
    -H "X-Api-Key: YOUR_API_KEY"
  ```

  ```javascript Node.js theme={null}
  const response = await fetch(
    "https://api.wappfy.io/api/instances/inst_abc123/contacts/5511999998888@s.whatsapp.net/profile-picture",
    {
      headers: { "X-Api-Key": "YOUR_API_KEY" },
    }
  );

  const { data } = await response.json();
  if (data.profile_picture_url) {
    console.log(`Profile picture: ${data.profile_picture_url}`);
  } else {
    console.log("No profile picture set");
  }
  ```
</CodeGroup>

**Risposta:**

```json theme={null}
{
  "data": {
    "profile_picture_url": "https://pps.whatsapp.net/v/t61.24694-24/..."
  }
}
```

<Note>
  Gli URL delle immagini del profilo sono temporanei e scadono dopo un certo periodo. Non memorizzarli in modo permanente -- recupera un URL aggiornato quando necessario.
</Note>

Se il contatto non ha un'immagine del profilo o ha limitato la visibilita nelle impostazioni di privacy, `profile_picture_url` sara `null`:

```json theme={null}
{
  "data": {
    "profile_picture_url": null
  }
}
```

***

## Pattern comuni

### Validare prima dell'invio

Verifica sempre se un numero esiste su WhatsApp prima di inviare un messaggio per evitare errori inutili:

```javascript theme={null}
async function sendMessageSafely(instanceId, phone, text) {
  // Step 1: Check if the number is on WhatsApp
  const checkResponse = await fetch(
    `https://api.wappfy.io/api/instances/${instanceId}/contacts/check?phone=${phone}`,
    { headers: { "X-Api-Key": "YOUR_API_KEY" } }
  );
  const { data: checkResult } = await checkResponse.json();

  if (!checkResult.exists) {
    console.log(`${phone} is not on WhatsApp, skipping`);
    return null;
  }

  // Step 2: Send the message using the confirmed chat_id
  const sendResponse = await fetch(
    `https://api.wappfy.io/api/instances/${instanceId}/messages/send`,
    {
      method: "POST",
      headers: {
        "X-Api-Key": "YOUR_API_KEY",
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        chat_id: checkResult.chat_id,
        type: "text",
        text,
      }),
    }
  );

  return sendResponse.json();
}
```

### Creare una rubrica contatti

Recupera tutti i contatti e arricchiscili con le immagini del profilo:

```javascript theme={null}
async function buildContactDirectory(instanceId) {
  // Get all contacts
  const contactsRes = await fetch(
    `https://api.wappfy.io/api/instances/${instanceId}/contacts`,
    { headers: { "X-Api-Key": "YOUR_API_KEY" } }
  );
  const { data: contacts } = await contactsRes.json();

  // Enrich with profile pictures (batch with delay to avoid rate limits)
  const enriched = [];
  for (const contact of contacts) {
    const picRes = await fetch(
      `https://api.wappfy.io/api/instances/${instanceId}/contacts/${contact.id}/profile-picture`,
      { headers: { "X-Api-Key": "YOUR_API_KEY" } }
    );
    const { data: pic } = await picRes.json();

    enriched.push({
      ...contact,
      profile_picture_url: pic.profile_picture_url,
    });

    // Small delay to respect rate limits
    await new Promise((r) => setTimeout(r, 200));
  }

  return enriched;
}
```

<Warning>
  Quando recuperi le immagini del profilo per molti contatti, aggiungi un ritardo tra le richieste per rispettare i [limiti di frequenza](/it/rate-limits). L'esempio sopra utilizza un ritardo di 200ms.
</Warning>

***

## Riferimento degli endpoint

| Metodo | Endpoint                                                   | Descrizione                              |
| ------ | ---------------------------------------------------------- | ---------------------------------------- |
| `GET`  | `/api/instances/{id}/contacts`                             | Elenca tutti i contatti                  |
| `GET`  | `/api/instances/{id}/contacts/check?phone={phone}`         | Verifica se un numero esiste su WhatsApp |
| `GET`  | `/api/instances/{id}/contacts/{contactId}`                 | Ottieni informazioni su un contatto      |
| `GET`  | `/api/instances/{id}/contacts/{contactId}/profile-picture` | Ottieni l'immagine del profilo           |

***

## Gestione degli errori

| Codice di stato | Descrizione                                                                                                   |
| --------------- | ------------------------------------------------------------------------------------------------------------- |
| `400`           | Formato del numero di telefono non valido. Usa solo cifre, con prefisso internazionale (es. `5511999998888`). |
| `404`           | Istanza non trovata o contatto non trovato.                                                                   |
| `429`           | Limite di frequenza superato. Consulta [Limiti di frequenza](/it/rate-limits).                                |
