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

# Fetch Metrics by Workspace

> Retrieve metrics from a workspace with optional pagination support.

Retrieve metrics available in a workspace. Use this endpoint to discover metrics for provisioning and embedding in your application.

<Note>
  This endpoint operates at the workspace level using a service token. Use the workspace name to scope which metrics are returned. Supports pagination for workspaces with many metrics.
</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="workspaceName" type="string" required>
  Name of the workspace to fetch metrics from. Must match an existing workspace in your organization.

  <Expandable title="Finding workspace names">
    * Use the [List Workspaces](/developer-docs/helpers/api-reference/list-workspaces) endpoint to see all available workspaces
    * Names are case-sensitive
    * Must be an exact match
  </Expandable>
</ParamField>

<ParamField body="isPagination" type="boolean">
  Enable pagination to retrieve metrics in batches of 10.

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

  <Expandable title="When to use pagination">
    - Use pagination when you have more than 20 metrics in a workspace
    - Improves response times for large datasets
    - Each page returns up to 10 metrics
  </Expandable>
</ParamField>

<ParamField body="pageNumber" type="number">
  The page number to retrieve when pagination is enabled. Pages are 1-indexed.

  **Note:** This parameter is only used when `isPagination` is set to `true`.
</ParamField>

## Response

<ResponseField name="data" type="array">
  Array of metric objects. Returns empty array if no metrics exist or page number exceeds available pages.

  <Expandable title="metric object properties">
    <ResponseField name="name" type="string">
      Display name of the metric.
    </ResponseField>

    <ResponseField name="metricId" type="string">
      Unique identifier for the metric.
    </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 - All Metrics theme={"dark"}
    curl --request POST \
      --url https://api.usedatabrain.com/api/v2/workspace/metrics \
      --header 'Authorization: Bearer dbn_live_abc123...' \
      --header 'Content-Type: application/json' \
      --data '{
        "workspaceName": "my-workspace"
      }'
    ```

    ```bash cURL - With Pagination theme={"dark"}
    curl --request POST \
      --url https://api.usedatabrain.com/api/v2/workspace/metrics \
      --header 'Authorization: Bearer dbn_live_abc123...' \
      --header 'Content-Type: application/json' \
      --data '{
        "workspaceName": "my-workspace",
        "isPagination": true,
        "pageNumber": 1
      }'
    ```

    ```javascript Node.js icon="fa-brands fa-node-js" theme={"dark"}
    const response = await fetch('https://api.usedatabrain.com/api/v2/workspace/metrics', {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer dbn_live_abc123...',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        workspaceName: 'my-workspace',
        isPagination: true,
        pageNumber: 1
      })
    });

    const result = await response.json();
    console.log('Metrics:', result.data);
    ```

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

    response = requests.post(
        'https://api.usedatabrain.com/api/v2/workspace/metrics',
        headers={
            'Authorization': 'Bearer dbn_live_abc123...',
            'Content-Type': 'application/json'
        },
        json={
            'workspaceName': 'my-workspace',
            'isPagination': True,
            'pageNumber': 1
        }
    )

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

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

    uri = URI('https://api.usedatabrain.com/api/v2/workspace/metrics')
    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 = {
      workspaceName: 'my-workspace',
      isPagination: true,
      pageNumber: 1
    }.to_json

    response = http.request(request)
    result = JSON.parse(response.body)
    puts "Metrics: #{result['data']}"
    ```

    ```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 FetchMetrics {
        public static void main(String[] args) throws Exception {
            HttpClient client = HttpClient.newHttpClient();

            String requestBody = """
                {
                    "workspaceName": "my-workspace",
                    "isPagination": true,
                    "pageNumber": 1
                }
                """;

            HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://api.usedatabrain.com/api/v2/workspace/metrics"))
                .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"
        "io"
        "net/http"
    )

    type MetricsRequest struct {
        WorkspaceName string `json:"workspaceName"`
        IsPagination  bool   `json:"isPagination,omitempty"`
        PageNumber    int    `json:"pageNumber,omitempty"`
    }

    func main() {
        reqData := MetricsRequest{
            WorkspaceName: "my-workspace",
            IsPagination:  true,
            PageNumber:    1,
        }

        jsonData, _ := json.Marshal(reqData)

        req, _ := http.NewRequest("POST",
            "https://api.usedatabrain.com/api/v2/workspace/metrics",
            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()

        body, _ := io.ReadAll(resp.Body)
        fmt.Println(string(body))
    }
    ```

    ```php PHP icon="fa-brands fa-php" theme={"dark"}
    <?php
    $url = 'https://api.usedatabrain.com/api/v2/workspace/metrics';
    $data = [
        'workspaceName' => 'my-workspace',
        'isPagination' => true,
        'pageNumber' => 1
    ];

    $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);

    print_r($result['data']);
    ?>
    ```
  </RequestExample>

  <ResponseExample>
    ```json 200 - Success theme={"dark"}
    {
      "data": [
        {
          "name": "Monthly Revenue",
          "metricId": "metric_abc123"
        },
        {
          "name": "Active Users",
          "metricId": "metric_def456"
        }
      ],
      "error": null
    }
    ```

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

    ```json 400 - Invalid Request Body theme={"dark"}
    {
      "error": {
        "code": "INVALID_REQUEST_BODY",
        "message": "\"workspaceName\" is required"
      }
    }
    ```

    ```json 400 - Workspace Not Found theme={"dark"}
    {
      "error": {
        "code": "WORKSPACE_ID_ERROR",
        "message": "The workspace name provided does not exist"
      }
    }
    ```

    ```json 401 - Unauthorized theme={"dark"}
    {
      "error": {
        "code": "INVALID_DATA_APP_API_KEY",
        "message": "API Key is not provided or Invalid!"
      }
    }
    ```
  </ResponseExample>
</Panel>

## HTTP Status Code Summary

| Status Code | Description                                       |
| ----------- | ------------------------------------------------- |
| `200`       | **OK** - Metrics retrieved 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 request body parameters |
| `WORKSPACE_ID_ERROR`       | 400         | Workspace name does not exist              |
| `INVALID_DATA_APP_API_KEY` | 401         | Invalid or expired API key                 |
| `INTERNAL_SERVER_ERROR`    | 500         | Server error                               |

## Next Steps

<CardGroup cols={2}>
  <Card title="Fetch Dashboards by Workspace" icon="table-columns" href="/developer-docs/helpers/api-reference/cloud-databrain-endpoint">
    Retrieve dashboards from a workspace
  </Card>

  <Card title="List Workspaces" icon="list" href="/developer-docs/helpers/api-reference/list-workspaces">
    List all workspaces in your organization
  </Card>

  <Card title="Create Workspace" icon="plus" href="/developer-docs/helpers/api-reference/create-workspace">
    Create a new workspace for your analytics environment
  </Card>

  <Card title="Guest Token API" icon="key" href="/developer-docs/helpers/api-reference/token">
    Generate secure tokens for embedded access
  </Card>
</CardGroup>
