> ## 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.

# Nueva instancia

> Aprovisiona una nueva instancia y, opcionalmente, configura webhook, WebSocket, Chatwoot, proxy, S3 y settings inline en la misma solicitud

**Auth:** `TokenAccount` • **Rate-limit:** `20/min` • **Idempotente:** no

## Descripción

Crea una nueva instancia de WhatsApp en tu cuenta. La instancia nace **disconnected**, el siguiente paso es llamar a [`GET /api/instance/connect/:instance`](/es/api/instance/connect) para obtener el QR code o pairing code.

Durante la creación, puedes enviar, en el mismo body, la configuración inicial de **proxy**, **webhook**, **WebSocket**, **integración Chatwoot**, **ajustes de comportamiento** y **almacenamiento S3**. Cada bloque es independiente: envía solo lo que necesites.

<Tip>
  La instancia se crea dentro de la cuota de tu cuenta. Si has alcanzado el límite, recibirás `403` con el mensaje `Account instance quota exceeded`, elimina una instancia que ya no uses para liberar espacio.
</Tip>

<Warning>
  Las fallas en sub-bloques (webhook / websocket / chatwoot) **no abortan** la creación de la instancia. Cada bloque es log-and-continue: la instancia se crea, el sub-bloque aparece como `enabled: false` o ausente en la respuesta y los logs del servidor describen la causa. Para Chatwoot, la falla también se expone en `chatwoot.status: "error"` + `chatwoot.error: "<message>"` en el payload de retorno.
</Warning>

## Ejemplos

### Mínimo

Crea la instancia con solo el `name`. El `TokenInstance` es generado automáticamente por el servidor y devuelto en `instance.token` en la respuesta, guárdalo para autenticar las llamadas subsiguientes.

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST "https://ryzeapi.cloud/api/instance/new" \
    -H "token: $Token_Account" \
    -H "Content-Type: application/json" \
    -d '{"name":"my-instance"}'
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch("https://ryzeapi.cloud/api/instance/new", {
    method: "POST",
    headers: {
      "token":        process.env.Token_Account,
      "Content-Type": "application/json"
    },
    body: JSON.stringify({ name: "my-instance" })
  });
  ```

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

  requests.post(
      "https://ryzeapi.cloud/api/instance/new",
      headers={
          "token":        os.environ["Token_Account"],
          "Content-Type": "application/json"
      },
      json={"name": "my-instance"}
  )
  ```

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

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

  func main() {
      body := strings.NewReader(`{"name":"my-instance"}`)
      req, _ := http.NewRequest("POST", "https://ryzeapi.cloud/api/instance/new", body)
      req.Header.Set("token", os.Getenv("Token_Account"))
      req.Header.Set("Content-Type", "application/json")
      http.DefaultClient.Do(req)
  }
  ```
</CodeGroup>

### Con token personalizado

Define manualmente el `TokenInstance` en el campo `token` en lugar de dejar que el servidor genere uno. Útil para reutilizar un valor ya registrado en otro sistema, el token debe ser único dentro de tu cuenta.

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST "https://ryzeapi.cloud/api/instance/new" \
    -H "token: $Token_Account" \
    -H "Content-Type: application/json" \
    -d '{
      "name":  "my-instance",
      "token": "my-custom-token-123"
    }'
  ```

  ```javascript JavaScript theme={null}
  await fetch("https://ryzeapi.cloud/api/instance/new", {
    method: "POST",
    headers: {
      "token":        process.env.Token_Account,
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      name:  "my-instance",
      token: "my-custom-token-123"
    })
  });
  ```

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

  requests.post(
      "https://ryzeapi.cloud/api/instance/new",
      headers={
          "token":        os.environ["Token_Account"],
          "Content-Type": "application/json"
      },
      json={
          "name":  "my-instance",
          "token": "my-custom-token-123"
      }
  )
  ```

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

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

  func main() {
      body := strings.NewReader(`{
          "name":  "my-instance",
          "token": "my-custom-token-123"
      }`)
      req, _ := http.NewRequest("POST", "https://ryzeapi.cloud/api/instance/new", body)
      req.Header.Set("token", os.Getenv("Token_Account"))
      req.Header.Set("Content-Type", "application/json")
      http.DefaultClient.Do(req)
  }
  ```
</CodeGroup>

### Con settings personalizados

