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

# Webhooks

> Referência da API para assinaturas e entregas de webhook

Crie e gerencie assinaturas de webhook para receber notificações em tempo real quando eventos ocorrerem na sua organização Avala.

> [!TIP]
>
> Os webhooks entregam cargas de eventos ao seu endpoint HTTPS por meio de requisições `POST`. Cada entrega é assinada com o seu segredo de webhook para que você possa verificar a autenticidade. Entregas com falha são reenviadas automaticamente.

## Listar webhooks

```
GET /api/v1/webhooks/
```

Retorna todas as assinaturas de webhook da organização do usuário autenticado, ordenadas da mais recente para a mais antiga.

### Parâmetros

| Nome | Tipo | Obrigatório | Descrição |
| - | - | - | - |
| `cursor` | string | Não | Cursor para paginação (parâmetro de consulta) |
| `limit` | integer | Não | Número de resultados por página (parâmetro de consulta) |

### Requisição

```bash cURL theme={null}
curl "https://api.avala.ai/api/v1/webhooks/" \
  -H "X-Avala-Api-Key: $AVALA_API_KEY"
```

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

response = requests.get(
    "https://api.avala.ai/api/v1/webhooks/",
    headers={"X-Avala-Api-Key": "YOUR_API_KEY"}
)
webhooks = response.json()["results"]
```

```typescript TypeScript theme={null}
const response = await fetch(
  "https://api.avala.ai/api/v1/webhooks/",
  {
    headers: { "X-Avala-Api-Key": "YOUR_API_KEY" },
  }
);
const { results } = await response.json();
```

```go Go theme={null}
req, _ := http.NewRequest("GET", "https://api.avala.ai/api/v1/webhooks/", nil)
req.Header.Set("X-Avala-Api-Key", "YOUR_API_KEY")

resp, err := http.DefaultClient.Do(req)
```

### Resposta

```json theme={null}
{
  "next": null,
  "previous": null,
  "results": [
    {
      "uid": "c2d3e4f5-a6b7-8c9d-0e1f-2a3b4c5d6e7f",
      "target_url": "https://my-app.example.com/avala-webhook",
      "events": ["result.submitted", "export.completed"],
      "is_active": true,
      "created_at": "2025-02-10T08:00:00Z",
      "updated_at": "2025-02-10T08:00:00Z"
    }
  ]
}
```

### Campos

| Campo | Tipo | Descrição |
| - | - | - |
| `uid` | string (UUID) | Identificador único da assinatura de webhook |
| `target_url` | string | HTTPS URL para onde as cargas de eventos são entregues |
| `events` | array | Lista de tipos de evento que este webhook assina |
| `is_active` | boolean | Indica se o webhook está atualmente habilitado |
| `created_at` | string (datetime) | Carimbo de data/hora ISO 8601 de quando o webhook foi criado |
| `updated_at` | string (datetime) | Timestamp ISO 8601 da última atualização |

***

## Criar webhook

```
POST /api/v1/webhooks/
```

Cria uma nova assinatura de webhook. Se nenhum `secret` for fornecido, um é gerado automaticamente.

O campo `secret` é retornado **somente** na resposta de criação. Armazene-o com segurança: ele é usado para verificar as assinaturas das entregas e não pode ser recuperado depois.

### Parâmetros

| Nome | Tipo | Obrigatório | Descrição |
| - | - | - | - |
| `target_url` | string | Sim | HTTPS URL para receber as cargas do webhook |
| `events` | array | Sim | Tipos de evento a assinar (consulte [Tipos de Evento](#tipos-de-evento)) |
| `secret` | string | Não | Segredo de assinatura (gerado automaticamente se não for fornecido, somente gravação) |
| `is_active` | boolean | Não | Indica se o webhook está habilitado (padrão: `true`) |

### Requisição

```bash cURL theme={null}
curl -X POST "https://api.avala.ai/api/v1/webhooks/" \
  -H "X-Avala-Api-Key: $AVALA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "target_url": "https://my-app.example.com/avala-webhook",
    "events": ["result.submitted", "export.completed"]
  }'
