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

# よくあるフロー

> 一般的なAPIユースケース向けのエンドツーエンドのワークフローガイド

このページでは、Devin APIを利用した一般的なエンドツーエンドのワークフローを紹介します。各フローには、コード使用例とあわせて、APIコールの一連の流れがすべて含まれています。各エンドポイントの詳細については、該当するAPIリファレンスページを参照してください。

<div id="setup">
  ## セットアップ
</div>

いずれの使用例を実行する前にも、これらの環境変数を設定してください。

```bash theme={null}
# 必須: サービスユーザーのAPIキー（cog_ で始まります）
export DEVIN_API_KEY="cog_your_key_here"

# 必須: 組織ID（Settings > Devin API の上部に表示されます）
export DEVIN_ORG_ID="your_org_id"
```

***

<div id="getting-started-api-key-to-first-session">
  ## はじめに: APIキーから最初のセッションまで
</div>

最も一般的なワークフローです。認証を行い、アカウント情報を確認して、最初のセッションを作成します。

<div id="step-1-verify-your-credentials">
  ### ステップ 1: 認証情報を確認する
</div>

<Note>組織スコープのサービスユーザーはステップ 3 に進んでください。org ID は Settings ページですでに確認済みです。</Note>

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

レスポンス:

```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">
  ### ステップ 2: 自分の組織を一覧表示する
</div>

**Enterprise のサービスユーザー**は、すべての組織を一覧表示できます。

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

**組織スコープのサービスユーザー**は、すでに自身の org ID を把握しています (サービスユーザーがプロビジョニングされた **Settings > Devin API** ページの上部に表示されています) 。

<div id="step-3-create-a-session">
  ### ステップ 3: セッションを作成する
</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"}'
```

レスポンス:

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

<div id="step-4-poll-for-events">
  ### ステップ 4: イベントをポーリングする
</div>

メッセージをポーリングして、セッションを監視します:

```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">
  ### 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. 認証情報を確認する
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. セッションを作成する
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. 完了するまでポーリングする
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">
  ## セッションの添付ファイルをダウンロード
</div>

セッションで生成されたファイル (ログ、スクリーンショット、生成コードなど) を取得します。

<div id="step-1-get-the-session">
  ### ステップ 1: セッションを取得する
</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">
  ### ステップ 2: 添付ファイルを一覧表示する
</div>

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

レスポンス:

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

<div id="step-3-download">
  ### ステップ 3: ダウンロード
</div>

添付ファイルのレスポンスに含まれる `url` を使用して、ファイルを直接ダウンロードします。

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

# 添付ファイルを一覧表示する
attachments = requests.get(
    f"{BASE}/organizations/{ORG_ID}/sessions/{SESSION_ID}/attachments",
    headers=HEADERS
).json()["items"]

# 各添付ファイルをダウンロードする
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">
  ## Knowledge と playbook の管理
</div>

Devin がセッションをまたいで利用する前提情報と指示を管理します。

<div id="create-a-knowledge-note">
  ### 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">
  ### 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">
  ### 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">
  ### 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">
  ### プレイブック を作成する
</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 '{
    "title": "PR Review",
    "body": "Review the PR for bugs, security issues, and style violations. Leave inline comments."
  }'
```

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

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

# すべてのノートを一覧表示する
notes = requests.get(
    f"{BASE}/organizations/{ORG_ID}/knowledge/notes",
    headers={"Authorization": f"Bearer {API_KEY}"}
).json()["items"]
print(f"Total notes: {len(notes)}")

# プレイブックを作成する
playbook = requests.post(
    f"{BASE}/organizations/{ORG_ID}/playbooks",
    headers=HEADERS,
    json={
        "title": "PR Review",
        "body": "Review the PR for bugs, security issues, and style violations."
    }
).json()
print(f"Created playbook: {playbook['playbook_id']}")
```

***

<div id="scheduling-automated-sessions">
  ## セッションの自動実行をスケジュールする
</div>

`schedule:recurring` トリガーを持つ[自動化](/ja/api-reference/v3/automations/post-organizations-automations)を作成すると、セッションを定期的に実行できます。このトリガーは `rrule` 条件を 1 つ受け取ります。これは UTC で評価される iCalendar の `RRULE` です (例: 夏時間中の東部時間午前 9 時に平日実行する場合は `FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR;BYHOUR=13;BYMINUTE=0`) 。`ManageOrgAutomations` 権限が必要です。

<Warning>
  従来の `/schedules` エンドポイントは非推奨です。2026 年 9 月 24 日以降、自動化へ移行済みの組織では `POST /v3/organizations/{org_id}/schedules` は `403` を返します。詳細は [API リリースノート](/ja/api-reference/release-notes)を参照してください。
</Warning>

<div id="create-a-scheduled-automation">
  ### スケジュール実行の自動化を作成する
</div>

```bash theme={null}
curl -X POST "https://api.devin.ai/v3/organizations/$DEVIN_ORG_ID/automations" \
  -H "Authorization: Bearer $DEVIN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Weekday test run",
    "run_as": {"type": "organization"},
    "triggers": [{
      "event_type": "schedule:recurring",
      "conditions": {"any": [{"all": [{
        "field": "rrule",
        "operator": "recurrence",
        "value": "FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR;BYHOUR=13;BYMINUTE=0"
      }]}]}
    }],
    "actions": [{
      "type": "start_session",
      "prompt": "Run the test suite and report any failures"
    }]
  }'