Crea la instancia con el bloque `settings` ya definido: rechaza llamadas automáticamente con un mensaje por defecto, mantiene presencia online, deshabilita la sincronización de historial e ignora estados. Equivale a llamar a `POST /api/instance/settings/:instance` justo después.

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST "https://ryzeapi.cloud/api/instance/new" \
    -H "token: $Token_Account" \
    -H "Content-Type: application/json" \
    -d '{
      "name": "my-instance",
      "autoRejectCalls":      true,
      "callRejectMessage":    "This number does not accept calls.",
      "ignoreGroupMessages":  false,
      "keepOnlineStatus":     true,
      "autoReadMessages":     false,
      "disableHistorySync":   true,
      "ignoreStatus":         true
    }'
  ```

  ```javascript JavaScript theme={null}
  await fetch("https://ryzeapi.cloud/api/instance/new", {
    method: "POST",
    headers: {
      "token":        process.env.Token_Account,
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      name:                "my-instance",
      autoRejectCalls:     true,
      callRejectMessage:   "This number does not accept calls.",
      ignoreGroupMessages: false,
      keepOnlineStatus:    true,
      autoReadMessages:    false,
      disableHistorySync:  true,
      ignoreStatus:        true
    })
  });
  ```

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

  requests.post(
      "https://ryzeapi.cloud/api/instance/new",
      headers={
          "token":        os.environ["Token_Account"],
          "Content-Type": "application/json"
      },
      json={
          "name":                "my-instance",
          "autoRejectCalls":     True,
          "callRejectMessage":   "This number does not accept calls.",
          "ignoreGroupMessages": False,
          "keepOnlineStatus":    True,
          "autoReadMessages":    False,
          "disableHistorySync":  True,
          "ignoreStatus":        True
      }
  )
  ```

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

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

  func main() {
      body := strings.NewReader(`{
          "name":                "my-instance",
          "autoRejectCalls":     true,
          "callRejectMessage":   "This number does not accept calls.",
          "ignoreGroupMessages": false,
          "keepOnlineStatus":    true,
          "autoReadMessages":    false,
          "disableHistorySync":  true,
          "ignoreStatus":        true
      }`)
      req, _ := http.NewRequest("POST", "https://ryzeapi.cloud/api/instance/new", body)
      req.Header.Set("token", os.Getenv("Token_Account"))
      req.Header.Set("Content-Type", "application/json")
      http.DefaultClient.Do(req)
  }
  ```
</CodeGroup>

### Con proxy

Aprovisiona la instancia apuntando a un proxy SOCKS5 autenticado. La contraseña se cifra at-rest con AES-256-GCM y nunca se devuelve en la respuesta.

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST "https://ryzeapi.cloud/api/instance/new" \
    -H "token: $Token_Account" \
    -H "Content-Type: application/json" \
    -d '{
      "name":          "my-instance",
      "proxyEnabled":  true,
      "proxyProtocol": "socks5",
      "proxyHost":     "proxy.company.com",
      "proxyPort":     "1080",
      "proxyUsername": "user",
      "proxyPassword": "proxy-password"
    }'
  ```

  ```javascript JavaScript theme={null}
  await fetch("https://ryzeapi.cloud/api/instance/new", {
    method: "POST",
    headers: {
      "token":        process.env.Token_Account,
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      name:          "my-instance",
      proxyEnabled:  true,
      proxyProtocol: "socks5",
      proxyHost:     "proxy.company.com",
      proxyPort:     "1080",
      proxyUsername: "user",
      proxyPassword: "proxy-password"
    })
  });
  ```

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

  requests.post(
      "https://ryzeapi.cloud/api/instance/new",
      headers={
          "token":        os.environ["Token_Account"],
          "Content-Type": "application/json"
      },
      json={
          "name":          "my-instance",
          "proxyEnabled":  True,
          "proxyProtocol": "socks5",
          "proxyHost":     "proxy.company.com",
          "proxyPort":     "1080",
          "proxyUsername": "user",
          "proxyPassword": "proxy-password"
      }
  )
  ```

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

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

  func main() {
      body := strings.NewReader(`{
          "name":          "my-instance",
          "proxyEnabled":  true,
          "proxyProtocol": "socks5",
          "proxyHost":     "proxy.company.com",
          "proxyPort":     "1080",
          "proxyUsername": "user",
          "proxyPassword": "proxy-password"
      }`)
      req, _ := http.NewRequest("POST", "https://ryzeapi.cloud/api/instance/new", body)
      req.Header.Set("token", os.Getenv("Token_Account"))
      req.Header.Set("Content-Type", "application/json")
      http.DefaultClient.Do(req)
  }
  ```
</CodeGroup>

### Con webhook

