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

# Nova instância

> Provisiona uma nova instância e, opcionalmente, já configura webhook, WebSocket, Chatwoot, proxy, S3 e settings no mesmo request

**Auth:** `TokenAccount` • **Rate-limit:** `20/min` • **Idempotente:** não

## Descrição

Cria uma nova instância de WhatsApp na sua conta. A instância nasce **desconectada**, o próximo passo é chamar [`GET /api/instance/connect/:instance`](/pt/api/instance/connect) para obter o QR code ou pairing code.

Durante a criação, você pode enviar, no mesmo body, a configuração inicial de **proxy**, **webhook**, **WebSocket**, **integração Chatwoot**, **ajustes de comportamento** e **armazenamento S3**. Cada bloco é independente: passe apenas o que precisar.

<Tip>
  A instância é criada dentro da cota da sua conta. Se você atingiu o limite, recebe `403` com mensagem `Account instance quota exceeded`, delete uma instância que não está mais usando para liberar espaço.
</Tip>

<Warning>
  Falhas em sub-blocos (webhook / websocket / chatwoot) **não abortam** a criação da instância. Cada bloco é log-and-continue: a instância é criada, o sub-bloco aparece como `enabled: false` ou ausente na resposta, e os logs do servidor descrevem a causa. Para Chatwoot, a falha também é exposta em `chatwoot.status: "error"` + `chatwoot.error: "<mensagem>"` no payload de retorno.
</Warning>

## Exemplos

### Mínimo

Cria a instância só com o `name`. O `TokenInstance` é gerado automaticamente pelo servidor e devolvido em `instance.token` na resposta, guarde-o para autenticar chamadas subsequentes.