```

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

response = requests.post(
    "https://api.avala.ai/api/v1/webhooks/",
    headers={
        "X-Avala-Api-Key": "YOUR_API_KEY",
        "Content-Type": "application/json"
    },
    json={
        "target_url": "https://my-app.example.com/avala-webhook",
        "events": ["result.submitted", "export.completed"]
    }
)
webhook = response.json()
```

```typescript TypeScript theme={null}
const response = await fetch(
  "https://api.avala.ai/api/v1/webhooks/",
  {
    method: "POST",
    headers: {
      "X-Avala-Api-Key": "YOUR_API_KEY",
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      target_url: "https://my-app.example.com/avala-webhook",
      events: ["result.submitted", "export.completed"],
    }),
  }
);
const webhook = await response.json();
```

```go Go theme={null}
body := strings.NewReader(`{
    "target_url": "https://my-app.example.com/avala-webhook",
    "events": ["result.submitted", "export.completed"]
}`)

req, _ := http.NewRequest("POST", "https://api.avala.ai/api/v1/webhooks/", body)
req.Header.Set("X-Avala-Api-Key", "YOUR_API_KEY")
req.Header.Set("Content-Type", "application/json")

resp, err := http.DefaultClient.Do(req)
```

### Resposta

```json theme={null}
{
  "uid": "c2d3e4f5-a6b7-8c9d-0e1f-2a3b4c5d6e7f",
  "target_url": "https://my-app.example.com/avala-webhook",
  "secret": "<redacted>",
  "events": ["result.submitted", "export.completed"],
  "is_active": true,
  "created_at": "2025-02-10T08:00:00Z",
  "updated_at": "2025-02-10T08:00:00Z"
}
```

> [!WARNING]
>
> O `secret` é retornado apenas uma vez, no momento da criação. Armazene-o com segurança. Use-o para verificar o cabeçalho `X-Avala-Signature` nas entregas recebidas.

***

## Obter webhook

```
GET /api/v1/webhooks/{uid}/
```

Retorna os detalhes de uma assinatura de webhook específica.

### Parâmetros

| Nome | Tipo | Obrigatório | Descrição |
| - | - | - | - |
| `uid` | string (UUID) | Sim | UID da assinatura de webhook (parâmetro de caminho) |

### Requisição

```bash cURL theme={null}
curl "https://api.avala.ai/api/v1/webhooks/c2d3e4f5-a6b7-8c9d-0e1f-2a3b4c5d6e7f/" \
  -H "X-Avala-Api-Key: $AVALA_API_KEY"
```

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

response = requests.get(
    "https://api.avala.ai/api/v1/webhooks/c2d3e4f5-a6b7-8c9d-0e1f-2a3b4c5d6e7f/",
    headers={"X-Avala-Api-Key": "YOUR_API_KEY"}
)
webhook = response.json()
```

```typescript TypeScript theme={null}
const response = await fetch(
  "https://api.avala.ai/api/v1/webhooks/c2d3e4f5-a6b7-8c9d-0e1f-2a3b4c5d6e7f/",
  {
    headers: { "X-Avala-Api-Key": "YOUR_API_KEY" },
  }
);
const webhook = await response.json();
```

```go Go theme={null}
req, _ := http.NewRequest("GET", "https://api.avala.ai/api/v1/webhooks/c2d3e4f5-a6b7-8c9d-0e1f-2a3b4c5d6e7f/", nil)
req.Header.Set("X-Avala-Api-Key", "YOUR_API_KEY")