En la misma solicitud, configura el webhook `default` para recibir solo los eventos `message.exchange` y `call.update`, con `Authorization` personalizado para validar el origen. La media no se envía en base64, el destino la obtiene vía la URL devuelta.

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST "https://ryzeapi.cloud/api/instance/new" \
    -H "token: $Token_Account" \
    -H "Content-Type: application/json" \
    -d '{
      "name":                 "my-instance",
      "webhookEnabled":       true,
      "webhookURL":           "https://myapp.com/webhook",
      "webhookAuthorization": "Bearer secret-key-123",
      "webhookByEvents":      false,
      "webhookEvents":        ["message.exchange", "call.update"],
      "webhookMediaBase64":   false
    }'
  ```

  ```javascript JavaScript theme={null}
  await fetch("https://ryzeapi.cloud/api/instance/new", {
    method: "POST",
    headers: {
      "token":        process.env.Token_Account,
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      name:                 "my-instance",
      webhookEnabled:       true,
      webhookURL:           "https://myapp.com/webhook",
      webhookAuthorization: "Bearer secret-key-123",
      webhookByEvents:      false,
      webhookEvents:        ["message.exchange", "call.update"],
      webhookMediaBase64:   false
    })
  });
  ```

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

  requests.post(
      "https://ryzeapi.cloud/api/instance/new",
      headers={
          "token":        os.environ["Token_Account"],
          "Content-Type": "application/json"
      },
      json={
          "name":                 "my-instance",
          "webhookEnabled":       True,
          "webhookURL":           "https://myapp.com/webhook",
          "webhookAuthorization": "Bearer secret-key-123",
          "webhookByEvents":      False,
          "webhookEvents":        ["message.exchange", "call.update"],
          "webhookMediaBase64":   False
      }
  )
  ```

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

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

  func main() {
      body := strings.NewReader(`{
          "name":                 "my-instance",
          "webhookEnabled":       true,
          "webhookURL":           "https://myapp.com/webhook",
          "webhookAuthorization": "Bearer secret-key-123",
          "webhookByEvents":      false,
          "webhookEvents":        ["message.exchange", "call.update"],
          "webhookMediaBase64":   false
      }`)
      req, _ := http.NewRequest("POST", "https://ryzeapi.cloud/api/instance/new", body)
      req.Header.Set("token", os.Getenv("Token_Account"))
      req.Header.Set("Content-Type", "application/json")
      http.DefaultClient.Do(req)
  }
  ```
</CodeGroup>

### Con WebSocket

Habilita el broadcast en tiempo real vía WebSocket filtrando por los eventos `message.exchange` y `call.update`. Útil para dashboards y bots que necesitan latencia mínima sin exponer un endpoint público de webhook.

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST "https://ryzeapi.cloud/api/instance/new" \
    -H "token: $Token_Account" \
    -H "Content-Type: application/json" \
    -d '{
      "name":                 "my-instance",
      "websocketEnabled":     true,
      "websocketEvents":      ["message.exchange", "call.update"],
      "websocketMediaBase64": false
    }'
  ```

  ```javascript JavaScript theme={null}
  await fetch("https://ryzeapi.cloud/api/instance/new", {
    method: "POST",
    headers: {
      "token":        process.env.Token_Account,
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      name:                 "my-instance",
      websocketEnabled:     true,
      websocketEvents:      ["message.exchange", "call.update"],
      websocketMediaBase64: false
    })
  });
  ```

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

  requests.post(
      "https://ryzeapi.cloud/api/instance/new",
      headers={
          "token":        os.environ["Token_Account"],
          "Content-Type": "application/json"
      },
      json={
          "name":                 "my-instance",
          "websocketEnabled":     True,
          "websocketEvents":      ["message.exchange", "call.update"],
          "websocketMediaBase64": False
      }
  )
  ```

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

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

  func main() {
      body := strings.NewReader(`{
          "name":                 "my-instance",
          "websocketEnabled":     true,
          "websocketEvents":      ["message.exchange", "call.update"],
          "websocketMediaBase64": false
      }`)
      req, _ := http.NewRequest("POST", "https://ryzeapi.cloud/api/instance/new", body)
      req.Header.Set("token", os.Getenv("Token_Account"))
      req.Header.Set("Content-Type", "application/json")
      http.DefaultClient.Do(req)
  }
  ```
</CodeGroup>

### Con S3

