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

# Update Workspace

> Update an existing workspace's connection settings to change datasource, datamart, multi-datasource, or multi-datamart configuration.

Update the connection settings of an existing workspace. You can switch between datasource, datamart, multi-datasource, and multi-datamart configurations. Updating a workspace also updates all associated metrics to use the new connection.

<Warning>
  **Important:** Updating a workspace connection will automatically update all metrics in that workspace to use the new datasource or datamart connection. Ensure the new connection has compatible table and column structures to avoid breaking existing metrics.
</Warning>

<Note>
  The workspace name is used to identify which workspace to update and cannot be changed through this endpoint. To rename a workspace, you'll need to create a new one and migrate your content.
</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 existing workspace to update. Must match exactly (case-sensitive).

  <Expandable title="Finding workspace names">
    * Use the [List Workspaces API](/developer-docs/helpers/api-reference/list-workspaces) to get all workspace names
    * Names are case-sensitive and must match exactly
    * This field identifies which workspace to update
  </Expandable>
</ParamField>

<ParamField body="connectionType" type="string" required>
  New connection type 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
    * **MULTI\_DATAMART**: Allow switching between multiple datamarts within this workspace

    **Note:** Changing connection type will update all metrics in this workspace. For `MULTI_DATASOURCE` or `MULTI_DATAMART`, `datasourceName` and `datamartName` are optional; the API clears prior single-datasource or single-datamart links and enables the selected multi mode. For `DATASOURCE` or `DATAMART`, `datasourceName` or `datamartName` is required (respectively), and multi-datasource / multi-datamart modes are turned off.
  </Expandable>
</ParamField>

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

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

  <Expandable title="Datasource considerations">
    * Must be an existing datasource in your organization
    * Use the exact name as stored in datasource credentials
    * Names are case-sensitive
    * All metrics will be updated to use this datasource
  </Expandable>
</ParamField>

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

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

  <Expandable title="Datamart considerations">
    * Must be an existing datamart in your organization
    * Use the [List Datamarts API](/developer-docs/helpers/api-reference/list-datamarts) to find available datamarts
    * Names are case-sensitive
    * All metrics will be updated to use this datamart's datasource
  </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 or disable AI-powered metric suggestions for this workspace.
</ParamField>

<ParamField body="isEnableMetricSummary" type="boolean">
  Optional flag to enable or disable AI-generated metric summaries for this workspace.
</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 updated workspace information on success.

  <Expandable title="data properties">
    <ResponseField name="name" type="string">
      The name of the successfully updated 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 - Switch to Datasource theme={"dark"}
    curl --request PUT \
      --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-production"
      }'
    ```

    ```bash cURL - Switch to Datamart theme={"dark"}
    curl --request PUT \
      --url https://api.usedatabrain.com/api/v2/workspace \
      --header 'Authorization: Bearer dbn_live_abc123...' \
      --header 'Content-Type: application/json' \
      --data '{
        "name": "Sales Analytics",
        "connectionType": "DATAMART",
        "datamartName": "sales-datamart"
      }'
    ```

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

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

    ```bash cURL - Update AI + Theme Settings theme={"dark"}
    curl --request PUT \
      --url https://api.usedatabrain.com/api/v2/workspace \
      --header 'Authorization: Bearer dbn_live_abc123...' \
      --header 'Content-Type: application/json' \
      --data '{
        "name": "Sales Analytics",
        "connectionType": "DATAMART",
        "datamartName": "sales-datamart",
        "llmName": "gpt-4o",
        "aiCopilotLlms": ["gpt-4o", "gpt-4.1-mini"],
        "isEnableMetricSuggestions": true,
        "isEnableMetricSummary": true,
        "summaryType": "custom",
        "customSummaryPrompt": "Summarize weekly KPI shifts with root-cause hypotheses.",
        "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: 'PUT',
      headers: {
        'Authorization': 'Bearer dbn_live_abc123...',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        name: 'Sales Analytics',
        connectionType: 'DATASOURCE',
        datasourceName: 'postgres-production'
      })
    });

    const result = await response.json();

    if (result.error) {
      console.error('Update failed:', result.error.message);
    } else {
      console.log('Workspace updated:', result.data.name);
    }
    ```

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

    response = requests.put(
        '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-production'
        }
    )

    result = response.json()

    if result.get('error'):
        print(f"Update failed: {result['error']['message']}")
    else:
        print(f"Workspace updated: {result['data']['name']}")
    ```

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

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

    if result['error']
      puts "Update failed: #{result['error']['message']}"
    else
      puts "Workspace updated: #{result['data']['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 UpdateWorkspace {
        public static void main(String[] args) throws Exception {
            HttpClient client = HttpClient.newHttpClient();
            
            String requestBody = """
                {
                    "name": "Sales Analytics",
                    "connectionType": "DATASOURCE",
                    "datasourceName": "postgres-production"
                }
                """;
            
            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")
                .PUT(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 WorkspaceUpdateRequest struct {
        Name            string `json:"name"`
        ConnectionType  string `json:"connectionType"`
        DatasourceName  string `json:"datasourceName,omitempty"`
        DatamartName    string `json:"datamartName,omitempty"`
    }

    func main() {
        reqData := WorkspaceUpdateRequest{
            Name:           "Sales Analytics",
            ConnectionType: "DATASOURCE",
            DatasourceName: "postgres-production",
        }
        
        jsonData, _ := json.Marshal(reqData)
        
        req, _ := http.NewRequest("PUT", 
            "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 updated 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-production'
    ];

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

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

    if (isset($result['error'])) {
        echo "Update failed: " . $result['error']['message'];
    } else {
        echo "Workspace updated: " . $result['data']['name'];
    }
    ?>
    ```
  </RequestExample>

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

    ```json 400 - Workspace Not Found theme={"dark"}
    {
      "error": {
        "code": "WORKSPACE_DOES_NOT_EXIST",
        "message": "Workspace does not exist"
      }
    }
    ```

    ```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 updated 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_DOES_NOT_EXIST` | 400         | Workspace not found           |
| `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                  |
