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

# List Workspaces

> Retrieve all workspaces in your organization with optional pagination support for efficient data retrieval.

Retrieve a list of all workspaces in your organization. This endpoint supports pagination to efficiently handle large numbers of workspaces.

> [!NOTE]
>
> Use pagination when you have many workspaces to improve response times and reduce data transfer. The default page limit is 10 workspaces per page.

## Authentication

This endpoint requires a service token in the Authorization header. Service tokens differ from data app API keys and provide organization-level permissions.

To access your service token:

1. In **Settings** page, navigate to the **Service Tokens** section.
2. Click the **"Generate Token"** button to create a new service token if you don't have one already.

Use this token as the Bearer value in your Authorization header.

## Headers

**Authorization** `string` *required*

Bearer token for API authentication. Use your service token.

```
Authorization: Bearer dbn_live_abc123...
```

## Query Parameters

**isPagination** `string` (default: false)

Enable pagination to retrieve workspaces in batches. Pass `"true"` to enable pagination.

**Note:** Query parameters are passed as strings. Use `"true"` or `"false"` (not boolean values).

* `"true"`: Enable pagination with page-based retrieval (10 items per page)
* `"false"` (default): Return all workspaces in a single response

**When to use pagination**

* Use pagination when you have more than 50 workspaces
* Improves response times for large datasets
* Reduces memory usage in your application
* Each page returns up to 10 workspaces

**pageNumber** `string` (default: 1)

The page number to retrieve when pagination is enabled. Must be a numeric string (e.g., `"1"`, `"2"`, `"3"`).

**Note:** This parameter is only used when `isPagination` is set to `"true"`.

* Pages start at 1 (first page)
* Each page contains up to 10 workspaces
* Returns empty array if page number exceeds available pages

## Response

**data** `array`

Array of workspace objects. Returns empty array if no workspaces exist or page number exceeds available pages.

**workspace object properties**

**name** `string`

The name of the workspace.

**error** `null | object`

Error object if the request failed, otherwise `null` for successful requests.

**error properties**

**code** `string`

Error code identifying the type of error.

**message** `string`

Human-readable error message describing what went wrong.

## Examples

```bash cURL - All Workspaces theme={"dark"}
curl --request GET \
  --url 'https://api.usedatabrain.com/api/v2/workspace' \
  --header 'Authorization: Bearer dbn_live_abc123...'
```

```bash cURL - With Pagination theme={"dark"}
curl --request GET \
  --url 'https://api.usedatabrain.com/api/v2/workspace?isPagination=true&pageNumber=1' \
  --header 'Authorization: Bearer dbn_live_abc123...'
```

```bash cURL - Second Page theme={"dark"}
curl --request GET \
  --url 'https://api.usedatabrain.com/api/v2/workspace?isPagination=true&pageNumber=2' \
  --header 'Authorization: Bearer dbn_live_abc123...'
```

```javascript Node.js - All Workspaces icon="fa-brands fa-node-js" theme={"dark"}
const response = await fetch('https://api.usedatabrain.com/api/v2/workspace', {
  method: 'GET',
  headers: {
    'Authorization': 'Bearer dbn_live_abc123...'
  }
});

const result = await response.json();
console.log(result.data); // Array of all workspaces
```

```javascript Node.js - With Pagination icon="fa-brands fa-node-js" theme={"dark"}
async function fetchAllWorkspaces() {
  let allWorkspaces = [];
  let pageNumber = 1;
  let hasMorePages = true;

  while (hasMorePages) {
    const response = await fetch(
      `https://api.usedatabrain.com/api/v2/workspace?isPagination=true&pageNumber=${pageNumber}`,
      {
        headers: {
          'Authorization': 'Bearer dbn_live_abc123...'
        }
      }
    );

    const result = await response.json();
    
    if (result.data && result.data.length > 0) {
      allWorkspaces = allWorkspaces.concat(result.data);
      pageNumber++;
    } else {
      hasMorePages = false;
    }
  }

  return allWorkspaces;
}