Apunta el almacenamiento de media a un bucket AWS S3 (`us-east-1`), con prefijo `media/` para organizar las subidas. La `s3SecretKey` se cifra at-rest y nunca aparece en la respuesta.

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST "https://ryzeapi.cloud/api/instance/new" \
    -H "token: $Token_Account" \
    -H "Content-Type: application/json" \
    -d '{
      "name":         "my-instance",
      "s3Enabled":    true,
      "s3Region":     "us-east-1",
      "s3Bucket":     "my-media-bucket",
      "s3AccessKey":  "AKIA...",
      "s3SecretKey":  "secret...",
      "s3Endpoint":   "https://s3.amazonaws.com",
      "s3PathPrefix": "media/"
    }'
  ```

  ```javascript JavaScript theme={null}
  await fetch("https://ryzeapi.cloud/api/instance/new", {
    method: "POST",
    headers: {
      "token":        process.env.Token_Account,
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      name:         "my-instance",
      s3Enabled:    true,
      s3Region:     "us-east-1",
      s3Bucket:     "my-media-bucket",
      s3AccessKey:  "AKIA...",
      s3SecretKey:  "secret...",
      s3Endpoint:   "https://s3.amazonaws.com",
      s3PathPrefix: "media/"
    })
  });
  ```

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

  requests.post(
      "https://ryzeapi.cloud/api/instance/new",
      headers={
          "token":        os.environ["Token_Account"],
          "Content-Type": "application/json"
      },
      json={
          "name":         "my-instance",
          "s3Enabled":    True,
          "s3Region":     "us-east-1",
          "s3Bucket":     "my-media-bucket",
          "s3AccessKey":  "AKIA...",
          "s3SecretKey":  "secret...",
          "s3Endpoint":   "https://s3.amazonaws.com",
          "s3PathPrefix": "media/"
      }
  )
  ```

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

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

  func main() {
      body := strings.NewReader(`{
          "name":         "my-instance",
          "s3Enabled":    true,
          "s3Region":     "us-east-1",
          "s3Bucket":     "my-media-bucket",
          "s3AccessKey":  "AKIA...",
          "s3SecretKey":  "secret...",
          "s3Endpoint":   "https://s3.amazonaws.com",
          "s3PathPrefix": "media/"
      }`)
      req, _ := http.NewRequest("POST", "https://ryzeapi.cloud/api/instance/new", body)
      req.Header.Set("token", os.Getenv("Token_Account"))
      req.Header.Set("Content-Type", "application/json")
      http.DefaultClient.Do(req)
  }
  ```
</CodeGroup>

### Con Chatwoot

Aprovisiona la instancia ya vinculada a una inbox de Chatwoot (`WhatsApp - Orion`), con firma de agente activa y reapertura automática de conversaciones resueltas. Si la activación de Chatwoot falla, la instancia se crea de todos modos y el objeto `chatwoot` regresa con `status: "error"`.

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST "https://ryzeapi.cloud/api/instance/new" \
    -H "token: $Token_Account" \
    -H "Content-Type: application/json" \
    -d '{
      "name":                  "support",
      "chatwootEnabled":       true,
      "chatwootBaseUrl":       "https://chatwoot.example.com",
      "chatwootAccountId":     5,
      "chatwootApiToken":      "sk_live_abc123...",
      "chatwootInboxName":     "WhatsApp - Orion",
      "chatwootSignMessages":  true,
      "chatwootIgnoreGroups":  false,
      "chatwootStartAsPending": false,
      "chatwootReopenResolved": true
    }'
  ```

  ```javascript JavaScript theme={null}
  await fetch("https://ryzeapi.cloud/api/instance/new", {
    method: "POST",
    headers: {
      "token":        process.env.Token_Account,
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      name:                   "support",
      chatwootEnabled:        true,
      chatwootBaseUrl:        "https://chatwoot.example.com",
      chatwootAccountId:      5,
      chatwootApiToken:       "sk_live_abc123...",
      chatwootInboxName:      "WhatsApp - Orion",
      chatwootSignMessages:   true,
      chatwootIgnoreGroups:   false,
      chatwootStartAsPending: false,
      chatwootReopenResolved: true
    })
  });
  ```

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

  requests.post(
      "https://ryzeapi.cloud/api/instance/new",
      headers={
          "token":        os.environ["Token_Account"],
          "Content-Type": "application/json"
      },
      json={
          "name":                   "support",
          "chatwootEnabled":        True,
          "chatwootBaseUrl":        "https://chatwoot.example.com",
          "chatwootAccountId":      5,
          "chatwootApiToken":       "sk_live_abc123...",
          "chatwootInboxName":      "WhatsApp - Orion",
          "chatwootSignMessages":   True,
          "chatwootIgnoreGroups":   False,
          "chatwootStartAsPending": False,
          "chatwootReopenResolved": True
      }
  )
  ```

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

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

  func main() {
      body := strings.NewReader(`{
          "name":                   "support",
          "chatwootEnabled":        true,
          "chatwootBaseUrl":        "https://chatwoot.example.com",
          "chatwootAccountId":      5,
          "chatwootApiToken":       "sk_live_abc123...",
          "chatwootInboxName":      "WhatsApp - Orion",
          "chatwootSignMessages":   true,
          "chatwootIgnoreGroups":   false,
          "chatwootStartAsPending": false,
          "chatwootReopenResolved": true
      }`)
      req, _ := http.NewRequest("POST", "https://ryzeapi.cloud/api/instance/new", body)
      req.Header.Set("token", os.Getenv("Token_Account"))
      req.Header.Set("Content-Type", "application/json")
      http.DefaultClient.Do(req)
  }
  ```
</CodeGroup>

### Completo