<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":"minha-instancia"}'
  ```

  ```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: "minha-instancia" })
  });
  ```

  ```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": "minha-instancia"}
  )
  ```

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

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

  func main() {
      body := strings.NewReader(`{"name":"minha-instancia"}`)
      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>

### Com Token personalizado

Define manualmente o `TokenInstance` no campo `token` em vez de deixar o servidor gerar. Útil para reutilizar um valor já cadastrado em outro sistema, o token precisa ser único na sua conta.

<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":  "minha-instancia",
      "token": "meu-token-customizado-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:  "minha-instancia",
      token: "meu-token-customizado-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":  "minha-instancia",
          "token": "meu-token-customizado-123"
      }
  )
  ```

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

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

  func main() {
      body := strings.NewReader(`{
          "name":  "minha-instancia",
          "token": "meu-token-customizado-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>

### Com configurações personalizadas

Cria a instância já com o bloco de `settings` definido: rejeita chamadas automaticamente com mensagem padrão, mantém presença online, desativa sync de histórico e ignora stories. Equivale a chamar `POST /api/instance/settings/:instance` logo depois.

<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": "minha-instancia",
      "autoRejectCalls":      true,
      "callRejectMessage":    "Este número não aceita ligações.",
      "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:                "minha-instancia",
      autoRejectCalls:     true,
      callRejectMessage:   "Este número não aceita ligações.",
      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":                "minha-instancia",
          "autoRejectCalls":     True,
          "callRejectMessage":   "Este número não aceita ligações.",
          "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":                "minha-instancia",
          "autoRejectCalls":     true,
          "callRejectMessage":   "Este número não aceita ligações.",
          "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>

### Com Proxy

Já provisiona a instância apontando para um proxy SOCKS5 autenticado. A senha é encriptada at-rest com AES-256-GCM e nunca volta na resposta.

<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":          "minha-instancia",
      "proxyEnabled":  true,
      "proxyProtocol": "socks5",
      "proxyHost":     "proxy.empresa.com",
      "proxyPort":     "1080",
      "proxyUsername": "usuario",
      "proxyPassword": "senha-do-proxy"
    }'
  ```

  ```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:          "minha-instancia",
      proxyEnabled:  true,
      proxyProtocol: "socks5",
      proxyHost:     "proxy.empresa.com",
      proxyPort:     "1080",
      proxyUsername: "usuario",
      proxyPassword: "senha-do-proxy"
    })
  });
  ```

  ```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":          "minha-instancia",
          "proxyEnabled":  True,
          "proxyProtocol": "socks5",
          "proxyHost":     "proxy.empresa.com",
          "proxyPort":     "1080",
          "proxyUsername": "usuario",
          "proxyPassword": "senha-do-proxy"
      }
  )
  ```

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

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

  func main() {
      body := strings.NewReader(`{
          "name":          "minha-instancia",
          "proxyEnabled":  true,
          "proxyProtocol": "socks5",
          "proxyHost":     "proxy.empresa.com",
          "proxyPort":     "1080",
          "proxyUsername": "usuario",
          "proxyPassword": "senha-do-proxy"
      }`)
      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>

### Com Webhook

Configura, no mesmo request, o webhook `default` recebendo apenas os eventos `message.exchange` e `call.update`, com `Authorization` custom para validar a origem. Mídias não vão em base64, o destino busca pela URL retornada.

<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":                 "minha-instancia",
      "webhookEnabled":       true,
      "webhookURL":           "https://meuapp.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:                 "minha-instancia",
      webhookEnabled:       true,
      webhookURL:           "https://meuapp.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":                 "minha-instancia",
          "webhookEnabled":       True,
          "webhookURL":           "https://meuapp.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":                 "minha-instancia",
          "webhookEnabled":       true,
          "webhookURL":           "https://meuapp.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>

### Com Websocket

Habilita o broadcast em tempo real via WebSocket filtrando pelos eventos `message.exchange` e `call.update`. Útil para dashboards e bots que precisam de latência mínima sem expor um endpoint público para 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":                 "minha-instancia",
      "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:                 "minha-instancia",
      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":                 "minha-instancia",
          "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":                 "minha-instancia",
          "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>

### Com S3

Já aponta o storage de mídia para um bucket AWS S3 (`us-east-1`), com prefixo `media/` para organizar uploads. A `s3SecretKey` é encriptada at-rest e nunca aparece na resposta.

<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":         "minha-instancia",
      "s3Enabled":    true,
      "s3Region":     "us-east-1",
      "s3Bucket":     "meu-bucket-media",
      "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:         "minha-instancia",
      s3Enabled:    true,
      s3Region:     "us-east-1",
      s3Bucket:     "meu-bucket-media",
      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":         "minha-instancia",
          "s3Enabled":    True,
          "s3Region":     "us-east-1",
          "s3Bucket":     "meu-bucket-media",
          "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":         "minha-instancia",
          "s3Enabled":    true,
          "s3Region":     "us-east-1",
          "s3Bucket":     "meu-bucket-media",
          "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>

### Com Chatwoot

Provisiona a instância já vinculada a um inbox Chatwoot (`WhatsApp - Orion`), com assinatura de agente ativa e reabertura automática de conversas resolvidas. Se a ativação do Chatwoot falhar, a instância é criada mesmo assim e o objeto `chatwoot` volta com `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":                  "suporte",
      "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:                   "suporte",
      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":                   "suporte",
          "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":                   "suporte",
          "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 os blocos no mesmo request: token custom, proxy SOCKS5, webhook, WebSocket, integração Chatwoot, settings de comportamento e storage S3. Cada bloco continua independente, falhas em sub-blocos não abortam a criação da instância.

<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": "meu-token-customizado-123",

      "proxyEnabled":  true,
      "proxyProtocol": "socks5",
      "proxyHost":     "proxy.empresa.com",
      "proxyPort":     "1080",
      "proxyUsername": "usuario",
      "proxyPassword": "senha-do-proxy",

      "webhookEnabled":       true,
      "webhookURL":           "https://meuservidor.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":   "Este número não aceita ligações.",
      "ignoreGroupMessages": false,
      "keepOnlineStatus":    true,
      "autoReadMessages":    false,
      "disableHistorySync":  false,
      "ignoreStatus":        true,

      "s3Enabled":    true,
      "s3Region":     "us-east-1",
      "s3Bucket":     "meu-bucket-media",
      "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: "meu-token-customizado-123",

      proxyEnabled:  true,
      proxyProtocol: "socks5",
      proxyHost:     "proxy.empresa.com",
      proxyPort:     "1080",
      proxyUsername: "usuario",
      proxyPassword: "senha-do-proxy",

      webhookEnabled:       true,
      webhookURL:           "https://meuservidor.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:   "Este número não aceita ligações.",
      ignoreGroupMessages: false,
      keepOnlineStatus:    true,
      autoReadMessages:    false,
      disableHistorySync:  false,
      ignoreStatus:        true,

      s3Enabled:    true,
      s3Region:     "us-east-1",
      s3Bucket:     "meu-bucket-media",
      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": "meu-token-customizado-123",

          "proxyEnabled":  True,
          "proxyProtocol": "socks5",
          "proxyHost":     "proxy.empresa.com",
          "proxyPort":     "1080",
          "proxyUsername": "usuario",
          "proxyPassword": "senha-do-proxy",

          "webhookEnabled":       True,
          "webhookURL":           "https://meuservidor.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":   "Este número não aceita ligações.",
          "ignoreGroupMessages": False,
          "keepOnlineStatus":    True,
          "autoReadMessages":    False,
          "disableHistorySync":  False,
          "ignoreStatus":        True,

          "s3Enabled":    True,
          "s3Region":     "us-east-1",
          "s3Bucket":     "meu-bucket-media",
          "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": "meu-token-customizado-123",

          "proxyEnabled":  true,
          "proxyProtocol": "socks5",
          "proxyHost":     "proxy.empresa.com",
          "proxyPort":     "1080",
          "proxyUsername": "usuario",
          "proxyPassword": "senha-do-proxy",

          "webhookEnabled":       true,
          "webhookURL":           "https://meuservidor.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":   "Este número não aceita ligações.",
          "ignoreGroupMessages": false,
          "keepOnlineStatus":    true,
          "autoReadMessages":    false,
          "disableHistorySync":  false,
          "ignoreStatus":        true,

          "s3Enabled":    true,
          "s3Region":     "us-east-1",
          "s3Bucket":     "meu-bucket-media",
          "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>

## Resposta de sucesso

A resposta inclui o **TokenInstance** gerado e o resumo de cada integração configurada (proxy, webhook, websocket, chatwoot, settings, s3). Guarde o `instance.token`, é com ele que você autentica chamadas subsequentes da própria instância.

```json 201 Created theme={null}
{
  "success": true,
  "message": "Instance created",
  "instance": {
    "id": "5e1d...",
    "name": "minha-instancia",
    "token": "a1b2c3d4-...",
    "status": "disconnected",
    "numberJid": null,
    "proxy": {
      "enabled": false,
      "host": null,
      "port": null,
      "protocol": null,
      "username": null,
      "password": null
    },
    "webhook": {
      "enabled": true,
      "url": "https://meuapp.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>
  O `chatwootApiToken` não é retornado nesta resposta (é exposto em plaintext apenas em [`GET /api/chatwoot/list/:instance`](/pt/api/chatwoot/info)). O `s3.secretKey` e o `proxy.password` **nunca** são retornados por nenhum endpoint.
</Note>

### Chatwoot com erro

Se o bloco `chatwoot*` foi enviado mas a configuração falhou (ex.: token inválido), a instância **é criada mesmo assim** e o objeto `chatwoot` na resposta vem com `status: "error"` e uma `error` acionável:

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

Você pode corrigir as credenciais via `POST /api/chatwoot/set/:instance` sem precisar recriar a instância.

## Headers

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

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

## Request body

<ParamField body="name" type="string" required>
  Identificador da instância (usado nos paths `:instance` em todos os outros endpoints). Não pode estar em branco e precisa ser único na sua conta. Recomenda-se kebab-case ou snake\_case.
</ParamField>

<ParamField body="token" type="string">
  Token custom para a instância. Se omitido, é gerado automaticamente (recomendado).
</ParamField>

### Bloco proxy (opcional)

<ParamField body="proxyEnabled" type="boolean">
  Ativa uso de proxy específico para esta instância.
</ParamField>

<ParamField body="proxyHost" type="string">
  IP ou hostname do proxy.
</ParamField>

<ParamField body="proxyPort" type="string">
  Porta como string (ex.: `"8080"`).
</ParamField>

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

<ParamField body="proxyUsername" type="string">
  Usuário do proxy (opcional).
</ParamField>

<ParamField body="proxyPassword" type="string">
  Senha do proxy (opcional, encriptada at-rest com AES-256-GCM).
</ParamField>

### Bloco webhook (opcional)

<ParamField body="webhookEnabled" type="boolean">
  Ativa o envio de eventos para uma URL.
</ParamField>

<ParamField body="webhookURL" type="string">
  URL para onde a RyzeAPI vai fazer POST dos eventos.
</ParamField>

<ParamField body="webhookAuthorization" type="string">
  Valor que a RyzeAPI envia no header `Authorization` de cada POST (útil para validar origem). Ex.: `Bearer secret-key-123`.
</ParamField>

<ParamField body="webhookByEvents" type="boolean">
  Se `true`, cada tipo de evento pode ter sua própria URL (padrão: `false`).
</ParamField>

<ParamField body="webhookEvents" type="string[]">
  Lista de eventos que a instância deve despachar. Ex.: `["message.exchange", "call.update"]`.
</ParamField>

<ParamField body="webhookMediaBase64" type="boolean">
  Inclui mídia recebida em base64 dentro do corpo do webhook.
</ParamField>

<Note>
  O bloco webhook cria **um** webhook com label `default`. Para múltiplos webhooks por instância, use [`POST /api/events/webhook`](/pt/api/events/overview) depois.
</Note>

### Bloco WebSocket (opcional)

<ParamField body="websocketEnabled" type="boolean">
  Ativa o broadcast de eventos via WebSocket para essa instância.
</ParamField>

<ParamField body="websocketEvents" type="string[]">
  Lista de eventos que serão emitidos via WebSocket. Se vier vazio com `websocketEnabled=true`, **todos** os eventos são emitidos.
</ParamField>

<ParamField body="websocketMediaBase64" type="boolean">
  Inclui mídia recebida em base64 nos frames do WebSocket.
</ParamField>

### Bloco Chatwoot (opcional)

<ParamField body="chatwootEnabled" type="boolean">
  Ativa a integração Chatwoot.
</ParamField>

<ParamField body="chatwootBaseUrl" type="string">
  URL da instalação Chatwoot (ex.: `https://chatwoot.example.com`). **Obrigatório** se `chatwootEnabled=true`.
</ParamField>

<ParamField body="chatwootAccountId" type="integer">
  ID numérico da conta Chatwoot. **Obrigatório** se `chatwootEnabled=true`.
</ParamField>

<ParamField body="chatwootApiToken" type="string">
  API token da conta Chatwoot (`access_token` do agente). **Obrigatório** se `chatwootEnabled=true`. Encriptado at-rest. Não é retornado nesta resposta, mas é exposto em plaintext em [`GET /api/chatwoot/list/:instance`](/pt/api/chatwoot/info).
</ParamField>

<ParamField body="chatwootInboxName" type="string">
  Nome do inbox que será criado no Chatwoot (ex.: `"WhatsApp - Orion"`).
</ParamField>

<ParamField body="chatwootSignMessages" type="boolean">
  Se `true`, mensagens enviadas pela API são prefixadas com a assinatura do agente Chatwoot.
</ParamField>

<ParamField body="chatwootIgnoreGroups" type="boolean">
  Se `true`, mensagens de grupos não viram conversas no Chatwoot.
</ParamField>

<ParamField body="chatwootStartAsPending" type="boolean">
  Se `true`, conversas novas começam como `pending` em vez de `open`.
</ParamField>

<ParamField body="chatwootReopenResolved" type="boolean">
  Se `true`, mensagens novas em conversas resolvidas reabrem-nas automaticamente.
</ParamField>

<Warning>
  A integração Chatwoot precisa estar habilitada no servidor. Se não estiver disponível, a criação da instância continua e o `chatwoot` retorna `enabled: false` (a falha aparece nos logs do servidor). Veja [a visão geral do Chatwoot](/pt/api/chatwoot/overview) para detalhes.
</Warning>

### Bloco settings (opcional)

<ParamField body="autoRejectCalls" type="boolean">
  Rejeita chamadas recebidas automaticamente.
</ParamField>

<ParamField body="callRejectMessage" type="string">
  Mensagem automática enviada ao chamador quando a chamada é rejeitada.
</ParamField>

<ParamField body="ignoreGroupMessages" type="boolean">
  Não processa mensagens de grupo (útil para bots 1-a-1).
</ParamField>

<ParamField body="keepOnlineStatus" type="boolean">
  Mantém a instância marcada como "online" no WhatsApp.
</ParamField>

<ParamField body="autoReadMessages" type="boolean">
  Marca automaticamente mensagens recebidas como lidas.
</ParamField>

<ParamField body="disableHistorySync" type="boolean" default="true">
  **Padrão `true`** (histórico não é sincronizado na primeira conexão). Envie `false` se quiser receber o backlog.
</ParamField>

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

### Bloco S3 (opcional, armazenamento de mídias)

<ParamField body="s3Enabled" type="boolean">
  Ativa upload de mídias recebidas para S3 ou MinIO.
</ParamField>

<ParamField body="s3Region" type="string">
  Região (ex.: `us-east-1`).
</ParamField>

<ParamField body="s3Bucket" type="string">
  Nome do bucket.
</ParamField>

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

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

<ParamField body="s3Endpoint" type="string">
  Endpoint custom para MinIO ou DigitalOcean Spaces. Omita para AWS S3 oficial.
</ParamField>

<ParamField body="s3PathPrefix" type="string">
  Prefixo de path (ex.: `media/`).
</ParamField>

## Erros

| HTTP | `error.message`                         | Quando                         |
| :--: | --------------------------------------- | ------------------------------ |
|  400 | `Invalid request body`                  | JSON malformado                |
|  400 | `The 'name' field is required`          | `name` ausente ou em branco    |
|  401 | `Invalid token`                         | TokenAccount inválido          |
|  403 | `Account instance quota exceeded`       | Cota de instâncias atingida    |
|  409 | `Instance or token already exists`      | Nome ou token já em uso        |
|  429 | `Rate limit exceeded. Try again later.` | Mais de 20 criações por minuto |
|  500 | `Failed to create instance`             | Erro interno                   |

**Exemplo de erro:**

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

## Próximo

<CardGroup cols={2}>
  <Card title="Conectar ao WhatsApp" icon="qrcode" href="/pt/api/instance/connect">
    Gere o QR code ou pairing code para vincular o número.
  </Card>

  <Card title="Verificar estado" icon="list-check" href="/pt/api/instance/list">
    Use `GET /api/instance/list?instanceName=<nome>` para conferir o status atual.
  </Card>
</CardGroup>