const workspaces = await fetchAllWorkspaces();
console.log(`Total workspaces: ${workspaces.length}`);
```

```python Python - All Workspaces icon="fa-brands fa-python" theme={"dark"}
import requests

response = requests.get(
    'https://api.usedatabrain.com/api/v2/workspace',
    headers={
        'Authorization': 'Bearer dbn_live_abc123...'
    }
)

result = response.json()
workspaces = result['data']
print(f"Total workspaces: {len(workspaces)}")
```

```python Python - With Pagination icon="fa-brands fa-python" theme={"dark"}
import requests

def fetch_all_workspaces(api_key):
    all_workspaces = []
    page_number = 1
    has_more_pages = True

    while has_more_pages:
        response = requests.get(
            'https://api.usedatabrain.com/api/v2/workspace',
            params={
                'isPagination': 'true',
                'pageNumber': page_number
            },
            headers={
                'Authorization': f'Bearer {api_key}'
            }
        )

        result = response.json()
        
        if result['data'] and len(result['data']) > 0:
            all_workspaces.extend(result['data'])
            page_number += 1
        else:
            has_more_pages = False

    return all_workspaces

workspaces = fetch_all_workspaces('dbn_live_abc123...')
print(f"Total workspaces: {len(workspaces)}")
```

```ruby Ruby icon="fa-solid fa-gem" theme={"dark"}
require 'net/http'
require 'json'

uri = URI('https://api.usedatabrain.com/api/v2/workspace')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true

request = Net::HTTP::Get.new(uri)
request['Authorization'] = 'Bearer dbn_live_abc123...'

response = http.request(request)
result = JSON.parse(response.body)

puts "Total workspaces: #{result['data'].length}"
result['data'].each do |workspace|
  puts "- #{workspace['name']}"
end
```

```java Java icon="fa-brands fa-java" theme={"dark"}
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URI;

