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

# REST API

> Use a Avala API diretamente com requisições HTTP

Você pode chamar a Avala API diretamente via HTTP a partir de qualquer linguagem de programação, script de shell ou ferramenta de automação. Nenhum SDK necessário.

## URL base

Todas as requisições da API são feitas para:

```
https://api.avala.ai/api/v1
```

## Autenticação

Toda requisição deve incluir sua chave de API no cabeçalho `X-Avala-Api-Key`.

```
X-Avala-Api-Key: your-api-key
```

Você pode encontrar sua chave de API no [Avala painel](https://avala.ai/settings?section=security) em **Settings > Security**.

## Fazendo requisições

Abaixo estão exemplos de listagem de conjuntos de dados em várias linguagens.

```bash cURL theme={null}
curl -X GET "https://api.avala.ai/api/v1/datasets/" \
  -H "X-Avala-Api-Key: $AVALA_API_KEY" \
  -H "Content-Type: application/json"
```

```python Python (requests) theme={null}
import requests
import os

response = requests.get(
    "https://api.avala.ai/api/v1/datasets/",
    headers={
        "X-Avala-Api-Key": os.environ["AVALA_API_KEY"],
        "Content-Type": "application/json",
    },
)

data = response.json()
for dataset in data["results"]:
    print(dataset["name"], dataset["uid"])
```

```go Go (net/http) theme={null}
package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"os"
)

func main() {
	req, _ := http.NewRequest("GET", "https://api.avala.ai/api/v1/datasets/", nil)
	req.Header.Set("X-Avala-Api-Key", os.Getenv("AVALA_API_KEY"))
	req.Header.Set("Content-Type", "application/json")

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	var result map[string]interface{}
	json.NewDecoder(resp.Body).Decode(&result)
	fmt.Println(result)
}
```

```ruby Ruby theme={null}
require "net/http"
require "json"

uri = URI("https://api.avala.ai/api/v1/datasets/")

request = Net::HTTP::Get.new(uri)
request["X-Avala-Api-Key"] = ENV["AVALA_API_KEY"]
request["Content-Type"] = "application/json"

response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
  http.request(request)
end

data = JSON.parse(response.body)
data["results"].each do |dataset|
  puts "#{dataset["name"]} (#{dataset["uid"]})"
end
```

```php PHP theme={null}
<?php

$ch = curl_init();

curl_setopt_array($ch, [
    CURLOPT_URL => "https://api.avala.ai/api/v1/datasets/",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        "X-Avala-Api-Key: " . getenv("AVALA_API_KEY"),
        "Content-Type: application/json",
    ],
]);

$response = curl_exec($ch);
curl_close($ch);

$data = json_decode($response, true);
foreach ($data["results"] as $dataset) {
    echo $dataset["name"] . " (" . $dataset["uid"] . ")\n";
}
```

## Tratando a paginação

Os endpoints de listagem retornam resultados paginados usando paginação baseada em cursor com os campos `next`, `previous` e `results`.

**Estrutura da resposta:**

```json theme={null}
{
  "next": "https://api.avala.ai/api/v1/datasets/?cursor=cD0yMDI0...",
  "previous": null,
  "results": [...]
}
```

| Campo | Tipo | Descrição |
| - | - | - |
| `next` | string \| null | URL da próxima página, ou `null` se esta for a última página |
| `previous` | string \| null | URL da página anterior, ou `null` se esta for a primeira página |
| `results` | array | Array de objetos de recurso da página atual |

**Paginando por todos os resultados:**

```bash cURL theme={null}
# First page
curl -s "https://api.avala.ai/api/v1/datasets/?limit=50" \
  -H "X-Avala-Api-Key: $AVALA_API_KEY" | jq .

# Next page (use the full `next` URL from previous response)
curl -s "https://api.avala.ai/api/v1/datasets/?cursor=cD0yMDI0&limit=50" \
  -H "X-Avala-Api-Key: $AVALA_API_KEY" | jq .
```

```python Python (requests) theme={null}
import requests
import os

base_url = "https://api.avala.ai/api/v1"
headers = {"X-Avala-Api-Key": os.environ["AVALA_API_KEY"]}

all_datasets = []
url = f"{base_url}/datasets/?limit=50"

while url:
    response = requests.get(url, headers=headers)
    data = response.json()

    all_datasets.extend(data["results"])
    url = data.get("next")

print(f"Fetched {len(all_datasets)} datasets")
```

## Tratamento de erros

A API retorna códigos de status HTTP padrão. As respostas de erro incluem um corpo JSON com detalhes.

**Formato da resposta de erro:**

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

Para erros de validação, a DRF retorna erros no nível de campo:

```json theme={null}
{
  "field_name": ["This field is required."]
}
```

| Código de status | Significado |
| - | - |
| `200` | Sucesso |
| `201` | Criado |
| `400` | Requisição inválida — verifique o campo `detail` ou os erros no nível de campo no corpo da resposta. |
| `401` | Não autorizado — chave de API inválida ou ausente. |
| `404` | Não encontrado — o recurso não existe. |
| `429` | Limite de taxa atingido — requisições demais. Respeite o cabeçalho `Retry-After`. |
| `500` | Erro interno do servidor — tente novamente mais tarde. |

### Tratando erros no código

```python Python (requests) theme={null}
import requests
import os
import time

headers = {"X-Avala-Api-Key": os.environ["AVALA_API_KEY"]}

response = requests.get(
    "https://api.avala.ai/api/v1/datasets/nonexistent/",
    headers=headers,
)

if response.status_code == 200:
    data = response.json()
elif response.status_code == 401:
    print("Invalid API key. Check your AVALA_API_KEY.")
elif response.status_code == 404:
    print("Resource not found.")
elif response.status_code == 429:
    retry_after = int(response.headers.get("Retry-After", 60))
    print(f"Rate limited. Retrying in {retry_after}s...")
    time.sleep(retry_after)
else:
    print(f"Error {response.status_code}: {response.json().get('detail', 'Unknown error')}")
```

```bash cURL theme={null}
# Check the HTTP status code
STATUS=$(curl -s -o /dev/null -w "%{http_code}" \
  "https://api.avala.ai/api/v1/datasets/nonexistent/" \
  -H "X-Avala-Api-Key: $AVALA_API_KEY")

if [ "$STATUS" = "429" ]; then
  echo "Rate limited. Check Retry-After header."
elif [ "$STATUS" != "200" ]; then
  echo "Error: HTTP $STATUS"
fi
```

> [!WARNING]
>
> Ao receber uma resposta `429`, sempre verifique o cabeçalho `Retry-After` para saber o número de segundos de espera antes de tentar novamente. O cabeçalho `X-RateLimit-Remaining` em cada resposta informa quantas requisições ainda restam.

## Uploads de arquivos

Os uploads de arquivos usam URLs pré-assinadas em vez de uploads multipart diretos para a API. O fluxo geral é:

1. Solicite uma URL de upload pré-assinada à API
2. Envie o arquivo diretamente para o armazenamento em nuvem usando a URL pré-assinada
3. Confirme o upload com a API

```bash cURL theme={null}
# Step 1: Request presigned URL
UPLOAD_INFO=$(curl -s -X POST "https://api.avala.ai/api/v1/datasets/manual-upload/file-upload-url/" \
  -H "X-Avala-Api-Key: $AVALA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"file_path_in_dataset": "image001.jpg", "dataset_name": "my-dataset"}')

PRESIGNED_URL=$(echo $UPLOAD_INFO | jq -r '.url')

# Step 2: Upload to cloud storage using the presigned POST fields
# All fields from the response must be included as form data
curl -X POST "$PRESIGNED_URL" \
  $(echo $UPLOAD_INFO | jq -r '.fields | to_entries[] | "-F \(.key)=\(.value)"') \
  -F "file=@./image001.jpg"
```

```python Python (requests) theme={null}
import requests
import os

headers = {"X-Avala-Api-Key": os.environ["AVALA_API_KEY"]}

# Step 1: Request presigned URL
response = requests.post(
    "https://api.avala.ai/api/v1/datasets/manual-upload/file-upload-url/",
    headers=headers,
    json={"file_path_in_dataset": "image001.jpg", "dataset_name": "my-dataset"},
)
upload_info = response.json()

# Step 2: Upload to cloud storage using the presigned POST fields
with open("image001.jpg", "rb") as f:
    requests.post(
        upload_info["url"],
        data=upload_info["fields"],
        files={"file": ("image001.jpg", f)},
    )
```

## Padrões comuns

### Listar todos os itens com paginação

Este padrão busca todos os itens de um conjunto de dados seguindo as URLs de paginação até que todas as páginas tenham sido recuperadas.

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

base_url = "https://api.avala.ai/api/v1"
headers = {"X-Avala-Api-Key": os.environ["AVALA_API_KEY"]}

def get_all_items(owner, slug):
    items = []
    url = f"{base_url}/datasets/{owner}/{slug}/items/?limit=100"

    while url:
        response = requests.get(url, headers=headers)
        response.raise_for_status()
        data = response.json()

        items.extend(data["results"])
        url = data.get("next")

    return items

all_items = get_all_items("acme-ai", "training-v2")
print(f"Total items: {len(all_items)}")
```

### Criar e aguardar uma exportação

Este padrão inicia um job de exportação e faz polling até que ele termine, e então recupera a URL de download.

```bash theme={null}
# Start the export
EXPORT=$(curl -s -X POST "https://api.avala.ai/api/v1/exports/" \
  -H "X-Avala-Api-Key: $AVALA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"project_id": "project_abc123"}')

EXPORT_UID=$(echo $EXPORT | jq -r '.uid')
echo "Export started: $EXPORT_UID"

# Poll until completed
while true; do
  STATUS=$(curl -s "https://api.avala.ai/api/v1/exports/$EXPORT_UID/" \
    -H "X-Avala-Api-Key: $AVALA_API_KEY" | jq -r '.status')

  echo "Status: $STATUS"

  if [ "$STATUS" = "completed" ]; then
    break
  fi

  sleep 2
done

# Get the download URL
DOWNLOAD_URL=$(curl -s "https://api.avala.ai/api/v1/exports/$EXPORT_UID/" \
  -H "X-Avala-Api-Key: $AVALA_API_KEY" | jq -r '.download_url')

echo "Download: $DOWNLOAD_URL"
```