resp, err := http.DefaultClient.Do(req)
```

### Resposta

```json theme={null}
{
  "uid": "c2d3e4f5-a6b7-8c9d-0e1f-2a3b4c5d6e7f",
  "target_url": "https://my-app.example.com/avala-webhook",
  "events": ["result.submitted", "export.completed"],
  "is_active": true,
  "created_at": "2025-02-10T08:00:00Z",
  "updated_at": "2025-02-10T08:00:00Z"
}
```

### Campos

Os mesmos campos de [Listar webhooks](#campos).

***

## Atualizar webhook

```
PUT /api/v1/webhooks/{uid}/
```

Atualiza uma assinatura de webhook existente. Você também pode usar `PATCH` para atualizações parciais. O segredo não pode ser alterado por este endpoint.

### Parâmetros

| Nome | Tipo | Obrigatório | Descrição |
| - | - | - | - |
| `uid` | string (UUID) | Sim | UID da assinatura de webhook (parâmetro de caminho) |
| `target_url` | string | Sim (PUT) | HTTPS URL para receber as cargas do webhook |
| `events` | array | Sim (PUT) | Tipos de evento a assinar |
| `is_active` | boolean | Não | Indica se o webhook está habilitado |

### Requisição

```bash cURL theme={null}
curl -X PATCH "https://api.avala.ai/api/v1/webhooks/c2d3e4f5-a6b7-8c9d-0e1f-2a3b4c5d6e7f/" \
  -H "X-Avala-Api-Key: $AVALA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "events": ["result.submitted", "result.accepted", "result.rejected"]
  }'
```

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

response = requests.patch(
    "https://api.avala.ai/api/v1/webhooks/c2d3e4f5-a6b7-8c9d-0e1f-2a3b4c5d6e7f/",
    headers={
        "X-Avala-Api-Key": "YOUR_API_KEY",
        "Content-Type": "application/json"
    },
    json={
        "events": ["result.submitted", "result.accepted", "result.rejected"]
    }
)
webhook = response.json()
```

```typescript TypeScript theme={null}
const response = await fetch(
  "https://api.avala.ai/api/v1/webhooks/c2d3e4f5-a6b7-8c9d-0e1f-2a3b4c5d6e7f/",
  {
    method: "PATCH",
    headers: {
      "X-Avala-Api-Key": "YOUR_API_KEY",
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      events: ["result.submitted", "result.accepted", "result.rejected"],
    }),
  }
);
const webhook = await response.json();
```

```go Go theme={null}
body := strings.NewReader(`{
    "events": ["result.submitted", "result.accepted", "result.rejected"]
}`)

req, _ := http.NewRequest("PATCH", "https://api.avala.ai/api/v1/webhooks/c2d3e4f5-a6b7-8c9d-0e1f-2a3b4c5d6e7f/", body)
req.Header.Set("X-Avala-Api-Key", "YOUR_API_KEY")
req.Header.Set("Content-Type", "application/json")

resp, err := http.DefaultClient.Do(req)
```

### Resposta

```json theme={null}
{
  "uid": "c2d3e4f5-a6b7-8c9d-0e1f-2a3b4c5d6e7f",
  "target_url": "https://my-app.example.com/avala-webhook",
  "events": ["result.submitted", "result.accepted", "result.rejected"],
  "is_active": true,
  "created_at": "2025-02-10T08:00:00Z",
  "updated_at": "2025-02-10T12:00:00Z"
}
```

***

## Excluir webhook

```
DELETE /api/v1/webhooks/{uid}/
```

Exclui permanentemente uma assinatura de webhook. Entregas pendentes para este webhook não serão reenviadas.

### Parâmetros

| Nome | Tipo | Obrigatório | Descrição |
| - | - | - | - |
| `uid` | string (UUID) | Sim | UID da assinatura de webhook (parâmetro de caminho) |

### Requisição

```bash cURL theme={null}
curl -X DELETE "https://api.avala.ai/api/v1/webhooks/c2d3e4f5-a6b7-8c9d-0e1f-2a3b4c5d6e7f/" \
  -H "X-Avala-Api-Key: $AVALA_API_KEY"
```

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

