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

# Organization Tree

> Retrieve the complete organizational hierarchy as a tree structure

# Organization Tree

Retrieve the complete hierarchical structure of your organization, starting from the top-level parent (holding) down to all subsidiaries and child organizations.

The tree always starts from the root organization, regardless of which organization is specified in the `x-organization-id` header. This means you can use the API key from any organization in the tree and always get the full hierarchy.

## Request

### Headers

<ParamField header="x-api-key" type="string" required>
  Your API key for authentication

  **Example:** `sk_live_1234567890abcdef`
</ParamField>

<ParamField header="x-organization-id" type="string" required>
  Your organization UUID. Can be any organization in the tree - the response always starts from the root.

  **Example:** `dce3ff33-9fcc-4521-910f-7972d81fb70c`
</ParamField>

## Response

<ResponseField name="id" type="string">
  Organization UUID (root/holding organization)
</ResponseField>

<ResponseField name="name" type="string">
  Organization name
</ResponseField>

<ResponseField name="children" type="array[object]">
  Child organizations (recursive structure - each child has the same shape)

  <Expandable title="Organization Node">
    <ResponseField name="id" type="string">
      Organization UUID
    </ResponseField>

    <ResponseField name="name" type="string">
      Organization name
    </ResponseField>

    <ResponseField name="children" type="array[object]">
      Nested child organizations (same recursive structure)
    </ResponseField>
  </Expandable>
</ResponseField>

## Example

<CodeGroup>
  ```bash cURL theme={"theme":{"light":"github-light","dark":"github-dark"}}
  curl -X GET "https://api.dcycle.io/v2/organizations/tree" \
    -H "x-api-key: ${DCYCLE_API_KEY}" \
    -H "x-organization-id: ${DCYCLE_ORG_ID}"
  ```

  ```python Python theme={"theme":{"light":"github-light","dark":"github-dark"}}
  import requests
  import os

  api_key = os.getenv("DCYCLE_API_KEY")
  org_id = os.getenv("DCYCLE_ORG_ID")

  headers = {
      "x-api-key": api_key,
      "x-organization-id": org_id
  }

  response = requests.get(
      "https://api.dcycle.io/v2/organizations/tree",
      headers=headers
  )

  tree = response.json()
  print(f"Root: {tree['name']} ({tree['id']})")
  for child in tree["children"]:
      print(f"  - {child['name']} ({child['id']})")
      for grandchild in child.get("children", []):
          print(f"      - {grandchild['name']}")
  ```

  ```javascript JavaScript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  const axios = require('axios');

  const apiKey = process.env.DCYCLE_API_KEY;
  const orgId = process.env.DCYCLE_ORG_ID;

  const headers = {
    'x-api-key': apiKey,
    'x-organization-id': orgId
  };

  axios.get(
    'https://api.dcycle.io/v2/organizations/tree',
    { headers }
  )
  .then(response => {
    const tree = response.data;
    console.log(`Root: ${tree.name} (${tree.id})`);
    tree.children.forEach(child => {
      console.log(`  - ${child.name} (${child.id})`);
      child.children.forEach(grandchild => {
        console.log(`      - ${grandchild.name}`);
      });
    });
  })
  .catch(error => console.error(error));
  ```
</CodeGroup>

### Successful Response

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "id": "dce3ff33-9fcc-4521-910f-7972d81fb70c",
  "name": "Acme Holdings",
  "children": [
    {
      "id": "d9e08b1a-bd28-4950-a730-3c300a2ff91e",
      "name": "Acme Construction",
      "children": [
        {
          "id": "22dcadf6-2da8-4077-a555-7da22c3c5eae",
          "name": "Project Alpha - Office Building",
          "children": []
        },
        {
          "id": "dbcd29bd-b55d-4007-a16e-25924597580e",
          "name": "Project Beta - Highway Extension",
          "children": []
        }
      ]
    },
    {
      "id": "e3d4c82b-1a8c-429c-aaea-1f82b6bd7fe4",
      "name": "Acme Restoration",
      "children": [
        {
          "id": "d3cc0278-f383-4912-8fb6-a6b127ed30e3",
          "name": "Historic Building Renovation",
          "children": []
        }
      ]
    },
    {
      "id": "132c18ba-6e5c-4cbc-a5e1-fb71b75e9012",
      "name": "Acme Industrial",
      "children": []
    },
    {
      "id": "eaa14ae8-73c2-4a42-9731-296fca49b7c4",
      "name": "Acme Integrated Services",
      "children": []
    }
  ]
}
```

## Common Errors

### 401 Unauthorized

**Cause:** Missing or invalid API key

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "detail": "Invalid API key",
  "code": "INVALID_API_KEY"
}
```

**Solution:** Verify your API key is valid and active. Get a new one from [Settings > API](https://app.dcycle.io/settings/api).

### 404 Not Found

**Cause:** Organization not found

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "code": "ORGANIZATION_NOT_FOUND",
  "detail": "Organization with id=UUID('...') not found"
}
```

**Solution:** Verify that the `x-organization-id` header contains a valid organization UUID.

## Use Cases

### List All Subsidiaries (Flat)

Flatten the tree to get a simple list of all organizations:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def flatten_tree(node, depth=0):
    """Recursively flatten the organization tree."""
    orgs = [{"id": node["id"], "name": node["name"], "depth": depth}]
    for child in node.get("children", []):
        orgs.extend(flatten_tree(child, depth + 1))
    return orgs

response = requests.get(
    "https://api.dcycle.io/v2/organizations/tree",
    headers=headers
)

all_orgs = flatten_tree(response.json())
for org in all_orgs:
    indent = "  " * org["depth"]
    print(f"{indent}{org['name']} ({org['id']})")
```

### Count Organizations by Level

Analyze the depth of the organizational structure:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from collections import Counter

def count_by_level(node, level=0, counter=None):
    """Count organizations at each level of the tree."""
    if counter is None:
        counter = Counter()
    counter[level] += 1
    for child in node.get("children", []):
        count_by_level(child, level + 1, counter)
    return counter

tree = response.json()
levels = count_by_level(tree)
for level, count in sorted(levels.items()):
    label = "Holding" if level == 0 else f"Level {level}"
    print(f"{label}: {count} organizations")
```

### Export Organization IDs

Extract all organization IDs for use with other API endpoints:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def get_all_org_ids(node):
    """Extract all organization IDs from the tree."""
    ids = [node["id"]]
    for child in node.get("children", []):
        ids.extend(get_all_org_ids(child))
    return ids

tree = response.json()
org_ids = get_all_org_ids(tree)
print(f"Total organizations: {len(org_ids)}")

# Use IDs with other endpoints (e.g., get vehicles for each org)
for org_id in org_ids:
    vehicles = requests.get(
        "https://api.dcycle.io/v2/vehicles",
        headers={**headers, "x-organization-id": org_id}
    ).json()
    print(f"Org {org_id}: {vehicles['total']} vehicles")
```

## Related Endpoints

<CardGroup cols={2}>
  <Card title="Organizations Overview" icon="building" href="/api-reference/organizations/overview">
    Learn about the Organizations API
  </Card>

  <Card title="Authentication" icon="key" href="/docs/authentication">
    Set up API authentication
  </Card>
</CardGroup>