Combina todos los bloques en la misma solicitud: token personalizado, proxy SOCKS5, webhook, WebSocket, integración Chatwoot, ajustes de comportamiento y almacenamiento S3. Cada bloque permanece independiente, las fallas en sub-bloques no abortan la creación de la instancia.

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST "https://ryzeapi.cloud/api/instance/new" \
    -H "token: $Token_Account" \
    -H "Content-Type: application/json" \
    -d '{
      "name":  "marketing",
      "token": "my-custom-token-123",

      "proxyEnabled":  true,
      "proxyProtocol": "socks5",
      "proxyHost":     "proxy.company.com",
      "proxyPort":     "1080",
      "proxyUsername": "user",
      "proxyPassword": "proxy-password",

      "webhookEnabled":       true,
      "webhookURL":           "https://myserver.com/webhook",
      "webhookAuthorization": "Bearer secret-key-123",
      "webhookByEvents":      false,
      "webhookEvents":        ["message.exchange", "call.update"],
      "webhookMediaBase64":   false,

      "websocketEnabled":     true,
      "websocketEvents":      ["message.exchange", "call.update"],
      "websocketMediaBase64": false,

      "chatwootEnabled":        true,
      "chatwootBaseUrl":        "https://chatwoot.example.com",
      "chatwootAccountId":      5,
      "chatwootApiToken":       "sk_live_abc123...",
      "chatwootInboxName":      "Marketing",
      "chatwootSignMessages":   true,
      "chatwootIgnoreGroups":   false,
      "chatwootStartAsPending": false,
      "chatwootReopenResolved": true,

      "autoRejectCalls":     true,
      "callRejectMessage":   "This number does not accept calls.",
      "ignoreGroupMessages": false,
      "keepOnlineStatus":    true,
      "autoReadMessages":    false,
      "disableHistorySync":  false,
      "ignoreStatus":        true,

      "s3Enabled":    true,
      "s3Region":     "us-east-1",
      "s3Bucket":     "my-media-bucket",
      "s3AccessKey":  "AKIA...",
      "s3SecretKey":  "secret...",
      "s3Endpoint":   "https://s3.amazonaws.com",
      "s3PathPrefix": "media/"
    }'
  ```

  ```javascript JavaScript theme={null}
  await fetch("https://ryzeapi.cloud/api/instance/new", {
    method: "POST",
    headers: {
      "token":        process.env.Token_Account,
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      name:  "marketing",
      token: "my-custom-token-123",

      proxyEnabled:  true,
      proxyProtocol: "socks5",
      proxyHost:     "proxy.company.com",
      proxyPort:     "1080",
      proxyUsername: "user",
      proxyPassword: "proxy-password",

      webhookEnabled:       true,
      webhookURL:           "https://myserver.com/webhook",
      webhookAuthorization: "Bearer secret-key-123",
      webhookByEvents:      false,
      webhookEvents:        ["message.exchange", "call.update"],
      webhookMediaBase64:   false,

      websocketEnabled:     true,
      websocketEvents:      ["message.exchange", "call.update"],
      websocketMediaBase64: false,

      chatwootEnabled:        true,
      chatwootBaseUrl:        "https://chatwoot.example.com",
      chatwootAccountId:      5,
      chatwootApiToken:       "sk_live_abc123...",
      chatwootInboxName:      "Marketing",
      chatwootSignMessages:   true,
      chatwootIgnoreGroups:   false,
      chatwootStartAsPending: false,
      chatwootReopenResolved: true,

      autoRejectCalls:     true,
      callRejectMessage:   "This number does not accept calls.",
      ignoreGroupMessages: false,
      keepOnlineStatus:    true,
      autoReadMessages:    false,
      disableHistorySync:  false,
      ignoreStatus:        true,

      s3Enabled:    true,
      s3Region:     "us-east-1",
      s3Bucket:     "my-media-bucket",
      s3AccessKey:  "AKIA...",
      s3SecretKey:  "secret...",
      s3Endpoint:   "https://s3.amazonaws.com",
      s3PathPrefix: "media/"
    })
  });
  ```

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

  requests.post(
      "https://ryzeapi.cloud/api/instance/new",
      headers={
          "token":        os.environ["Token_Account"],
          "Content-Type": "application/json"
      },
      json={
          "name":  "marketing",
          "token": "my-custom-token-123",

          "proxyEnabled":  True,
          "proxyProtocol": "socks5",
          "proxyHost":     "proxy.company.com",
          "proxyPort":     "1080",
          "proxyUsername": "user",
          "proxyPassword": "proxy-password",

          "webhookEnabled":       True,
          "webhookURL":           "https://myserver.com/webhook",
          "webhookAuthorization": "Bearer secret-key-123",
          "webhookByEvents":      False,
          "webhookEvents":        ["message.exchange", "call.update"],
          "webhookMediaBase64":   False,

          "websocketEnabled":     True,
          "websocketEvents":      ["message.exchange", "call.update"],
          "websocketMediaBase64": False,

          "chatwootEnabled":        True,
          "chatwootBaseUrl":        "https://chatwoot.example.com",
          "chatwootAccountId":      5,
          "chatwootApiToken":       "sk_live_abc123...",
          "chatwootInboxName":      "Marketing",
          "chatwootSignMessages":   True,
          "chatwootIgnoreGroups":   False,
          "chatwootStartAsPending": False,
          "chatwootReopenResolved": True,

          "autoRejectCalls":     True,
          "callRejectMessage":   "This number does not accept calls.",
          "ignoreGroupMessages": False,
          "keepOnlineStatus":    True,
          "autoReadMessages":    False,
          "disableHistorySync":  False,
          "ignoreStatus":        True,

          "s3Enabled":    True,
          "s3Region":     "us-east-1",
          "s3Bucket":     "my-media-bucket",
          "s3AccessKey":  "AKIA...",
          "s3SecretKey":  "secret...",
          "s3Endpoint":   "https://s3.amazonaws.com",
          "s3PathPrefix": "media/"
      }
  )
  ```

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

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

  func main() {
      body := strings.NewReader(`{
          "name":  "marketing",
          "token": "my-custom-token-123",

          "proxyEnabled":  true,
          "proxyProtocol": "socks5",
          "proxyHost":     "proxy.company.com",
          "proxyPort":     "1080",
          "proxyUsername": "user",
          "proxyPassword": "proxy-password",

          "webhookEnabled":       true,
          "webhookURL":           "https://myserver.com/webhook",
          "webhookAuthorization": "Bearer secret-key-123",
          "webhookByEvents":      false,
          "webhookEvents":        ["message.exchange", "call.update"],
          "webhookMediaBase64":   false,

          "websocketEnabled":     true,
          "websocketEvents":      ["message.exchange", "call.update"],
          "websocketMediaBase64": false,

          "chatwootEnabled":        true,
          "chatwootBaseUrl":        "https://chatwoot.example.com",
          "chatwootAccountId":      5,
          "chatwootApiToken":       "sk_live_abc123...",
          "chatwootInboxName":      "Marketing",
          "chatwootSignMessages":   true,
          "chatwootIgnoreGroups":   false,
          "chatwootStartAsPending": false,
          "chatwootReopenResolved": true,

          "autoRejectCalls":     true,
          "callRejectMessage":   "This number does not accept calls.",
          "ignoreGroupMessages": false,
          "keepOnlineStatus":    true,
          "autoReadMessages":    false,
          "disableHistorySync":  false,
          "ignoreStatus":        true,

          "s3Enabled":    true,
          "s3Region":     "us-east-1",
          "s3Bucket":     "my-media-bucket",
          "s3AccessKey":  "AKIA...",
          "s3SecretKey":  "secret...",
          "s3Endpoint":   "https://s3.amazonaws.com",
          "s3PathPrefix": "media/"
      }`)
      req, _ := http.NewRequest("POST", "https://ryzeapi.cloud/api/instance/new", body)
      req.Header.Set("token", os.Getenv("Token_Account"))
      req.Header.Set("Content-Type", "application/json")
      http.DefaultClient.Do(req)
  }
  ```
</CodeGroup>

## Respuesta exitosa

La respuesta incluye el **TokenInstance** generado y el resumen de cada integración configurada (proxy, webhook, websocket, chatwoot, settings, s3). Guarda el `instance.token`, es lo que autentica las llamadas subsiguientes de la propia instancia.

```json 201 Created theme={null}
{
  "success": true,
  "message": "Instance created",
  "instance": {
    "id": "5e1d...",
    "name": "my-instance",
    "token": "a1b2c3d4-...",
    "status": "disconnected",
    "numberJid": null,
    "proxy": {
      "enabled": false,
      "host": null,
      "port": null,
      "protocol": null,
      "username": null,
      "password": null
    },
    "webhook": {
      "enabled": true,
      "url": "https://myapp.com/webhook",
      "events": ["message.exchange", "call.update"]
    },
    "websocket": {
      "enabled": true,
      "events": ["message.exchange"],
      "mediaBase64": false
    },
    "chatwoot": {
      "enabled": true,
      "status": "active",
      "bridgeIntegrationId": "int_xyz789abc",
      "baseUrl": "https://chatwoot.example.com",
      "accountId": 5,
      "inboxName": "WhatsApp - Orion"
    },
    "settings": {
      "autoRejectCalls": false,
      "callRejectMessage": "",
      "ignoreGroupMessages": false,
      "keepOnlineStatus": false,
      "autoReadMessages": false,
      "disableHistorySync": true,
      "ignoreStatus": false
    },
    "s3": {
      "enabled": false,
      "region": null,
      "bucket": null,
      "accessKey": null,
      "secretKey": null,
      "endpoint": null,
      "pathPrefix": null
    },
    "createdAt": "2026-04-28T10:30:00Z",
    "updatedAt": "2026-04-28T10:30:00Z"
  }
}
```

<Note>
  El `chatwootApiToken` no es devuelto en esta respuesta (solo se expone en plaintext en [`GET /api/chatwoot/list/:instance`](/es/api/chatwoot/info)). El `s3.secretKey` y la `proxy.password` **nunca** son devueltos por ningún endpoint.
</Note>

### Chatwoot con error

Si el bloque `chatwoot*` fue enviado pero la configuración falló (p. ej., token inválido), la instancia **se crea de todos modos** y el objeto `chatwoot` en la respuesta viene con `status: "error"` y un `error` accionable:

```json theme={null}
"chatwoot": {
  "enabled": false,
  "status": "error",
  "error": "Chatwoot API returned 401 - verifique o chatwootApiToken"
}
```

Puedes corregir las credenciales vía `POST /api/chatwoot/set/:instance` sin recrear la instancia.

## Cabeceras

<ParamField header="token" type="string" required>
  Tu **TokenAccount**.
</ParamField>

<ParamField header="Content-Type" type="string" required>
  `application/json`
</ParamField>

## Cuerpo de la solicitud

<ParamField body="name" type="string" required>
  Identificador de la instancia (usado en las rutas `:instance` de todos los demás endpoints). No puede estar en blanco y debe ser único dentro de tu cuenta. Se recomienda kebab-case o snake\_case.
</ParamField>

<ParamField body="token" type="string">
  Token personalizado para la instancia. Si se omite, se genera automáticamente (recomendado).
</ParamField>

### Bloque proxy (opcional)

<ParamField body="proxyEnabled" type="boolean">
  Habilita el uso de un proxy específico para esta instancia.
</ParamField>

<ParamField body="proxyHost" type="string">
  IP o hostname del proxy.
</ParamField>

<ParamField body="proxyPort" type="string">
  Puerto como string (p. ej., `"8080"`).
</ParamField>

<ParamField body="proxyProtocol" type="string">
  `http`, `https` o `socks5`.
</ParamField>

<ParamField body="proxyUsername" type="string">
  Usuario del proxy (opcional).
</ParamField>

<ParamField body="proxyPassword" type="string">
  Contraseña del proxy (opcional, cifrada at-rest con AES-256-GCM).
</ParamField>

### Bloque webhook (opcional)

<ParamField body="webhookEnabled" type="boolean">
  Habilita el envío de eventos a una URL.
</ParamField>

<ParamField body="webhookURL" type="string">
  URL donde RyzeAPI hará POST de los eventos.
</ParamField>

<ParamField body="webhookAuthorization" type="string">
  Valor que RyzeAPI envía en la cabecera `Authorization` de cada POST (útil para validar origen). Ej.: `Bearer secret-key-123`.
</ParamField>

<ParamField body="webhookByEvents" type="boolean">
  Si es `true`, cada tipo de evento puede tener su propia URL (default: `false`).
</ParamField>

<ParamField body="webhookEvents" type="string[]">
  Lista de eventos que la instancia debe despachar. Ej.: `["message.exchange", "call.update"]`.
</ParamField>

<ParamField body="webhookMediaBase64" type="boolean">
  Incluye media recibida como base64 dentro del body del webhook.
</ParamField>

<Note>
  El bloque webhook crea **un** webhook con label `default`. Para múltiples webhooks por instancia, usa [`POST /api/events/webhook`](/es/api/events/overview) después.
</Note>

### Bloque WebSocket (opcional)

<ParamField body="websocketEnabled" type="boolean">
  Habilita el broadcasting de eventos vía WebSocket para esta instancia.
</ParamField>

<ParamField body="websocketEvents" type="string[]">
  Lista de eventos que serán emitidos vía WebSocket. Si está vacío con `websocketEnabled=true`, **todos** los eventos son emitidos.
</ParamField>

<ParamField body="websocketMediaBase64" type="boolean">
  Incluye media recibida como base64 en los frames del WebSocket.
</ParamField>

### Bloque Chatwoot (opcional)

<ParamField body="chatwootEnabled" type="boolean">
  Habilita la integración con Chatwoot.
</ParamField>

<ParamField body="chatwootBaseUrl" type="string">
  URL de la instalación de Chatwoot (p. ej., `https://chatwoot.example.com`). **Requerido** si `chatwootEnabled=true`.
