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

# Create Workspace

> Create a new workspace with datasource, datamart, multi-datasource, or multi-datamart configuration to organize your analytics environment.

Create workspaces to organize your analytics environment by connecting datasources or datamarts. Workspaces serve as containers for dashboards and metrics, providing structured access to your data.

<Note>
  Choose a `connectionType` that matches how this workspace will use data. For `DATASOURCE` or `DATAMART`, the corresponding `datasourceName` or `datamartName` must already exist in your organization. For `MULTI_DATASOURCE` or `MULTI_DATAMART`, those name fields are not required in the request body (see `connectionType` below).
</Note>

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

<ParamField header="Authorization" type="string" required>
  Bearer token for API authentication. Use your service token.

  ```
  Authorization: Bearer dbn_live_abc123...
  ```
</ParamField>

<ParamField header="Content-Type" type="string" required>
  Must be set to `application/json` for all requests.

  ```
  Content-Type: application/json
  ```
</ParamField>

## Request Body

<ParamField body="name" type="string" required>
  Name of the workspace to create. Must be unique within your organization.

  <Expandable title="Naming guidelines">
    * Use descriptive names (e.g., "sales-analytics", "customer-insights")
    * Alphanumeric characters and spaces are supported
    * Must be unique within your organization
    * Cannot be changed after creation (use update API to modify connection)
  </Expandable>
</ParamField>

<ParamField body="connectionType" type="string" required>
  Type of connection for the workspace. Must be one of: `DATASOURCE`, `DATAMART`, `MULTI_DATASOURCE`, or `MULTI_DATAMART`.

  <Expandable title="Connection type details">
    * **DATASOURCE**: Connect directly to a single datasource
    * **DATAMART**: Connect to a pre-configured datamart
    * **MULTI\_DATASOURCE**: Allow connections to multiple datasources within this workspace (`datasourceName` is not required for this type)
    * **MULTI\_DATAMART**: Allow multiple datamarts in this workspace (`datamartName` is not required for this type; it is required only when `connectionType` is `DATAMART`)
  </Expandable>
</ParamField>

<ParamField body="datasourceName" type="string">
  Name of the datasource to connect to this workspace.

  **Required when** `connectionType` is `DATASOURCE`.

  <Expandable title="Finding datasource names">
    * Check your datasources list in the DataBrain dashboard
    * Use the exact name as stored in datasource credentials
    * Names are case-sensitive
  </Expandable>
</ParamField>

<ParamField body="datamartName" type="string">
  Name of the datamart to connect to this workspace.

  **Required when** `connectionType` is `DATAMART`.

  <Expandable title="Finding datamart names">
    * List available datamarts using the [List Datamarts API](/developer-docs/helpers/api-reference/list-datamarts)
    * Use the exact name as it appears in your datamart configuration
    * Names are case-sensitive
  </Expandable>
</ParamField>

<ParamField body="llmName" type="string">
  Optional primary LLM name for workspace-level AI features. Must match an existing LLM configured in your organization.
</ParamField>

<ParamField body="aiCopilotLlms" type="array">
  Optional list of LLM names available for AI Copilot in this workspace. Every value must match an existing organization LLM name.
</ParamField>

<ParamField body="isEnableMetricSuggestions" type="boolean">
  Optional flag to enable AI-powered metric suggestions in this workspace. Defaults to `false` when omitted.
</ParamField>

<ParamField body="isEnableMetricSummary" type="boolean">
  Optional flag to enable AI-generated metric summaries in this workspace. Defaults to `false` when omitted.
</ParamField>

<ParamField body="summaryType" type="string">
  Summary mode used when metric summaries are enabled. Must be one of:
  `technicalAndInsightSummary`, `forecastAndTrendAnalysis`, `comparativeAndAnomalyDetection`, `custom`.

  **Required when** `isEnableMetricSummary` is `true`.
</ParamField>

<ParamField body="customSummaryPrompt" type="string">
  Custom summary instruction prompt for AI-generated summaries.

  **Required when** `summaryType` is `custom`.
</ParamField>

<ParamField body="themeName" type="string">
  Optional workspace theme name. Must match an existing theme configured in your organization.
</ParamField>

## Response

<ResponseField name="data" type="object">
  Contains the created workspace information on success.

  <Expandable title="data properties">
    <ResponseField name="name" type="string">
      The name of the successfully created workspace.
    </ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="error" type="null | object">
  Error object if the request failed, otherwise `null` for successful requests.

  <Expandable title="error properties">
    <ResponseField name="code" type="string">
      Error code identifying the type of error.
    </ResponseField>

    <ResponseField name="message" type="string">
      Human-readable error message describing what went wrong.
    </ResponseField>
  </Expandable>
</ResponseField>

## Examples