response = requests.delete(
    "https://api.avala.ai/api/v1/webhooks/c2d3e4f5-a6b7-8c9d-0e1f-2a3b4c5d6e7f/",
    headers={"X-Avala-Api-Key": "YOUR_API_KEY"}
)
```

```typescript TypeScript theme={null}
const response = await fetch(
  "https://api.avala.ai/api/v1/webhooks/c2d3e4f5-a6b7-8c9d-0e1f-2a3b4c5d6e7f/",
  {
    method: "DELETE",
    headers: { "X-Avala-Api-Key": "YOUR_API_KEY" },
  }
);
```

```go Go theme={null}
req, _ := http.NewRequest("DELETE", "https://api.avala.ai/api/v1/webhooks/c2d3e4f5-a6b7-8c9d-0e1f-2a3b4c5d6e7f/", nil)
req.Header.Set("X-Avala-Api-Key", "YOUR_API_KEY")

resp, err := http.DefaultClient.Do(req)
```

### Resposta

Retorna `204 No Content` em caso de sucesso.

***

## Testar webhook

```
POST /api/v1/webhooks/{uid}/test/
```

Envia um evento de teste `ping` para o URL de destino do webhook. A entrega é processada de forma assíncrona; consulte o endpoint [Listar entregas](#listar-entregas) para ver o resultado.

### Parâmetros

| Nome | Tipo | Obrigatório | Descrição |
| - | - | - | - |
| `uid` | string (UUID) | Sim | UID da assinatura de webhook (parâmetro de caminho) |

### Requisição

```bash cURL theme={null}
curl -X POST "https://api.avala.ai/api/v1/webhooks/c2d3e4f5-a6b7-8c9d-0e1f-2a3b4c5d6e7f/test/" \
  -H "X-Avala-Api-Key: $AVALA_API_KEY"
```

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

response = requests.post(
    "https://api.avala.ai/api/v1/webhooks/c2d3e4f5-a6b7-8c9d-0e1f-2a3b4c5d6e7f/test/",
    headers={"X-Avala-Api-Key": "YOUR_API_KEY"}
)
result = response.json()
```

```typescript TypeScript theme={null}
const response = await fetch(
  "https://api.avala.ai/api/v1/webhooks/c2d3e4f5-a6b7-8c9d-0e1f-2a3b4c5d6e7f/test/",
  {
    method: "POST",
    headers: { "X-Avala-Api-Key": "YOUR_API_KEY" },
  }
);
const result = await response.json();
```

```go Go theme={null}
req, _ := http.NewRequest("POST", "https://api.avala.ai/api/v1/webhooks/c2d3e4f5-a6b7-8c9d-0e1f-2a3b4c5d6e7f/test/", nil)
req.Header.Set("X-Avala-Api-Key", "YOUR_API_KEY")

resp, err := http.DefaultClient.Do(req)
```

### Resposta

```json theme={null}
{
  "detail": "Test webhook queued.",
  "delivery_uid": "f6a7b8c9-d0e1-2f3a-4b5c-6d7e8f9a0b1c"
}
```

***

## Listar entregas

```
GET /api/v1/webhook-deliveries/
```

Retorna todas as tentativas de entrega de webhook da organização do usuário autenticado, ordenadas da mais recente para a mais antiga.

### Parâmetros

| Nome | Tipo | Obrigatório | Descrição |
| - | - | - | - |
| `cursor` | string | Não | Cursor para paginação (parâmetro de consulta) |
| `limit` | integer | Não | Número de resultados por página (parâmetro de consulta) |

### Requisição

```bash cURL theme={null}
curl "https://api.avala.ai/api/v1/webhook-deliveries/" \
  -H "X-Avala-Api-Key: $AVALA_API_KEY"
```

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

response = requests.get(
    "https://api.avala.ai/api/v1/webhook-deliveries/",
    headers={"X-Avala-Api-Key": "YOUR_API_KEY"}
)
deliveries = response.json()["results"]
```

```typescript TypeScript theme={null}
const response = await fetch(
  "https://api.avala.ai/api/v1/webhook-deliveries/",
  {
    headers: { "X-Avala-Api-Key": "YOUR_API_KEY" },
  }
);
const { results } = await response.json();
```

```go Go theme={null}
req, _ := http.NewRequest("GET", "https://api.avala.ai/api/v1/webhook-deliveries/", nil)
req.Header.Set("X-Avala-Api-Key", "YOUR_API_KEY")