</ParamField>

<ParamField body="chatwootAccountId" type="integer">
  ID numérico de la cuenta de Chatwoot. **Requerido** si `chatwootEnabled=true`.
</ParamField>

<ParamField body="chatwootApiToken" type="string">
  Token de API de la cuenta de Chatwoot (el `access_token` del agente). **Requerido** si `chatwootEnabled=true`. Cifrado at-rest. No se devuelve en esta respuesta, pero se expone en plaintext en [`GET /api/chatwoot/list/:instance`](/es/api/chatwoot/info).
</ParamField>

<ParamField body="chatwootInboxName" type="string">
  Nombre del inbox que se creará en Chatwoot (p. ej., `"WhatsApp - Orion"`).
</ParamField>

<ParamField body="chatwootSignMessages" type="boolean">
  Si es `true`, los mensajes enviados a través de la API se prefijan con la firma del agente de Chatwoot.
</ParamField>

<ParamField body="chatwootIgnoreGroups" type="boolean">
  Si es `true`, los mensajes de grupo no se convierten en conversaciones en Chatwoot.
</ParamField>

<ParamField body="chatwootStartAsPending" type="boolean">
  Si es `true`, las nuevas conversaciones inician como `pending` en lugar de `open`.
</ParamField>

<ParamField body="chatwootReopenResolved" type="boolean">
  Si es `true`, los nuevos mensajes en conversaciones resueltas las reabren automáticamente.