public class ListWorkspaces {
    public static void main(String[] args) throws Exception {
        HttpClient client = HttpClient.newHttpClient();
        
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.usedatabrain.com/api/v2/workspace"))
            .header("Authorization", "Bearer dbn_live_abc123...")
            .GET()
            .build();
            
        HttpResponse<String> response = client.send(request, 
            HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }
}
```

```go Go - With Pagination icon="fa-brands fa-golang" theme={"dark"}
package main

import (
    "encoding/json"
    "fmt"
    "io"
    "net/http"
)

type WorkspaceResponse struct {
    Data  []Workspace `json:"data"`
    Error interface{}  `json:"error"`
}

type Workspace struct {
    Name string `json:"name"`
}

func fetchAllWorkspaces(apiKey string) ([]Workspace, error) {
    var allWorkspaces []Workspace
    pageNumber := 1

    for {
        url := fmt.Sprintf(
            "https://api.usedatabrain.com/api/v2/workspace?isPagination=true&pageNumber=%d",
            pageNumber,
        )

        req, _ := http.NewRequest("GET", url, nil)
        req.Header.Set("Authorization", "Bearer "+apiKey)

        client := &http.Client{}
        resp, err := client.Do(req)
        if err != nil {
            return nil, err
        }

        body, _ := io.ReadAll(resp.Body)
        resp.Body.Close()

        var result WorkspaceResponse
        json.Unmarshal(body, &result)

        if len(result.Data) == 0 {
            break
        }

        allWorkspaces = append(allWorkspaces, result.Data...)
        pageNumber++
    }

    return allWorkspaces, nil
}

func main() {
    workspaces, _ := fetchAllWorkspaces("dbn_live_abc123...")
    fmt.Printf("Total workspaces: %d\n", len(workspaces))
}
```

```php PHP icon="fa-brands fa-php" theme={"dark"}
<?php
$url = 'https://api.usedatabrain.com/api/v2/workspace';

$options = [
    'http' => [
        'header' => 'Authorization: Bearer dbn_live_abc123...',
        'method' => 'GET'
    ]
];

$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
$result = json_decode($response, true);

echo "Total workspaces: " . count($result['data']) . "\n";
foreach ($result['data'] as $workspace) {
    echo "- " . $workspace['name'] . "\n";
}
?>
```

```json 200 - Success (Multiple Workspaces) theme={"dark"}
{
  "data": [
    {
      "name": "Sales Analytics"
    },
    {
      "name": "Customer Insights"
    },
    {
      "name": "Marketing Dashboard"
    }
  ],
  "error": null
}
```

```json 200 - Success (Empty) theme={"dark"}
{
  "data": [],
  "error": null
}
```

```json 200 - Success (First Page) theme={"dark"}
{
  "data": [
    {
      "name": "Workspace 1"
    },
    {
      "name": "Workspace 2"
    },
    {
      "name": "Workspace 3"
    },
    {
      "name": "Workspace 4"
    },
    {
      "name": "Workspace 5"
    },
    {
      "name": "Workspace 6"
    },
    {
      "name": "Workspace 7"
    },
    {
      "name": "Workspace 8"
    },
    {
      "name": "Workspace 9"
    },
    {
      "name": "Workspace 10"
    }
  ],
  "error": null
}
```

```json 401 - Unauthorized theme={"dark"}
{
  "error": {
    "code": "INVALID_DATA_APP_API_KEY",
    "message": "invalid or expired API KEY, data app not found"
  }
}
```

```json 500 - Server Error theme={"dark"}
{
  "error": {
    "code": "INTERNAL_SERVER_ERROR",
    "message": "Internal Server Error"
  }
}
```

## HTTP Status Code Summary

| Status Code | Description |
| - | - |
| `200` | **OK** - Workspaces retrieved successfully |
| `401` | **Unauthorized** - Invalid or missing API key |
| `500` | **Internal Server Error** - Server error occurred |

## Possible Errors

| Error Code | HTTP Status | Description | Solution |
| - | - | - | - |
| `INVALID_DATA_APP_API_KEY` | 401 | Invalid API key | Verify your API key is correct and has proper permissions |
| `INTERNAL_SERVER_ERROR` | 500 | Server error | Contact support if error persists |

## Pagination Details

> [accordion] How pagination works
>
> When `isPagination` is set to `true`:
>
> * Each page returns up to **10 workspaces**
> * Pages are 1-indexed (first page is `pageNumber=1`)
> * An empty array is returned when you've reached the end
> * Use this to implement "load more" or infinite scroll patterns
>
> **Example flow:**
>
> 1. Request page 1 → Returns 10 workspaces
> 2. Request page 2 → Returns 10 more workspaces
> 3. Request page 3 → Returns 5 workspaces
> 4. Request page 4 → Returns empty array (no more data)

> [accordion] When to use pagination
>
> **Use pagination when:**
>
> * You have more than 50 workspaces
> * Building user interfaces with "load more" functionality
> * Implementing infinite scroll
> * Optimizing for mobile or slow connections
>
> **Skip pagination when:**
>
> * You have fewer than 20 workspaces
> * You need all workspace data for processing
> * Implementing search or filter functionality client-side

> [accordion] Best practices
>
> * **Cache results**: Store workspace lists client-side to reduce API calls
> * **Handle empty pages**: Check for empty arrays to detect the last page
> * **Show loading states**: Display loading indicators between page requests
> * **Error handling**: Implement retry logic for failed requests
> * **Rate limiting**: Respect API rate limits when fetching multiple pages

## Quick Start: Implement Pagination

**1. Implement pagination**

For large workspace lists, implement pagination to efficiently fetch results page by page:

```javascript theme={"dark"}
async function loadWorkspacePage(pageNumber) {
  const response = await fetch(
    `https://api.usedatabrain.com/api/v2/workspace?isPagination=true&pageNumber=${pageNumber}`,
    {
      headers: { 'Authorization': 'Bearer dbn_live_abc123...' }
    }
  );

return await response.json();
}

// Load first page
const page1 = await loadWorkspacePage(1);
```

> [!TIP]
>
> Implement a "Load More" button that increments the page number on each click to fetch additional workspaces.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.