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

# Fluxos comuns

> Guias de fluxos de trabalho completos para casos de uso comuns da API

Esta página apresenta fluxos de trabalho completos comuns com a API do Devin. Cada fluxo inclui a sequência completa de chamadas à API, com exemplos de código. Para detalhes de cada endpoint, consulte as páginas relevantes da referência da API.

<div id="setup">
  ## Configuração
</div>

Defina estas variáveis de ambiente antes de executar qualquer exemplo:

```bash theme={null}
# Obrigatório: a chave de API do seu service user (começa com cog_)
export DEVIN_API_KEY="cog_your_key_here"

# Obrigatório: o ID da sua organização (encontre em Configurações > Usuários de serviço)
export DEVIN_ORG_ID="your_org_id"
```

***

<div id="getting-started-api-key-to-first-session">
  ## Primeiros passos: da Chave de API à primeira sessão
</div>

O fluxo de trabalho mais comum — autenticar-se, identificar sua conta e criar sua primeira sessão.

<div id="step-1-verify-your-credentials">
  ### Etapa 1: Verifique suas credenciais
</div>

<Note>Usuários de serviço com escopo de organização podem pular para a Etapa 3 — você já sabe o ID da sua organização na página Configurações.</Note>

```bash theme={null}
curl "https://api.devin.ai/v3/self" \
  -H "Authorization: Bearer $DEVIN_API_KEY"
```

Resposta:

```json theme={null}
{
  "principal_type": "service_user",
  "service_user_id": "service-user-abc123",
  "service_user_name": "CI Bot",
  "org_id": null
}
```

<div id="step-2-list-your-organizations">
  ### Etapa 2: Liste suas organizações
</div>

**Usuários de serviço Enterprise** podem listar todas as organizações:

```bash theme={null}
curl "https://api.devin.ai/v3/enterprise/organizations" \
  -H "Authorization: Bearer $DEVIN_API_KEY"
```

**Usuário de serviço com escopo de organização** já sabe o ID da org (ele está na página Configurações > Usuários de serviço, onde a chave foi criada).

<div id="step-3-create-a-session">
  ### Etapa 3: Criar uma sessão
</div>

```bash theme={null}
curl -X POST "https://api.devin.ai/v3/organizations/$DEVIN_ORG_ID/sessions" \
  -H "Authorization: Bearer $DEVIN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"prompt": "Create a Python script that analyzes CSV data"}'
```

Resposta:

```json theme={null}
{
  "session_id": "devin-abc123",
  "url": "https://app.devin.ai/sessions/devin-abc123",
  "status": "running"
}
```

<div id="step-4-poll-for-events">
  ### Etapa 4: Consultar eventos periodicamente
</div>

Monitore a sessão consultando periodicamente as mensagens:

```bash theme={null}
curl "https://api.devin.ai/v3/organizations/$DEVIN_ORG_ID/sessions/devin-abc123/messages" \
  -H "Authorization: Bearer $DEVIN_API_KEY"
```

<div id="full-python-example">
  ### Exemplo completo em Python
</div>

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

API_KEY = os.environ["DEVIN_API_KEY"]
ORG_ID = os.environ["DEVIN_ORG_ID"]
BASE = "https://api.devin.ai/v3"
HEADERS = {"Authorization": f"Bearer {API_KEY}"}

# 1. Verificar credenciais
me = requests.get(f"{BASE}/self", headers=HEADERS)
me.raise_for_status()
data = me.json()
print(f"Authenticated as: {data.get('service_user_name') or data.get('user_name')}")

# 2. Criar uma sessão
session = requests.post(
    f"{BASE}/organizations/{ORG_ID}/sessions",
    headers={**HEADERS, "Content-Type": "application/json"},
    json={"prompt": "Create a Python script that analyzes CSV data"}
).json()
print(f"Session: {session['url']}")