</ParamField>

<Warning>
  La integración Chatwoot necesita estar habilitada en el servidor. Si no está disponible, la creación de la instancia continúa y `chatwoot` regresa con `enabled: false` (la falla aparece en los logs del servidor). Consulta [el resumen de Chatwoot](/es/api/chatwoot/overview) para detalles.
</Warning>

### Bloque settings (opcional)

<ParamField body="autoRejectCalls" type="boolean">
  Rechaza automáticamente las llamadas entrantes.
</ParamField>

<ParamField body="callRejectMessage" type="string">
  Mensaje automático enviado al llamante cuando la llamada es rechazada.
</ParamField>

<ParamField body="ignoreGroupMessages" type="boolean">
  No procesa mensajes de grupo (útil para bots 1-a-1).
</ParamField>

<ParamField body="keepOnlineStatus" type="boolean">
  Mantiene la instancia marcada como "online" en WhatsApp.
</ParamField>

<ParamField body="autoReadMessages" type="boolean">
  Marca automáticamente los mensajes recibidos como leídos.
</ParamField>

<ParamField body="disableHistorySync" type="boolean" default="true">
  **Default `true`** (el historial no se sincroniza en la primera conexión). Envía `false` si quieres recibir el backlog.
</ParamField>

<ParamField body="ignoreStatus" type="boolean">
  Ignora mensajes de tipo "status" (stories).