resp, err := http.DefaultClient.Do(req)
```

### Resposta

```json theme={null}
{
  "next": null,
  "previous": null,
  "results": [
    {
      "uid": "f6a7b8c9-d0e1-2f3a-4b5c-6d7e8f9a0b1c",
      "subscription": "c2d3e4f5-a6b7-8c9d-0e1f-2a3b4c5d6e7f",
      "event_type": "result.submitted",
      "payload": {
        "event": "result.submitted",
        "result_uid": "990c1800-b62f-85a8-e150-880099881111"
      },
      "response_status": 200,
      "response_body": "{\"ok\": true}",
      "attempts": 1,
      "next_retry_at": null,
      "status": "delivered",
      "created_at": "2025-02-10T14:00:00Z",
      "updated_at": "2025-02-10T14:00:01Z"
    }
  ]
}
```

### Campos da entrega

| Campo | Tipo | Descrição |
| - | - | - |
| `uid` | string (UUID) | Identificador único da entrega |
| `subscription` | string (UUID) | UID da assinatura de webhook |
| `event_type` | string | Tipo de evento que disparou esta entrega |
| `payload` | objeto | Carga do evento que foi enviada |
| `response_status` | integer \| null | Código de status HTTP do URL de destino |
| `response_body` | string \| null | Corpo da resposta do URL de destino |
| `attempts` | integer | Número de tentativas de entrega realizadas |
| `next_retry_at` | string (datetime) \| null | Quando a próxima nova tentativa está agendada, se aplicável |
| `status` | string | Status da entrega (veja [Status de entrega](#status-de-entrega)) |
| `created_at` | string (datetime) | Carimbo de data/hora ISO 8601 da criação |
| `updated_at` | string (datetime) | Timestamp ISO 8601 da última atualização |

***

## Obter entrega

```
GET /api/v1/webhook-deliveries/{uid}/
```

Retorna os detalhes de uma entrega de webhook específica.

### Parâmetros

| Nome | Tipo | Obrigatório | Descrição |
| - | - | - | - |
| `uid` | string (UUID) | Sim | UID da entrega (parâmetro de caminho) |

### Requisição

```bash cURL theme={null}
curl "https://api.avala.ai/api/v1/webhook-deliveries/f6a7b8c9-d0e1-2f3a-4b5c-6d7e8f9a0b1c/" \
  -H "X-Avala-Api-Key: $AVALA_API_KEY"
```

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

response = requests.get(
    "https://api.avala.ai/api/v1/webhook-deliveries/f6a7b8c9-d0e1-2f3a-4b5c-6d7e8f9a0b1c/",
    headers={"X-Avala-Api-Key": "YOUR_API_KEY"}
)
delivery = response.json()
```

```typescript TypeScript theme={null}
const response = await fetch(
  "https://api.avala.ai/api/v1/webhook-deliveries/f6a7b8c9-d0e1-2f3a-4b5c-6d7e8f9a0b1c/",
  {
    headers: { "X-Avala-Api-Key": "YOUR_API_KEY" },
  }
);
const delivery = await response.json();
```

```go Go theme={null}
req, _ := http.NewRequest("GET", "https://api.avala.ai/api/v1/webhook-deliveries/f6a7b8c9-d0e1-2f3a-4b5c-6d7e8f9a0b1c/", nil)
req.Header.Set("X-Avala-Api-Key", "YOUR_API_KEY")

resp, err := http.DefaultClient.Do(req)
```

### Resposta