<Panel>
  <RequestExample>
    ```bash cURL - Datasource Connection theme={"dark"}
    curl --request POST \
      --url https://api.usedatabrain.com/api/v2/workspace \
      --header 'Authorization: Bearer dbn_live_abc123...' \
      --header 'Content-Type: application/json' \
      --data '{
        "name": "Sales Analytics",
        "connectionType": "DATASOURCE",
        "datasourceName": "postgres-main"
      }'
    ```

    ```bash cURL - Datamart Connection theme={"dark"}
    curl --request POST \
      --url https://api.usedatabrain.com/api/v2/workspace \
      --header 'Authorization: Bearer dbn_live_abc123...' \
      --header 'Content-Type: application/json' \
      --data '{
        "name": "Customer Insights",
        "connectionType": "DATAMART",
        "datamartName": "customer-data-mart"
      }'
    ```

    ```bash cURL - Multi-Datasource theme={"dark"}
    curl --request POST \
      --url https://api.usedatabrain.com/api/v2/workspace \
      --header 'Authorization: Bearer dbn_live_abc123...' \
      --header 'Content-Type: application/json' \
      --data '{
        "name": "Cross-Platform Analytics",
        "connectionType": "MULTI_DATASOURCE"
      }'
    ```

    ```bash cURL - Multi-Datamart theme={"dark"}
    curl --request POST \
      --url https://api.usedatabrain.com/api/v2/workspace \
      --header 'Authorization: Bearer dbn_live_abc123...' \
      --header 'Content-Type: application/json' \
      --data '{
        "name": "Multi-Datamart Analytics",
        "connectionType": "MULTI_DATAMART"
      }'
    ```

    ```bash cURL - Datamart with AI + Theme Settings theme={"dark"}
    curl --request POST \
      --url https://api.usedatabrain.com/api/v2/workspace \
      --header 'Authorization: Bearer dbn_live_abc123...' \
      --header 'Content-Type: application/json' \
      --data '{
        "name": "Executive AI Workspace",
        "connectionType": "DATAMART",
        "datamartName": "finance-datamart",
        "llmName": "gpt-4o",
        "aiCopilotLlms": ["gpt-4o", "gpt-4.1-mini"],
        "isEnableMetricSuggestions": true,
        "isEnableMetricSummary": true,
        "summaryType": "custom",
        "customSummaryPrompt": "Summarize KPIs with variance drivers and weekly action items.",
        "themeName": "Executive Theme"
      }'
    ```

    ```javascript Node.js icon="fa-brands fa-node-js" theme={"dark"}
    const response = await fetch('https://api.usedatabrain.com/api/v2/workspace', {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer dbn_live_abc123...',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        name: 'Sales Analytics',
        connectionType: 'DATASOURCE',
        datasourceName: 'postgres-main'
      })
    });

    const result = await response.json();
    console.log(result);
    ```

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

    response = requests.post(
        'https://api.usedatabrain.com/api/v2/workspace',
        headers={
            'Authorization': 'Bearer dbn_live_abc123...',
            'Content-Type': 'application/json'
        },
        json={
            'name': 'Sales Analytics',
            'connectionType': 'DATASOURCE',
            'datasourceName': 'postgres-main'
        }
    )

    result = response.json()
    print(result)
    ```

    ```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::Post.new(uri)
    request['Authorization'] = 'Bearer dbn_live_abc123...'
    request['Content-Type'] = 'application/json'
    request.body = {
      name: 'Sales Analytics',
      connectionType: 'DATASOURCE',
      datasourceName: 'postgres-main'
    }.to_json

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

    ```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 CreateWorkspace {
        public static void main(String[] args) throws Exception {
            HttpClient client = HttpClient.newHttpClient();
            
            String requestBody = """
                {
                    "name": "Sales Analytics",
                    "connectionType": "DATASOURCE",
                    "datasourceName": "postgres-main"
                }
                """;
            
            HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://api.usedatabrain.com/api/v2/workspace"))
                .header("Authorization", "Bearer dbn_live_abc123...")
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(requestBody))
                .build();
                
            HttpResponse<String> response = client.send(request, 
                HttpResponse.BodyHandlers.ofString());
            System.out.println(response.body());
        }
    }
    ```

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

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

    type WorkspaceRequest struct {
        Name            string `json:"name"`
        ConnectionType  string `json:"connectionType"`
        DatasourceName  string `json:"datasourceName,omitempty"`
        DatamartName    string `json:"datamartName,omitempty"`
    }

    func main() {
        reqData := WorkspaceRequest{
            Name:           "Sales Analytics",
            ConnectionType: "DATASOURCE",
            DatasourceName: "postgres-main",
        }
        
        jsonData, _ := json.Marshal(reqData)
        
        req, _ := http.NewRequest("POST", 
            "https://api.usedatabrain.com/api/v2/workspace", 
            bytes.NewBuffer(jsonData))
        req.Header.Set("Authorization", "Bearer dbn_live_abc123...")
        req.Header.Set("Content-Type", "application/json")
        
        client := &http.Client{}
        resp, _ := client.Do(req)
        defer resp.Body.Close()
        
        fmt.Println("Workspace created successfully")
    }
    ```

    ```php PHP icon="fa-brands fa-php" theme={"dark"}
    <?php
    $url = 'https://api.usedatabrain.com/api/v2/workspace';
    $data = [
        'name' => 'Sales Analytics',
        'connectionType' => 'DATASOURCE',
        'datasourceName' => 'postgres-main'
    ];

    $options = [
        'http' => [
            'header' => [
                'Authorization: Bearer dbn_live_abc123...',
                'Content-Type: application/json'
            ],
            'method' => 'POST',
            'content' => json_encode($data)
        ]
    ];

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

    echo "Workspace: " . $result['data']['name'];
    ?>
    ```
  </RequestExample>

  <ResponseExample>
    ```json 200 - Success theme={"dark"}
    {
      "data": {
        "name": "Sales Analytics"
      },
      "error": null
    }
    ```

    ```json 400 - Workspace Already Exists theme={"dark"}
    {
      "error": {
        "code": "WORKSPACE_NAME_ALREADY_EXISTS",
        "message": "Workspace with the same name already exists"
      }
    }
    ```

    ```json 400 - Invalid Datasource theme={"dark"}
    {
      "error": {
        "code": "INVALID_DATASOURCE_NAME",
        "message": "Invalid datasource name provided"
      }
    }
    ```

    ```json 400 - Invalid Datamart theme={"dark"}
    {
      "error": {
        "code": "INVALID_DATAMART_NAME",
        "message": "Invalid datamart name provided"
      }
    }
    ```

    ```json 400 - Validation Error theme={"dark"}
    {
      "error": {
        "code": "INVALID_REQUEST_BODY",
        "message": "\"connectionType\" is required"
      }
    }
    ```

    ```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"
      }
    }
    ```
  </ResponseExample>
</Panel>

## HTTP Status Code Summary

| Status Code | Description                                       |
| ----------- | ------------------------------------------------- |
| `200`       | **OK** - Workspace created successfully           |
| `400`       | **Bad Request** - Invalid request parameters      |
| `401`       | **Unauthorized** - Invalid or missing API key     |
| `500`       | **Internal Server Error** - Server error occurred |

## Possible Errors

| Error Code                      | HTTP Status | Description                   |
| ------------------------------- | ----------- | ----------------------------- |
| `INVALID_REQUEST_BODY`          | 400         | Missing or invalid parameters |
| `WORKSPACE_NAME_ALREADY_EXISTS` | 400         | Workspace name already exists |
| `INVALID_DATASOURCE_NAME`       | 400         | Datasource not found          |
| `INVALID_DATAMART_NAME`         | 400         | Datamart not found            |
| `INVALID_LLM_NAME`              | 400         | Invalid LLM name provided     |
| `INVALID_AI_COPILOT_LLMS`       | 400         | Invalid AI Copilot LLM list   |
| `INVALID_THEME_NAME`            | 400         | Invalid theme name provided   |
| `INVALID_DATA_APP_API_KEY`      | 401         | Invalid API key               |
| `INTERNAL_SERVER_ERROR`         | 500         | Server error                  |

## Quick Start Guide

<Steps>
  <Step title="Verify prerequisites">
    Before creating a workspace, ensure you have:

    * A valid API token from your data app
    * Either a datasource or datamart already configured
    * The exact name of your datasource or datamart (case-sensitive)
  </Step>

  <Step title="Choose your connection type">
    Decide which connection type fits your use case:

    * **DATASOURCE**: For connecting to a single data source
    * **DATAMART**: For connecting to a pre-configured datamart with table/column configurations
    * **MULTI\_DATASOURCE**: For workspaces that need access to multiple datasources
    * **MULTI\_DATAMART**: For workspaces that support multiple datamarts (same API shape as multi-datasource: only `name` and `connectionType` in the minimal body)

    <Tip>
      Start with DATASOURCE for simple use cases. Use DATAMART when you need structured access with tenancy settings. For multi-datamart setup in the product UI, see [Multi Datamart Workspace](/guides/workspace/multi-datamart-workspace).
    </Tip>
  </Step>

  <Step title="Create your workspace">
    Make the API call with your chosen configuration:

    ```bash theme={"dark"}
    curl --request POST \
      --url https://api.usedatabrain.com/api/v2/workspace \
      --header 'Authorization: Bearer dbn_live_abc123...' \
      --header 'Content-Type: application/json' \
      --data '{
        "name": "My Analytics Workspace",
        "connectionType": "DATASOURCE",
        "datasourceName": "postgres-main"
      }'
    ```

    <Check>
      Successful response returns the workspace name. Save this for use in embed configurations.
    </Check>
  </Step>

  <Step title="Use your workspace">
    Reference your workspace in dashboards and metrics:

    ```javascript theme={"dark"}
    const embedConfig = {
      workspaceName: 'My Analytics Workspace',
      // ... other configuration
    };
    ```
  </Step>
</Steps>