</ParamField>

### Bloque S3 (opcional, almacenamiento de media)

<ParamField body="s3Enabled" type="boolean">
  Habilita el upload de media recibida a S3 o MinIO.
</ParamField>

<ParamField body="s3Region" type="string">
  Región (p. ej., `us-east-1`).
</ParamField>

<ParamField body="s3Bucket" type="string">
  Nombre del bucket.
</ParamField>

<ParamField body="s3AccessKey" type="string">
  Access Key ID.
</ParamField>

<ParamField body="s3SecretKey" type="string">
  Secret Access Key (cifrado at-rest, nunca devuelto).
</ParamField>

<ParamField body="s3Endpoint" type="string">
  Endpoint personalizado para MinIO o DigitalOcean Spaces. Omite para AWS S3 oficial.
</ParamField>

<ParamField body="s3PathPrefix" type="string">
  Prefijo de path (p. ej., `media/`).
</ParamField>

## Errores

| HTTP | `error.message`                         | Cuándo                          |
| :--: | --------------------------------------- | ------------------------------- |
|  400 | `Invalid request body`                  | JSON malformado                 |
|  400 | `The 'name' field is required`          | `name` faltante o en blanco     |
|  401 | `Invalid token`                         | TokenAccount inválido           |
|  403 | `Account instance quota exceeded`       | Cuota de instancias alcanzada   |
|  409 | `Instance or token already exists`      | Nombre o token ya en uso        |
|  429 | `Rate limit exceeded. Try again later.` | Más de 20 creaciones por minuto |
|  500 | `Failed to create instance`             | Error interno                   |

**Ejemplo de error:**

```json theme={null}
{
  "success": false,
  "error": {
    "message": "Instance or token already exists"
  }
}
```

## Siguiente

<CardGroup cols={2}>
  <Card title="Conectar a WhatsApp" icon="qrcode" href="/es/api/instance/connect">
    Genera el QR code o pairing code para vincular el número.
  </Card>

  <Card title="Verificar estado" icon="list-check" href="/es/api/instance/list">
    Usa `GET /api/instance/list?instanceName=<name>` para inspeccionar el status actual.
  </Card>
</CardGroup>
