> ## 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 Embed and Client

> Retrieve metrics available for a specific embed configuration and client, with support for pagination and client-specific filtering.

Get a list of metrics that are accessible through a specific embed configuration for a particular client. This endpoint is essential for understanding what metrics are available for querying within an embedded dashboard context.

<Note>
  This endpoint returns metrics filtered by client access. Client-created metrics are only visible to the specific client that created them, while shared metrics are visible to all clients.
</Note>

## Authentication

All API requests must include your API key in the Authorization header. Get your API token when creating a data app - see our [data app creation guide](/guides/datasources/create-a-data-app) for details.

**Finding your API token:** For detailed instructions, see the [API Token guide](/developer-docs/helpers/api-token).

<Panel>
  <RequestExample>
    ```bash Authentication theme={"dark"}
    curl --request GET \
      --url https://api.usedatabrain.com/api/v2/data-app/metrics \
      --header 'Authorization: Bearer dbn_live_...'
    ```
  </RequestExample>
</Panel>

## Headers

<ParamField header="Authorization" type="string" required>
  Bearer token for API authentication. Use your API key from the data app.

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

## Query Parameters

<ParamField query="embedId" type="string" required>
  The embed configuration ID to fetch metrics for. This identifies which embedded dashboard's metrics you want to retrieve.

  <Expandable title="Finding embed IDs">
    * Created when you configure an embed via the [Create Embed API](/developer-docs/helpers/api-reference/create-embed)
    * Retrieved via the [List Embeds API](/developer-docs/helpers/api-reference/list-embed)
    * Available in your DataBrain dashboard embed settings
  </Expandable>
</ParamField>

<ParamField query="clientId" type="string" required>
  The client identifier for filtering metrics. Determines which metrics the client has access to based on their permissions and ownership.
</ParamField>

<ParamField query="isPagination" type="string">
  Enable pagination to limit the number of results returned. Pass `"true"` to enable pagination with a limit of 10 per page.

  **Note:** Query parameters are passed as strings. Use `"true"` or `"false"`.
</ParamField>

<ParamField query="pageNumber" type="string">
  Page number for pagination (1-based). Only used when isPagination is `"true"`. Must be a numeric string (e.g., `"1"`, `"2"`).
</ParamField>

<ParamField query="isMetric" type="string">
  When set to `"true"`, returns only the list of metrics — excluding elements and summaries. Pass `"false"` or omit this parameter to return all items, including non-metric components.

  **Note:** Query parameters are passed as strings. Use `"true"` or `"false"`.
</ParamField>

<ParamField query="userIdentifier" type="string">
  Filter metrics by the user identifier who created them. When provided, only returns metrics created by the specified user.

  <Expandable title="User filtering behavior">
    * When `userIdentifier` is provided: Returns only metrics where `createdByIdentifier` matches
    * When omitted: Returns all metrics the client has access to
    * System-created metrics (no creator) are excluded when filtering by user
    * Useful for showing "My Metrics" views in your application
  </Expandable>
</ParamField>

## Response

<ResponseField name="data" type="array">
  Array of metric objects available for the specified embed and client.

  <ResponseField name="data.name" type="string">
    Display name of the metric.
  </ResponseField>

  <ResponseField name="data.metricId" type="string">
    Unique identifier for the metric that can be used in query operations.
  </ResponseField>

  <ResponseField name="data.isPublished" type="boolean">
    Indicates whether the metric is published and visible to end users.

    * `true`: Metric is published and visible
    * `false`: Metric is unpublished (hidden but not deleted)
    * System-created metrics (without a creator) are always `true`
  </ResponseField>

  <ResponseField name="data.createdByUser" type="string | null">
    The identifier of the user who created this metric, or `null` for system-created metrics.

    * Non-null value: Indicates a user-created metric with the creator's identifier
    * `null`: Indicates a system-created or admin-created metric
    * Useful for implementing "My Metrics" filtering and ownership displays
  </ResponseField>
</ResponseField>

<ResponseField name="error" type="object">
  Error object returned only when the request fails. Not present in successful responses.

  <Expandable title="Error structure">
    <ResponseField name="error.code" type="string">
      Machine-readable error code for programmatic handling.
    </ResponseField>

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

## Examples