O mesmo formato dos itens individuais em [Listar entregas](#listar-entregas).

***

## Tipos de evento

| Evento | Descrição |
| - | - |
| `dataset.created` | Um novo conjunto de dados foi criado |
| `dataset.updated` | Um conjunto de dados existente foi atualizado |
| `dataset.deleted` | Um conjunto de dados foi excluído |
| `export.completed` | Um trabalho de exportação foi concluído com sucesso |
| `export.failed` | Um trabalho de exportação falhou |
| `task.completed` | Uma tarefa foi marcada como concluída |
| `result.submitted` | Um resultado de anotação foi enviado |
| `result.accepted` | Um resultado de anotação foi aceito |
| `result.rejected` | Um resultado de anotação foi rejeitado |
| `auto_label.completed` | Um job de rotulagem automática foi concluído com sucesso |
| `auto_label.failed` | Um job de rotulagem automática falhou |
| `quality.alert` | Um limite de meta de qualidade foi ultrapassado |

***

## Status de entrega

| Status | Descrição |
| - | - |
| `pending` | A entrega está na fila e ainda não foi tentada |
| `delivered` | A carga foi entregue com sucesso (resposta 2xx recebida) |
| `failed` | Todas as tentativas de entrega falharam |

## Comportamento de novas tentativas

Entregas com falha são reenviadas automaticamente com espera exponencial (backoff). A Avala faz até **5 novas tentativas** antes de marcar uma entrega como `failed`.

| Tentativa | Atraso | Tempo total decorrido |
| - | - | - |
| 1 (inicial) | Imediata | 0s |
| 2 | 60 segundos | 1 min |
| 3 | 120 segundos | 3 min |
| 4 | 240 segundos | 7 min |
| 5 | 480 segundos | 15 min |
| 6 | 960 segundos | 31 min |

**Regras de nova tentativa:**

* **Respostas 2xx** são tratadas como bem-sucedidas. Sem nova tentativa.
* **Respostas 4xx** (erros do cliente) **não são reenviadas**. Elas indicam um problema no seu endpoint (URL inválido, falha de autenticação, carga rejeitada). Corrija seu endpoint e use o endpoint [Testar webhook](#testar-webhook) para verificar novamente.
* **Respostas 5xx** e **erros de rede** (timeout, conexão recusada) são reenviadas conforme o cronograma de espera acima.
* O campo `next_retry_at` em uma entrega mostra quando a próxima tentativa está agendada. Ele é `null` para entregas concluídas ou com falha permanente.

> [!TIP]
>
> Projete seu endpoint de webhook para ser **idempotente**. Se você receber o mesmo evento duas vezes (devido a novas tentativas ou problemas de rede), seu manipulador deve produzir o mesmo resultado. Use o `uid` da entrega como chave de deduplicação.

### Verificação de assinatura

Toda entrega inclui um cabeçalho `X-Avala-Webhook-Signature`. Verifique-o usando o `secret` de quando você criou o webhook:

```python theme={null}
import hashlib
import hmac

def verify_signature(payload_body: bytes, signature: str, secret: str) -> bool:
    expected = hmac.HMAC(
        secret.encode(), payload_body, hashlib.sha256
    ).hexdigest()
    return hmac.compare_digest(expected, signature)
```

Sempre verifique as assinaturas antes de processar as cargas do webhook para evitar eventos falsificados.

***

## Respostas de erro

### Erro de validação (400)

```json theme={null}
{
  "events": ["Invalid events: invalid.event"],
  "target_url": ["A webhook subscription for this URL already exists."]
}
```

Retornado quando o corpo da requisição contém eventos inválidos ou um URL de destino duplicado.

### Não autorizado (401)

```json theme={null}
{
  "detail": "Invalid API key."
}
```

Retornado quando o cabeçalho `X-Avala-Api-Key` está ausente ou contém uma chave inválida.

### Permissão negada (403)

```json theme={null}
{
  "detail": "You do not have permission to perform this action."
}
```

Retornado quando o usuário autenticado não tem acesso ao webhook solicitado.

### Não encontrado (404)

```json theme={null}
{
  "detail": "Not found."
}
```

Retornado quando o webhook ou a entrega UID especificado não existe.