# 3. Consultar até concluir
while True:
    status = requests.get(
        f"{BASE}/organizations/{ORG_ID}/sessions/{session['session_id']}",
        headers=HEADERS
    ).json()["status"]
    print(f"Status: {status}")
    if status in ("exit", "error", "suspended"):
        break
    time.sleep(10)
```

***

<div id="downloading-session-attachments">
  ## Baixar anexos da sessão
</div>

Baixe os arquivos produzidos em uma sessão (logs, capturas de tela, código gerado etc.).

<div id="step-1-get-the-session">
  ### Etapa 1: Obter a sessão
</div>

```bash theme={null}
curl "https://api.devin.ai/v3/organizations/$DEVIN_ORG_ID/sessions/$SESSION_ID" \
  -H "Authorization: Bearer $DEVIN_API_KEY"
```

<div id="step-2-list-attachments">
  ### Etapa 2: Listar anexos
</div>

```bash theme={null}
curl "https://api.devin.ai/v3/organizations/$DEVIN_ORG_ID/sessions/$SESSION_ID/attachments" \
  -H "Authorization: Bearer $DEVIN_API_KEY"
```

Resposta:

```json theme={null}
{
  "items": [
    {
      "attachment_id": "att_123",
      "name": "output.py",
      "url": "https://..."
    }
  ]
}
```

<div id="step-3-download">
  ### Etapa 3: Baixar
</div>

Use a `url` retornada na resposta do anexo para baixar o arquivo diretamente.

<div id="full-python-example">
  ### Exemplo completo em Python
</div>

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

API_KEY = os.environ["DEVIN_API_KEY"]
ORG_ID = os.environ["DEVIN_ORG_ID"]
SESSION_ID = os.environ["SESSION_ID"]
BASE = "https://api.devin.ai/v3"
HEADERS = {"Authorization": f"Bearer {API_KEY}"}

# Listar anexos
attachments = requests.get(
    f"{BASE}/organizations/{ORG_ID}/sessions/{SESSION_ID}/attachments",
    headers=HEADERS
).json()["items"]

# Baixar cada anexo
for att in attachments:
    print(f"Baixando {att['name']}...")
    content = requests.get(att["url"]).content
    with open(att["name"], "wb") as f:
        f.write(content)
    print(f"  Salvo {att['name']} ({len(content)} bytes)")
```

***

<div id="knowledge-playbook-management">
  ## Gerenciamento de Knowledge e playbook
</div>

Gerencie o contexto e as instruções que o Devin usa entre sessões.

<div id="create-a-knowledge-note">
  ### Criar uma nota do Knowledge
</div>

```bash theme={null}
curl -X POST "https://api.devin.ai/v3/organizations/$DEVIN_ORG_ID/knowledge/notes" \
  -H "Authorization: Bearer $DEVIN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Coding standards",
    "trigger": "When writing code in any repository",
    "body": "Use TypeScript strict mode. Follow existing code style. Run lint before committing."
  }'
```

<div id="list-knowledge-notes">
  ### Listar notas do Knowledge
</div>

```bash theme={null}
curl "https://api.devin.ai/v3/organizations/$DEVIN_ORG_ID/knowledge/notes" \
  -H "Authorization: Bearer $DEVIN_API_KEY"
```

<div id="update-a-knowledge-note">
  ### Atualizar uma nota do Knowledge
</div>

```bash theme={null}
curl -X PUT "https://api.devin.ai/v3/organizations/$DEVIN_ORG_ID/knowledge/notes/$NOTE_ID" \
  -H "Authorization: Bearer $DEVIN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Coding standards (updated)",
    "trigger": "When writing code in any repository",
    "body": "Use TypeScript strict mode. Follow existing code style. Run lint and type-check before committing."
  }'
```

<div id="delete-a-knowledge-note">
  ### Excluir uma nota do Knowledge
</div>

