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

# Flussi comuni

> Guide ai flussi di lavoro end-to-end per i casi d'uso più comuni dell'API

Questa pagina descrive i flussi di lavoro end-to-end più comuni con l'API di Devin. Ogni flusso include la sequenza completa delle chiamate API con esempi di codice. Per i dettagli sui singoli endpoint, consulta le pagine di riferimento dell'API pertinenti.

<div id="setup">
  ## Configurazione
</div>

Imposta queste environment variables prima di eseguire qualsiasi esempio:

```bash theme={null}
# Obbligatorio: l'API key del tuo utente di servizio (inizia con cog_)
export DEVIN_API_KEY="cog_your_key_here"

# Obbligatorio: l'ID della tua organizzazione (trovalo in Settings > Service Users)
export DEVIN_ORG_ID="your_org_id"
```

***

<div id="getting-started-api-key-to-first-session">
  ## Per iniziare: dall'API key alla prima sessione
</div>

Il flusso di lavoro più comune: autenticarsi, individuare il proprio account e creare la prima sessione.

<div id="step-1-verify-your-credentials">
  ### Passaggio 1: Verifica le tue credenziali
</div>

<Note>Gli utente di servizio con ambito organizzazione possono passare al Passaggio 3 — conosci già il tuo ID org dalla pagina Settings.</Note>

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

Risposta:

```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">
  ### Passaggio 2: Elenca le tue organizzazioni
</div>

**Gli utenti di servizio Enterprise** possono elencare tutte le organizzazioni:

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

**Gli utenti di servizio con ambito organizzazione** conoscono già il proprio ID org (è indicato nella pagina Settings > Service Users in cui è stata creata la chiave).

<div id="step-3-create-a-session">
  ### Passaggio 3: Creare una sessione
</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"}'
```

Risposta:

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

<div id="step-4-poll-for-events">
  ### Passaggio 4: Esegui il polling degli eventi
</div>

Monitora la sessione effettuando il polling dei messaggi:

```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">
  ### Esempio completo in 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. Verifica le credenziali
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. Crea una sessione
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. Esegui il polling fino al completamento
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">
  ## Scaricare gli allegati della sessione
</div>

Recupera i file generati da una sessione (log, screenshot, codice generato, ecc.).

<div id="step-1-get-the-session">
  ### Passaggio 1: Recupera la sessione
</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">
  ### Passaggio 2: Elencare gli allegati
</div>

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

Risposta:

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

<div id="step-3-download">
  ### Passaggio 3: Scaricamento
</div>

Usa l'`url` restituito nella risposta dell'allegato per scaricare direttamente il file.

<div id="full-python-example">
  ### Esempio completo in 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}"}

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

# Scarica ogni allegato
for att in attachments:
    print(f"Downloading {att['name']}...")
    content = requests.get(att["url"]).content
    with open(att["name"], "wb") as f:
        f.write(content)
    print(f"  Saved {att['name']} ({len(content)} bytes)")
```

***

<div id="knowledge-playbook-management">
  ## Gestione di Knowledge e playbook
</div>

Gestisci il contesto e le istruzioni che Devin usa nelle varie sessioni.

<div id="create-a-knowledge-note">
  ### Crea una nota di 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">
  ### Elenca le note di 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">
  ### Aggiorna una nota di 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">
  ### Eliminare una nota di 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">
  ### Creare un 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">
  ### Esempio completo in 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"
}

# Crea nota 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']}")

# Elenca tutte le note
notes = requests.get(
    f"{BASE}/organizations/{ORG_ID}/knowledge/notes",
    headers={"Authorization": f"Bearer {API_KEY}"}
).json()["items"]
print(f"Total notes: {len(notes)}")

# Crea 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">
  ## Pianificazione delle sessioni automatizzate
</div>

Crea sessioni ricorrenti che vengono eseguite in base a una pianificazione.

<div id="create-a-schedule">
  ### Crea una pianificazione
</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"
  }'
```

Questo crea una pianificazione che viene eseguita ogni giorno feriale alle 9:00 ET.

<div id="list-schedules">
  ### Elencare le pianificazioni
</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">
  ### Aggiornare una pianificazione
</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">
  ### Eliminare una pianificazione
</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">
  ### Esempio completo in 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"
}

# Crea una pianificazione giornaliera di controllo dello stato
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']}")

# Elenca tutte le pianificazioni
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">
  ## Affida un'attività da qualsiasi ambiente
</div>

Poiché la Sessions API crea una sessione di Devin nel cloud a partire da una singola richiesta, qualsiasi tool, script o coding agent può "affidare" il lavoro a Devin, includendo nel prompt la repo corrente, il branch e le modifiche non ancora sottoposte a commit, così la sessione cloud riprende da dove avevi lasciato.

<div id="create-a-session-with-repo-context">
  ### Creare una sessione con il contesto del repo
</div>

```bash theme={null}
# Costruisce il corpo JSON con jq in modo che il diff grezzo — che contiene virgolette,
# backslash e newline — venga codificato come stringa JSON valida.
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)"}')"
```

La sessione cloud clona la repo, applica il contesto del prompt e viene eseguita nella propria VM con una shell, un browser e accesso completo alla repo. Monitora l'avanzamento [facendo polling dei messaggi](#step-4-poll-for-events) o nell'[app web di Devin](https://app.devin.ai).

<Warning>
  `git diff HEAD` può includere segreti non ancora sottoposti a commit — chiavi API, token o modifiche a `.env` — e il prompt viene caricato nella sessione cloud. Controlla il diff ed esegui il commit, lo stash o rimuovi le modifiche sensibili prima di affidare il lavoro.
</Warning>

<Tip>
  Non vuoi implementare tutto questo da solo? Il plugin open-source [Devin Handoff](https://github.com/club-cog/devin-handoff) racchiude esattamente questo flusso — rilevando automaticamente repo, branch e diff — così puoi affidare il lavoro da Devin CLI, Claude Code, Codex, Cursor o da un semplice script shell. Vedi [Affida il lavoro a Devin](/it/work-with-devin/devin-handoff).
</Tip>

***

<div id="error-handling">
  ## Gestione degli errori
</div>

Negli ambienti di produzione, tutti gli esempi sopra dovrebbero includere la gestione degli errori. Ecco uno schema riutilizzabile:

```python theme={null}
import requests

def api_request(method, url, headers, **kwargs):
    """Esegui una richiesta API con gestione standard degli errori."""
    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">
  ## Supporto
</div>

<Card title="Hai bisogno di aiuto?">
  Per domande sull'API o per segnalare problemi, scrivi a [support@cognition.ai](mailto:support@cognition.ai)
</Card>