<Panel>
  <RequestExample>
    ```bash cURL theme={"dark"}
    curl --request GET \
      --url 'https://api.usedatabrain.com/api/v2/data-app/metrics?embedId=embed_abc123&clientId=client_xyz789&isPagination=true&pageNumber=1&isMetric=true' \
      --header 'Authorization: Bearer dbn_live_abc123...'
    ```

    ```javascript Node.js theme={"dark"}
    const params = new URLSearchParams({
      embedId: 'embed_abc123',
      clientId: 'client_xyz789',
      isPagination: 'true',
      pageNumber: '1',
      isMetric: 'true'
    });

    const response = await fetch(`https://api.usedatabrain.com/api/v2/data-app/metrics?${params}`, {
      method: 'GET',
      headers: {
        'Authorization': 'Bearer dbn_live_abc123...'
      }
    });

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

    ```python Python theme={"dark"}
    import requests

    url = "https://api.usedatabrain.com/api/v2/data-app/metrics"
    headers = {
        "Authorization": "Bearer dbn_live_abc123..."
    }
    params = {
        "embedId": "embed_abc123",
        "clientId": "client_xyz789",
        "isPagination": "true",
        "pageNumber": "1",
        "isMetric": "true"
    }

    response = requests.get(url, headers=headers, params=params)
    data = response.json()
    print(f"Available metrics: {data['data']}")
    ```

    ```ruby Ruby theme={"dark"}
    require 'net/http'
    require 'json'

    uri = URI('https://api.usedatabrain.com/api/v2/data-app/metrics')
    params = {
      embedId: 'embed_abc123',
      clientId: 'client_xyz789',
      isPagination: 'true',
      pageNumber: '1',
      isMetric: 'true'
    }
    uri.query = URI.encode_www_form(params)

    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)
    data = JSON.parse(response.body)
    puts "Available metrics: #{data['data']}"
    ```

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

    public class DataBrainMetricsAPI {
        public static void main(String[] args) throws Exception {
            HttpClient client = HttpClient.newHttpClient();
            
            String url = "https://api.usedatabrain.com/api/v2/data-app/metrics" +
                "?embedId=embed_abc123&clientId=client_xyz789&isPagination=true&pageNumber=1&isMetric=true";
            
            HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("Authorization", "Bearer dbn_live_abc123...")
                .GET()
                .build();
                
            HttpResponse<String> response = client.send(request, 
                HttpResponse.BodyHandlers.ofString());
                
            System.out.println("Response: " + response.body());
        }
    }
    ```

    ```go Go theme={"dark"}
    package main

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

    type Metric struct {
        Name          string  `json:"name"`
        MetricID      string  `json:"metricId"`
        IsPublished   bool    `json:"isPublished"`
        CreatedByUser *string `json:"createdByUser"`
    }

    type MetricResponse struct {
        Data  []Metric    `json:"data"`
        Error interface{} `json:"error"`
    }

    func main() {
        baseURL := "https://api.usedatabrain.com/api/v2/data-app/metrics"
        params := url.Values{}
        params.Add("embedId", "embed_abc123")
        params.Add("clientId", "client_xyz789")
        params.Add("isPagination", "true")
        params.Add("pageNumber", "1")
        params.Add("isMetric", "true")
        
        fullURL := fmt.Sprintf("%s?%s", baseURL, params.Encode())
        
        req, _ := http.NewRequest("GET", fullURL, nil)
        req.Header.Set("Authorization", "Bearer dbn_live_abc123...")
        
        client := &http.Client{}
        resp, err := client.Do(req)
        if err != nil {
            panic(err)
        }
        defer resp.Body.Close()
        
        var metricResp MetricResponse
        json.NewDecoder(resp.Body).Decode(&metricResp)
        
        fmt.Printf("Available metrics: %+v\n", metricResp.Data)
    }
    ```

    ```php PHP theme={"dark"}
    <?php
    $params = http_build_query([
        'embedId' => 'embed_abc123',
        'clientId' => 'client_xyz789',
        'isPagination' => 'true',
        'pageNumber' => '1',
        'isMetric' => 'true'
    ]);

    $url = 'https://api.usedatabrain.com/api/v2/data-app/metrics?' . $params;

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

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

    echo "Available metrics: " . print_r($response['data'], true);
    ?>
    ```
  </RequestExample>

  <ResponseExample>
    ```json Success Response theme={"dark"}
    {
      "data": [
        {
          "name": "Total Revenue",
          "metricId": "metric_revenue_123",
          "isPublished": true,
          "createdByUser": null
        },
        {
          "name": "Active Users",
          "metricId": "metric_users_456",
          "isPublished": true,
          "createdByUser": "user_abc123"
        },
        {
          "name": "Conversion Rate",
          "metricId": "metric_conversion_789",
          "isPublished": false,
          "createdByUser": "user_abc123"
        }
      ]
    }
    ```

    ```json Empty Results Response theme={"dark"}
    {
      "data": []
    }
    ```

    ```json Error Response (400) theme={"dark"}
    {
      "error": {
        "code": "INVALID_DATA_APP_API_KEY",
        "message": "invalid or expired API KEY, data app not found"
      }
    }
    ```

    ```json Error Response (400) theme={"dark"}
    {
      "error": {
        "code": "EMBED_PARAM_ERROR",
        "message": "invalid embed id, embed id not found for given data app"
      }
    }
    ```

    ```json Error Response (400) theme={"dark"}
    {
      "error": {
        "code": "INVALID_REQUEST_BODY",
        "message": "\"embedId\" is required"
      }
    }
    ```
  </ResponseExample>
</Panel>

## HTTP Status Code Summary

| Status Code | Description                                                                                                   |
| ----------- | ------------------------------------------------------------------------------------------------------------- |
| `200`       | **OK** - Metrics retrieved successfully                                                                       |
| `400`       | **Bad Request** - Invalid request parameters, missing required fields, invalid API key, or embed ID not found |

## Possible Errors

| Error Code                 | HTTP Status | Description                            |
| -------------------------- | ----------- | -------------------------------------- |
| `INVALID_DATA_APP_API_KEY` | 400         | Invalid or expired API key             |
| `EMBED_PARAM_ERROR`        | 400         | Embed ID not found for data app        |
| `INVALID_REQUEST_BODY`     | 400         | Missing or invalid required parameters |

## Client Access Control

### Metric Visibility Rules

1. **Shared Metrics**: Available to all clients within the embed
2. **Client-Created Metrics**: Only visible to the client that created them
3. **Access Settings**: Controlled by the embed configuration's access settings

### Understanding Client-Specific Results

The API automatically filters metrics based on the client's access permissions:

```javascript theme={"dark"}
// Client A will see their own metrics + shared metrics
const clientAMetrics = await fetchMetrics('embed_123', 'client_A');

// Client B will see their own metrics + shared metrics (different from Client A)
const clientBMetrics = await fetchMetrics('embed_123', 'client_B');
```