```bash theme={null}
curl -X DELETE "https://api.devin.ai/v3/organizations/$DEVIN_ORG_ID/knowledge/notes/$NOTE_ID" \
  -H "Authorization: Bearer $DEVIN_API_KEY"
```

<div id="create-a-playbook">
  ### Criar um playbook
</div>

```bash theme={null}
curl -X POST "https://api.devin.ai/v3/organizations/$DEVIN_ORG_ID/playbooks" \
  -H "Authorization: Bearer $DEVIN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "PR Review",
    "instructions": "Review the PR for bugs, security issues, and style violations. Leave inline comments."
  }'
```

<div id="full-python-example">
  ### Exemplo completo em Python
</div>

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

API_KEY = os.environ["DEVIN_API_KEY"]
ORG_ID = os.environ["DEVIN_ORG_ID"]
BASE = "https://api.devin.ai/v3"
HEADERS = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json"
}

# Criar nota de Knowledge
note = requests.post(
    f"{BASE}/organizations/{ORG_ID}/knowledge/notes",
    headers=HEADERS,
    json={
        "name": "Coding standards",
        "trigger": "When writing code in any repository",
        "body": "Use TypeScript strict mode. Follow existing code style."
    }
).json()
print(f"Created note: {note['note_id']}")

# Listar todas as notas
notes = requests.get(
    f"{BASE}/organizations/{ORG_ID}/knowledge/notes",
    headers={"Authorization": f"Bearer {API_KEY}"}
).json()["items"]
print(f"Total notes: {len(notes)}")

# Criar playbook
playbook = requests.post(
    f"{BASE}/organizations/{ORG_ID}/playbooks",
    headers=HEADERS,
    json={
        "name": "PR Review",
        "instructions": "Review the PR for bugs, security issues, and style violations."
    }
).json()
print(f"Created playbook: {playbook['playbook_id']}")
```

***

<div id="scheduling-automated-sessions">
  ## Agendamento de sessões automatizadas
</div>

Crie sessões recorrentes executadas de acordo com um agendamento.

<div id="create-a-schedule">
  ### Criar um agendamento
</div>

```bash theme={null}
curl -X POST "https://api.devin.ai/v3/organizations/$DEVIN_ORG_ID/schedules" \
  -H "Authorization: Bearer $DEVIN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "Run the test suite and report any failures",
    "cron_schedule": "0 9 * * 1-5",
    "timezone": "America/New_York"
  }'
```

Isso cria um agendamento executado em todos os dias úteis às 9h, no horário do leste dos EUA.

<div id="list-schedules">
  ### Listar agendamentos
</div>

```bash theme={null}
curl "https://api.devin.ai/v3/organizations/$DEVIN_ORG_ID/schedules" \
  -H "Authorization: Bearer $DEVIN_API_KEY"
```

<div id="update-a-schedule">
  ### Atualizar um agendamento
</div>

```bash theme={null}
curl -X PATCH "https://api.devin.ai/v3/organizations/$DEVIN_ORG_ID/schedules/$SCHEDULE_ID" \
  -H "Authorization: Bearer $DEVIN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "cron_schedule": "0 8 * * 1-5",
    "is_enabled": true
  }'
```

<div id="delete-a-schedule">
  ### Excluir um agendamento
</div>

```bash theme={null}
curl -X DELETE "https://api.devin.ai/v3/organizations/$DEVIN_ORG_ID/schedules/$SCHEDULE_ID" \
  -H "Authorization: Bearer $DEVIN_API_KEY"
