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

# Historial del chat

> Solicita los mensajes almacenados de un chat con filtros opcionales por fecha

**Auth:** `TokenAccount` o `TokenInstance` • **Rate-limit:** `Global` (100/min) • **Idempotente:** sí

## Descripción

Devuelve los mensajes almacenados de un chat específico, ordenados del más reciente al más antiguo. Puedes controlar la cantidad con `count` y filtrar por una ventana de fechas con `from`/`to`.

<Note>
  **No hay cursor de paginación.** Para paginar, ajusta los filtros `from` y `to`. El campo `hasMore` es una heurística: es `true` cuando la cantidad de mensajes devueltos == `count` (probablemente hay más).
</Note>

## Ejemplos

### Últimos 50

Forma mínima: pasa solo `number` y usa el `count` predeterminado de 50 mensajes, devolviendo los más recientes del chat ordenados del más nuevo al más antiguo.

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST "https://ryzeapi.cloud/api/chat/history/$Instance_Name" \
    -H "token: $Token_Instance" \
    -H "Content-Type: application/json" \
    -d '{"number":"5511999999999"}'
  ```

  ```javascript JavaScript theme={null}
  await fetch(`https://ryzeapi.cloud/api/chat/history/${process.env.Instance_Name}`, {
    method: "POST",
    headers: {
      "token":        process.env.Token_Instance,
      "Content-Type": "application/json"
    },
    body: JSON.stringify({ number: "5511999999999" })
  });
  ```

  ```python Python theme={null}
  import os, requests

  requests.post(
      f"https://ryzeapi.cloud/api/chat/history/{os.environ['Instance_Name']}",
      headers={
          "token":        os.environ["Token_Instance"],
          "Content-Type": "application/json"
      },
      json={"number": "5511999999999"}
  )
  ```

  ```go Go theme={null}
  package main

  import (
      "net/http"
      "os"
      "strings"
  )

  func main() {
      body := strings.NewReader(`{"number":"5511999999999"}`)
      req, _ := http.NewRequest("POST", "https://ryzeapi.cloud/api/chat/history/"+os.Getenv("Instance_Name"), body)
      req.Header.Set("token", os.Getenv("Token_Instance"))
      req.Header.Set("Content-Type", "application/json")
      http.DefaultClient.Do(req)
  }
  ```
</CodeGroup>

### Con ventana de fechas

Recupera hasta 200 mensajes enviados entre el 20 y el 28 de abril de 2026 (`from`/`to` en ISO 8601). Útil para extraer historial de un intervalo específico o paginar usando `to` como cursor.

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST "https://ryzeapi.cloud/api/chat/history/$Instance_Name" \
    -H "token: $Token_Instance" \
    -H "Content-Type: application/json" \
    -d '{
      "number": "5511999999999",
      "count":  200,
      "from":   "2026-04-20T00:00:00Z",
      "to":     "2026-04-28T23:59:59Z"
    }'
  ```

  ```javascript JavaScript theme={null}
  await fetch(`https://ryzeapi.cloud/api/chat/history/${process.env.Instance_Name}`, {
    method: "POST",
    headers: {
      "token":        process.env.Token_Instance,
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      number: "5511999999999",
      count:  200,
      from:   "2026-04-20T00:00:00Z",
      to:     "2026-04-28T23:59:59Z"
    })
  });
  ```

  ```python Python theme={null}
  import os, requests

  requests.post(
      f"https://ryzeapi.cloud/api/chat/history/{os.environ['Instance_Name']}",
      headers={
          "token":        os.environ["Token_Instance"],
          "Content-Type": "application/json"
      },
      json={
          "number": "5511999999999",
          "count":  200,
          "from":   "2026-04-20T00:00:00Z",
          "to":     "2026-04-28T23:59:59Z"
      }
  )
  ```

  ```go Go theme={null}
  package main

  import (
      "net/http"
      "os"
      "strings"
  )

  func main() {
      body := strings.NewReader(`{
          "number": "5511999999999",
          "count":  200,
          "from":   "2026-04-20T00:00:00Z",
          "to":     "2026-04-28T23:59:59Z"
      }`)
      req, _ := http.NewRequest("POST", "https://ryzeapi.cloud/api/chat/history/"+os.Getenv("Instance_Name"), body)
      req.Header.Set("token", os.Getenv("Token_Instance"))
      req.Header.Set("Content-Type", "application/json")
      http.DefaultClient.Do(req)
  }
  ```
</CodeGroup>

### Grupo

La misma lógica, pero con `number` apuntando a un JID de grupo (`@g.us`) y `count` de 100. Cada item en `messages[]` lleva `senderJid` con el autor del mensaje dentro del grupo.

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST "https://ryzeapi.cloud/api/chat/history/$Instance_Name" \
    -H "token: $Token_Instance" \
    -H "Content-Type: application/json" \
    -d '{
      "number": "120363123456789@g.us",
      "count":  100
    }'
  ```

  ```javascript JavaScript theme={null}
  await fetch(`https://ryzeapi.cloud/api/chat/history/${process.env.Instance_Name}`, {
    method: "POST",
    headers: {
      "token":        process.env.Token_Instance,
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      number: "120363123456789@g.us",
      count:  100
    })
  });
  ```

  ```python Python theme={null}
  import os, requests

  requests.post(
      f"https://ryzeapi.cloud/api/chat/history/{os.environ['Instance_Name']}",
      headers={
          "token":        os.environ["Token_Instance"],
          "Content-Type": "application/json"
      },
      json={
          "number": "120363123456789@g.us",
          "count":  100
      }
  )
  ```

  ```go Go theme={null}
  package main

  import (
      "net/http"
      "os"
      "strings"
  )

  func main() {
      body := strings.NewReader(`{
          "number": "120363123456789@g.us",
          "count":  100
      }`)
      req, _ := http.NewRequest("POST", "https://ryzeapi.cloud/api/chat/history/"+os.Getenv("Instance_Name"), body)
      req.Header.Set("token", os.Getenv("Token_Instance"))
      req.Header.Set("Content-Type", "application/json")
      http.DefaultClient.Do(req)
  }
  ```
</CodeGroup>

## Respuesta exitosa

`messages` lleva los mensajes en orden cronológico inverso (más nuevos primero). `count` indica cuántos items vinieron en esta página y `hasMore` es `true` cuando alcanzaste exactamente el `count` solicitado, señalando que puede haber más mensajes, pagina usando los `from`/`to` del último mensaje devuelto. `chat_jid` es el JID resuelto del chat solicitado.

```json 200 OK theme={null}
{
  "success": true,
  "message": "Retrieved 2 messages from chat history",
  "chat_jid": "5511999999999@s.whatsapp.net",
  "messages": [
    {
      "id": "3EB08FCF27E532F1B0F5",
      "fromMe": true,
      "timestamp": "2026-04-28T14:30:00Z",
      "content": "Hi",
      "type": "text",
      "chatJid": "5511999999999@s.whatsapp.net",
      "senderJid": ""
    },
    {
      "id": "3EB08FCF27E532F1B0F4",
      "fromMe": false,
      "timestamp": "2026-04-28T14:29:55Z",
      "content": "Good morning!",
      "type": "text",
      "chatJid": "5511999999999@s.whatsapp.net",
      "senderJid": "5511999999999@s.whatsapp.net"
    }
  ],
  "count": 2,
  "hasMore": false
}
```

## Parámetros de ruta

<ParamField path="instance" type="string" required>
  Nombre de la instancia.
</ParamField>

## Cabeceras

| Nombre         | Requerido              | Ejemplo            | Descripción                   |
| -------------- | ---------------------- | ------------------ | ----------------------------- |
| `Content-Type` | sí                     | `application/json` | ,                             |
| `token`        | sí (o `Authorization`) | `a1b2c3d4-...`     | TokenAccount o TokenInstance. |

## Cuerpo de la solicitud

<ParamField body="number" type="string" required>
  Número de teléfono, JID privado (`...@s.whatsapp.net` o `...@lid`), JID de grupo (`...@g.us`) o newsletter.
</ParamField>

<ParamField body="count" type="int" default="50">
  Cantidad máxima de mensajes a devolver. Sin límite superior interno.
</ParamField>

<ParamField body="from" type="string">
  ISO 8601 / RFC3339. Mensajes **a partir de** esta fecha (inclusive).
</ParamField>

<ParamField body="to" type="string">
  ISO 8601 / RFC3339. Mensajes **hasta** esta fecha (inclusive).
</ParamField>

## Notas y precauciones

<Note>
  * Funciona **incluso cuando la instancia está desconectada**, lee directamente de la base de datos de ingestión.
  * Para paginar de forma segura, define `to = timestamp del mensaje más antiguo ya recibido` en la llamada anterior.
  * `hasMore=true` no garantiza al 100% que existan más mensajes, es solo una heurística basada en el count solicitado.
</Note>

## Respuestas de error

| HTTP | `error.message`                                                                  | Cuándo ocurre    |
| ---- | -------------------------------------------------------------------------------- | ---------------- |
| 400  | `Instance name is required`                                                      | ,                |
| 400  | `Invalid request body: <...>`                                                    | JSON malformado. |
| 400  | `Number is required`                                                             | ,                |
| 400  | `invalid 'from' date format. Use ISO 8601 format (e.g., '2026-02-16T18:32:39Z')` | ,                |
| 400  | `invalid 'to' date format. Use ISO 8601 format (e.g., '2026-02-16T18:32:39Z')`   | ,                |
| 401  | `Invalid token`                                                                  | ,                |
| 404  | `Instance not found`                                                             | ,                |

```json Error 400 theme={null}
{
  "success": false,
  "error": { "message": "Number is required" }
}
```

## Relacionados

<CardGroup cols={2}>
  <Card title="Buscar mensaje" href="/es/api/chat/find-message">
    Recupera un mensaje específico del historial.
  </Card>

  <Card title="Media en base64" href="/es/api/chat/media-base64">
    Descarga un media referenciado en el historial.
  </Card>
</CardGroup>