```

1回限りの実行の場合は、`DTSTART` と `COUNT=1` を組み合わせて利用します。例えば `DTSTART:20260915T170000Z\nRRULE:FREQ=DAILY;COUNT=1` のように指定します。この自動化は1回だけ発生し、その後は自動的に無効化されます。

<div id="list-update-and-delete">
  ### 一覧取得、更新、削除
</div>

```bash theme={null}
# 自動化の一覧を取得
curl "https://api.devin.ai/v3/organizations/$DEVIN_ORG_ID/automations" \
  -H "Authorization: Bearer $DEVIN_API_KEY"

# 自動化を無効化する
curl -X PATCH "https://api.devin.ai/v3/organizations/$DEVIN_ORG_ID/automations/$AUTOMATION_ID" \
  -H "Authorization: Bearer $DEVIN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"enabled": false}'

# 自動化を削除する
curl -X DELETE "https://api.devin.ai/v3/organizations/$DEVIN_ORG_ID/automations/$AUTOMATION_ID" \
  -H "Authorization: Bearer $DEVIN_API_KEY"
```

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

# 毎日のヘルスチェック自動化を作成する（毎日09:00 UTC）
automation = requests.post(
    f"{BASE}/organizations/{ORG_ID}/automations",
    headers=HEADERS,
    json={
        "name": "Daily health check",
        "run_as": {"type": "organization"},
        "triggers": [{
            "event_type": "schedule:recurring",
            "conditions": {"any": [{"all": [{
                "field": "rrule",
                "operator": "recurrence",
                "value": "FREQ=DAILY;BYHOUR=9;BYMINUTE=0"
            }]}]}
        }],
        "actions": [{
            "type": "start_session",
            "prompt": "Run the test suite and report any failures"
        }]
    }
).json()
print(f"Created automation: {automation['automation_id']}")

# すべての自動化を一覧表示する（エンドポイントは1ページあたり最大100件を返す）
automations = []
after = None
while True:
    page = requests.get(
        f"{BASE}/organizations/{ORG_ID}/automations",
        headers={"Authorization": f"Bearer {API_KEY}"},
        params={"after": after},
    ).json()
    automations.extend(page["items"])
    if not page["has_next_page"]:
        break
    after = page["end_cursor"]

for a in automations:
    status = "enabled" if a.get("enabled") else "disabled"
    print(f"  {a['automation_id']}: {a['name']} ({status})")
```

***

<div id="hand-off-a-task-from-anywhere">
  ## どこからでもタスクを引き継げる
</div>

Sessions API は単一のリクエストで cloud Devin セッションを作成できるため、どのツール、スクリプト、コーディングエージェントからでも作業を Devin に「引き継ぐ」ことができます。現在の repo、ブランチ、未コミットの変更をプロンプトにまとめて含めることで、cloud Devin セッションは中断したところから作業を再開できます。

<div id="create-a-session-with-repo-context">
  ### repoの前提情報付きでセッションを作成する
</div>

```bash theme={null}
# jq を使って JSON ボディを構築し、生の diff（引用符、バックスラッシュ、改行を含む）を有効な JSON 文字列にエスケープする。
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)"}')"
```

クラウドセッションはリポジトリをクローンし、プロンプトの前提情報を適用したうえで、シェル、ブラウザ、リポジトリへのフルアクセスを備えた専用のVM上で実行されます。[メッセージをポーリングする](#step-4-poll-for-events)か、[Devin web app](https://app.devin.ai) で追跡できます。

<Warning>
  `git diff HEAD` には、未コミットのシークレット (APIキー、トークン、`.env` の編集など) が含まれる場合があり、プロンプトはクラウドセッションにアップロードされます。引き継ぐ前に diff を確認し、機密性の高い変更はコミット、stash、または削除してください。
</Warning>

<Tip>
  これを自分で実装したくないですか？オープンソースの [Devin Handoff](https://github.com/club-cog/devin-handoff) プラグインは、まさにこのフローをラップしており、リポジトリ、ブランチ、diff を自動検出するため、Devin CLI、Claude Code、Codex、Cursor、または通常のシェルスクリプトから引き継げます。詳しくは [Devin に引き継ぐ](/ja/work-with-devin/devin-handoff) を参照してください。
</Tip>

***

<div id="error-handling">
  ## エラー処理
</div>

本番環境では、上記のすべての使用例にエラー処理を含める必要があります。以下に、再利用可能なパターンを示します。

```python theme={null}
import requests

def api_request(method, url, headers, **kwargs):
    """標準的なエラー処理を含むAPIリクエストを実行する。"""
    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("APIキーが無効または期限切れです")
        elif status == 403:
            raise Exception("サービスユーザーに必要なpermissionがありません")
        elif status == 404:
            raise Exception("リソースが見つかりません")
        elif status == 429:
            raise Exception("レート制限を超過しました — しばらく待ってから再試行してください")
        else:
            raise Exception(f"APIエラー {status}: {e.response.text}")
```

<div id="support">
  ## サポート
</div>

<Card title="お困りですか？">
  API に関するご質問や問題の報告は、[support@cognition.ai](mailto:support@cognition.ai) までメールでお問い合わせください
</Card>