```

<div id="full-python-example">
  ### Exemplo completo em Python
</div>

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

API_KEY = os.environ["DEVIN_API_KEY"]
ORG_ID = os.environ["DEVIN_ORG_ID"]
BASE = "https://api.devin.ai/v3"
HEADERS = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json"
}

# Criar um agendamento diário de verificação de integridade
schedule = requests.post(
    f"{BASE}/organizations/{ORG_ID}/schedules",
    headers=HEADERS,
    json={
        "prompt": "Run the test suite and report any failures",
        "cron_schedule": "0 9 * * 1-5",
        "timezone": "America/New_York"
    }
).json()
print(f"Created schedule: {schedule['schedule_id']}")

# Listar todos os agendamentos
schedules = requests.get(
    f"{BASE}/organizations/{ORG_ID}/schedules",
    headers={"Authorization": f"Bearer {API_KEY}"}
).json()["items"]

for s in schedules:
    status = "enabled" if s.get("is_enabled") else "disabled"
    print(f"  {s['schedule_id']}: {s['cron_schedule']} ({status})")
```

***

<div id="hand-off-a-task-from-anywhere">
  ## Passe uma tarefa de qualquer lugar
</div>

Como a Sessions API cria uma sessão do Devin na nuvem a partir de uma única requisição, qualquer ferramenta, script ou agente de codificação pode "passar" o trabalho para o Devin, incluindo no prompt o repositório atual, a branch e as alterações ainda não comitadas, para que a sessão na nuvem continue de onde você parou.

<div id="create-a-session-with-repo-context">
  ### Criar uma sessão com contexto de repositório
</div>

```bash theme={null}
# Constrói o corpo JSON com jq para que o diff bruto — que contém aspas,
# barras invertidas e quebras de linha — seja escapado em uma string JSON válida.
curl -X POST "https://api.devin.ai/v3/organizations/$DEVIN_ORG_ID/sessions" \
  -H "Authorization: Bearer $DEVIN_API_KEY" \
  -H "Content-Type: application/json" \
  -d "$(jq -n --arg diff "$(git diff HEAD)" \
    '{prompt: "Repo: my-org/my-repo (branch: fix-flaky-tests)\nFix the flaky integration tests in CI.\n\nUncommitted changes:\n\($diff)"}')"
```

A sessão na nuvem clona o repositório, aplica o contexto do seu prompt e roda em sua própria VM com um shell, navegador e acesso completo ao repositório. Acompanhe-a [consultando as mensagens](#step-4-poll-for-events) ou no [app web do Devin](https://app.devin.ai).

<Warning>
  `git diff HEAD` pode incluir segredos ainda não comitados — chaves de API, tokens ou edições em `.env` — e o prompt é importado para a sessão na nuvem. Revise seu diff e faça commit, stash ou remova alterações sensíveis antes de transferir.
</Warning>

<Tip>
  Não quer montar isso por conta própria? O plugin open-source [Devin Handoff](https://github.com/club-cog/devin-handoff) encapsula exatamente esse fluxo — detectando automaticamente repositório, branch e diff — para que você possa transferir a partir do Devin CLI, Claude Code, Codex, Cursor ou de um script de shell simples. Veja [Transferir para o Devin](/pt-BR/work-with-devin/devin-handoff).
</Tip>

***

<div id="error-handling">
  ## Tratamento de erros
</div>

Todos os exemplos acima devem incluir tratamento de erros em ambiente de produção. Aqui está um padrão reutilizável:

```python theme={null}
import requests

def api_request(method, url, headers, **kwargs):
    """Make an API request with standard error handling."""
    response = requests.request(method, url, headers=headers, **kwargs)
    try:
        response.raise_for_status()
        return response.json()
    except requests.exceptions.HTTPError as e:
        status = e.response.status_code
        if status == 401:
            raise Exception("Invalid or expired API key")
        elif status == 403:
            raise Exception("Service user lacks required permission")
        elif status == 404:
            raise Exception("Resource not found")
        elif status == 429:
            raise Exception("Rate limit exceeded — wait and retry")
        else:
            raise Exception(f"API error {status}: {e.response.text}")
```

<div id="support">
  ## Suporte
</div>

<Card title="Precisa de ajuda?">
  Em caso de dúvidas sobre a API ou para relatar problemas, envie um e-mail para [support@cognition.ai](mailto:support@cognition.ai)
</Card>
