> ## 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 > Service Users で確認できます）
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 > Service Users ページに記載されています) 。

<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"
```

### Pythonの完全な例

```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">
  ### 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">
  ### 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."
  }'
```

### Pythonの完全な例

```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={
        "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">
  ## 自動セッションのスケジュール設定
</div>

スケジュールに沿って実行される定期セッションを作成します。

<div id="create-a-schedule">
  ### スケジュールを作成する
</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"
  }'
```

これにより、米国東部時間の平日午前9時に実行されるスケジュールが作成されます。

<div id="list-schedules">
  ### スケジュールを一覧表示する
</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">
  ### スケジュールを更新する
</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">
  ### スケジュールを削除する
</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"
```

### Pythonの完全な例

```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"
}

# 毎日のヘルスチェックスケジュールを作成する
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']}")

# すべてのスケジュールを一覧表示する
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">
  ## どこからでもタスクを引き継げる
</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>
