> ## 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 metric data by data app

> Execute queries on metrics within your embedded dashboards and retrieve the resulting data.

Query specific metrics from your embedded dashboards to retrieve data programmatically. This endpoint allows you to fetch metric data with optional filtering and is essential for building custom analytics interfaces or exporting data from your embedded dashboards.

<Warning>
  **Endpoint Migration Notice:** We're transitioning to kebab-case endpoints. The new endpoint is `/api/v2/data-app/query`. The old endpoint `/api/v2/dataApp/query` will be deprecated soon. Please update your integrations to use the new endpoint format.
</Warning>

<Note>
  This endpoint requires an embed ID, metric ID, and client ID. The metric must be associated with the specified embed configuration for the query to succeed.
</Note>

## Endpoint Formats

<Tabs>
  <Tab title="New Endpoint (Recommended)">
    ```
    POST https://api.usedatabrain.com/api/v2/data-app/query
    ```

    **Use this endpoint** for all new integrations. This is the recommended endpoint format.
  </Tab>

  <Tab title="Legacy Endpoint (Deprecated Soon)">
    ```
    POST https://api.usedatabrain.com/api/v2/dataApp/query
    ```

    This endpoint still works but will be deprecated. Please migrate to the new endpoint format.
  </Tab>
</Tabs>

## 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 POST \
      --url https://api.usedatabrain.com/api/v2/data-app/query \
      --header 'Authorization: Bearer dbn_live_...' \
      --header 'Content-Type: application/json'
    ```
  </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>

<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="embedId" type="string" required>
  The unique identifier of the embed configuration containing the metric.

  <Expandable title="Finding embed IDs">
    * Use the List All Embeds API to get embed IDs
    * Check the response from embed creation
    * Available in the DataBrain dashboard when viewing embed configurations
  </Expandable>
</ParamField>

<ParamField body="metricId" type="string" required>
  The unique identifier of the metric to query.

  <Expandable title="Finding metric IDs">
    * Available in the metric URL: `/metric/{metricId}`
    * Retrieved via the [Fetch Metrics by Embed](/developer-docs/helpers/api-reference/fetch-metrics-by-embed-and-client) API
    * Found in the DataBrain dashboard when viewing a metric
  </Expandable>
</ParamField>

<ParamField body="clientId" type="string" required>
  Unique identifier for the end user making the query. Used for row-level security and access control.

  <Expandable title="Client ID usage">
    * Should match the clientId used in guest token generation
    * Used for applying row-level security filters
    * Consistent across user sessions
    * Enables multi-tenant data isolation
  </Expandable>
</ParamField>

<ParamField body="dashboardFilter" type="object">
  Dashboard-level filters to apply to the metric query. These filters affect the entire dashboard context.

  <Expandable title="Dashboard filter examples">
    ```json theme={"dark"}
    {
      "date_range": {
        "start": "2024-01-01",
        "end": "2024-01-31"
      },
      "region": "north-america",
      "product_category": "electronics"
    }
    ```
  </Expandable>
</ParamField>

<ParamField body="metricFilter" type="object">
  Metric-specific filters to apply to the query. Used for row-level security and additional filtering.

  <Expandable title="Metric filter examples">
    ```json theme={"dark"}
    {
      "customer_segment": "enterprise",
      "product_category": "software",
      "status": "active"
    }
    ```
  </Expandable>
</ParamField>

<ParamField body="datasourceName" type="string">
  Optional string. Use when the dashboard’s workspace is configured for **multiple datasources** (`MULTI_DATASOURCE`): pass the datasource **name** (as in Data Studio / your integration credentials) so the query runs against that datasource. If the name does not resolve, the API returns `DATASOURCE_NAME_ERROR` (400).

  <Expandable title="Details">
    * Not used for multi-datamart workspaces; use `dataMartName` instead when applicable
    * For workspaces that are not multi-datasource, omit this field unless your integration already relies on it
  </Expandable>
</ParamField>

<ParamField body="dataMartName" type="string">
  Optional string. Use the exact JSON property name **`dataMartName`** (camelCase with a capital **M** in `Mart`).

  When the dashboard’s workspace is configured for **multiple datamarts** (`MULTI_DATAMART`), pass the datamart **name** so the query resolves that datamart’s linked datasource. Names follow the same rules as in the [List Datamarts](/developer-docs/helpers/api-reference/list-datamarts) API. If the name does not resolve, the API returns `DATAMART_NAME_ERROR` (400).

  <Expandable title="Details">
    * Not used for multi-datasource workspaces; use `datasourceName` instead when applicable
    * Distinct from workspace create/update body field `datamartName` (different casing for this endpoint)
  </Expandable>
</ParamField>

## Response

<ResponseField name="data" type="array">
  Array of objects containing the query results. Each object represents a row of data with column names as keys.

  ```json Example theme={"dark"}
  [
    {
      "date": "2024-01-01",
      "revenue": 15000,
      "region": "north-america"
    },
    {
      "date": "2024-01-02",
      "revenue": 18000,
      "region": "north-america"
    }
  ]
  ```
</ResponseField>

<ResponseField name="timeTaken" type="number">
  Query execution time in milliseconds.
</ResponseField>

<ResponseField name="comparisonValue" type="number">
  Comparison value for metrics with comparison enabled.
</ResponseField>

<ResponseField name="totalRecords" type="number">
  Total number of records in the result set.
</ResponseField>

<ResponseField name="metaData" type="object">
  Metadata about the query results.

  <ResponseField name="metaData.columns" type="array">
    Array of column information.

    <ResponseField name="metaData.columns.name" type="string">
      Column name.
    </ResponseField>

    <ResponseField name="metaData.columns.dataType" type="string">
      Data type of the column (e.g., "string", "number", "date").
    </ResponseField>
  </ResponseField>

  <ResponseField name="metaData.groupbyColumnList" type="array">
    List of columns used in GROUP BY operations.
  </ResponseField>
</ResponseField>

<ResponseField name="metricid" type="string">
  The metric ID that was queried (echo of request parameter).
</ResponseField>

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

## Examples

<Panel>
  <RequestExample>
    ```bash cURL theme={"dark"}
    curl --request POST \
      --url https://api.usedatabrain.com/api/v2/data-app/query \
      --header 'Authorization: Bearer dbn_live_abc123...' \
      --header 'Content-Type: application/json' \
      --data '{
        "embedId": "embed_123",
        "metricId": "metric_456",
        "clientId": "user_789",
        "dashboardFilter": {
          "date_range": {
            "start": "2024-01-01",
            "end": "2024-01-31"
          }
        },
        "metricFilter": {
          "region": "north-america"
        }
      }'
    ```

    ```javascript Node.js icon="fa-brands fa-node-js" theme={"dark"}
    const response = await fetch('https://api.usedatabrain.com/api/v2/data-app/query', {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer dbn_live_abc123...',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        embedId: 'embed_123',
        metricId: 'metric_456',
        clientId: 'user_789',
        dashboardFilter: {
          date_range: {
            start: '2024-01-01',
            end: '2024-01-31'
          }
        },
        metricFilter: {
          region: 'north-america'
        }
      })
    });

    const data = await response.json();
    console.log('Query results:', data.data.length, 'rows');
    console.log('Time taken:', data.timeTaken, 'ms');
    ```

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

    url = "https://api.usedatabrain.com/api/v2/data-app/query"
    headers = {
        "Authorization": "Bearer dbn_live_abc123...",
        "Content-Type": "application/json"
    }
    payload = {
        "embedId": "embed_123",
        "metricId": "metric_456",
        "clientId": "user_789",
        "dashboardFilter": {
            "date_range": {
                "start": "2024-01-01",
                "end": "2024-01-31"
            }
        },
        "metricFilter": {
            "region": "north-america"
        }
    }

    response = requests.post(url, headers=headers, data=json.dumps(payload))
    data = response.json()
    print(f"Query results: {len(data['data'])} rows")
    print(f"Time taken: {data['timeTaken']} ms")
    ```

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

    uri = URI('https://api.usedatabrain.com/api/v2/data-app/query')
    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 = {
      embedId: 'embed_123',
      metricId: 'metric_456',
      clientId: 'user_789',
      dashboardFilter: {
        date_range: {
          start: '2024-01-01',
          end: '2024-01-31'
        }
      },
      metricFilter: {
        region: 'north-america'
      }
    }.to_json

    response = http.request(request)
    data = JSON.parse(response.body)
    puts "Query results: #{data['data'].length} rows"
    puts "Time taken: #{data['timeTaken']} ms"
    ```

    ```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;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import java.util.Map;
    import java.util.HashMap;

    public class DataBrainQueryAPI {
        public static void main(String[] args) throws Exception {
            HttpClient client = HttpClient.newHttpClient();
            ObjectMapper mapper = new ObjectMapper();
            
            Map<String, Object> dashboardFilter = new HashMap<>();
            Map<String, String> dateRange = new HashMap<>();
            dateRange.put("start", "2024-01-01");
            dateRange.put("end", "2024-01-31");
            dashboardFilter.put("date_range", dateRange);
            
            Map<String, Object> metricFilter = new HashMap<>();
            metricFilter.put("region", "north-america");
            
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("embedId", "embed_123");
            requestBody.put("metricId", "metric_456");
            requestBody.put("clientId", "user_789");
            requestBody.put("dashboardFilter", dashboardFilter);
            requestBody.put("metricFilter", metricFilter);
            
            String jsonBody = mapper.writeValueAsString(requestBody);
            
            HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://api.usedatabrain.com/api/v2/data-app/query"))
                .header("Authorization", "Bearer dbn_live_abc123...")
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(jsonBody))
                .build();
                
            HttpResponse<String> response = client.send(request, 
                HttpResponse.BodyHandlers.ofString());
                
            System.out.println("Response: " + response.body());
        }
    }
    ```

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

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

    type QueryRequest struct {
        EmbedId         string                 `json:"embedId"`
        MetricId        string                 `json:"metricId"`
        ClientId        string                 `json:"clientId"`
        DashboardFilter map[string]interface{} `json:"dashboardFilter,omitempty"`
        MetricFilter    map[string]interface{} `json:"metricFilter,omitempty"`
    }

    type QueryResponse struct {
        Data         []map[string]interface{} `json:"data"`
        TimeTaken    int                      `json:"timeTaken"`
        TotalRecords int                      `json:"totalRecords"`
        MetaData     map[string]interface{}   `json:"metaData"`
    }

    func main() {
        reqBody := QueryRequest{
            EmbedId:  "embed_123",
            MetricId: "metric_456",
            ClientId: "user_789",
            DashboardFilter: map[string]interface{}{
                "date_range": map[string]string{
                    "start": "2024-01-01",
                    "end":   "2024-01-31",
                },
            },
            MetricFilter: map[string]interface{}{
                "region": "north-america",
            },
        }
        
        jsonData, _ := json.Marshal(reqBody)
        
        req, _ := http.NewRequest("POST", 
            "https://api.usedatabrain.com/api/v2/data-app/query", 
            bytes.NewBuffer(jsonData))
        
        req.Header.Set("Authorization", "Bearer dbn_live_abc123...")
        req.Header.Set("Content-Type", "application/json")
        
        client := &http.Client{}
        resp, err := client.Do(req)
        if err != nil {
            panic(err)
        }
        defer resp.Body.Close()
        
        var queryResp QueryResponse
        json.NewDecoder(resp.Body).Decode(&queryResp)
        
        fmt.Printf("Query results: %d rows\n", len(queryResp.Data))
        fmt.Printf("Time taken: %d ms\n", queryResp.TimeTaken)
    }
    ```

    ```php PHP icon="fa-brands fa-php" theme={"dark"}
    <?php
    $url = 'https://api.usedatabrain.com/api/v2/data-app/query';
    $data = [
        'embedId' => 'embed_123',
        'metricId' => 'metric_456',
        'clientId' => 'user_789',
        'dashboardFilter' => [
            'date_range' => [
                'start' => '2024-01-01',
                'end' => '2024-01-31'
            ]
        ],
        'metricFilter' => [
            'region' => 'north-america'
        ]
    ];

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

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

    echo "Query results: " . count($response['data']) . " rows\n";
    echo "Time taken: " . $response['timeTaken'] . " ms\n";
    ?>
    ```
  </RequestExample>

  <ResponseExample>
    ```json Success Response theme={"dark"}
    {
      "data": [
        {
          "date": "2024-01-01",
          "revenue": 15000,
          "region": "north-america",
          "customer_count": 45
        },
        {
          "date": "2024-01-02", 
          "revenue": 18500,
          "region": "north-america",
          "customer_count": 52
        },
        {
          "date": "2024-01-03",
          "revenue": 16500,
          "region": "north-america",
          "customer_count": 138
        }
      ],
      "timeTaken": 245,
      "comparisonValue": 12500,
      "totalRecords": 31,
      "metaData": {
        "columns": [
          {
            "name": "date",
            "dataType": "date"
          },
          {
            "name": "revenue",
            "dataType": "number"
          },
          {
            "name": "region",
            "dataType": "string"
          },
          {
            "name": "customer_count",
            "dataType": "number"
          }
        ],
        "groupbyColumnList": ["date", "region"]
      },
      "metricid": "metric_456",
      "error": null
    }
    ```

    ```json Empty Results Response theme={"dark"}
    {
      "data": [],
      "timeTaken": 45,
      "totalRecords": 0,
      "metaData": {
        "columns": [],
        "groupbyColumnList": []
      },
      "metricid": "metric_456",
      "error": null
    }
    ```

    ```json Error Response (401) theme={"dark"}
    {
      "error": {
        "code": "INVALID_DATA_APP_API_KEY",
        "message": "Invalid or missing Data App API Key"
      }
    }
    ```

    ```json Error Response (400) theme={"dark"}
    {
      "error": {
        "code": "INVALID_EMBED_ID",
        "message": "Embed ID not found or access denied",
        "status": 400
      }
    }
    ```

    ```json Error Response (404) theme={"dark"}
    {
      "error": {
        "code": "EMBED_PARAM_ERROR",
        "message": "Embed ID not found or mismatched with API Key"
      }
    }
    ```
  </ResponseExample>
</Panel>

## Error Codes

<ResponseField name="INVALID_EMBED_ID" type="string">
  **Invalid embed ID** - The specified embed ID doesn't exist or you don't have access
</ResponseField>

<ResponseField name="INVALID_METRIC_ID" type="string">
  **Invalid metric ID** - The specified metric ID doesn't exist or isn't associated with the embed
</ResponseField>

<ResponseField name="INVALID_DATA_APP_API_KEY" type="string">
  **Missing or invalid data app** - Check your API key and data app configuration
</ResponseField>

<ResponseField name="EMBED_PARAM_ERROR" type="string">
  **Embed ID error** - The embed ID was not found or doesn't match the API key being used
</ResponseField>

<ResponseField name="METRIC_NOT_FOUND" type="string">
  **Metric not found** - The specified metric ID doesn't exist or isn't associated with the embed configuration
</ResponseField>

<ResponseField name="DATASOURCE_NAME_ERROR" type="string">
  **Invalid datasource name** - The specified datasource name could not be resolved for a multi-datasource workspace
</ResponseField>

<ResponseField name="DATAMART_NAME_ERROR" type="string">
  **Invalid datamart name** - The specified `dataMartName` could not be resolved for a multi-datamart workspace
</ResponseField>

## HTTP Status Code Summary

| Status Code | Description                                                             |
| ----------- | ----------------------------------------------------------------------- |
| `200`       | **OK** - Query executed successfully                                    |
| `400`       | **Bad Request** - Invalid request parameters or missing required fields |
| `401`       | **Unauthorized** - Invalid or expired API token                         |
| `404`       | **Not Found** - Embed ID or metric ID not found                         |
| `429`       | **Too Many Requests** - Rate limit exceeded                             |
| `500`       | **Internal Server Error** - Unexpected server error                     |

## Possible Errors

| Error Code                 | HTTP Status | Description                                |
| -------------------------- | ----------- | ------------------------------------------ |
| `INVALID_EMBED_ID`         | 400         | Embed ID not found                         |
| `INVALID_METRIC_ID`        | 400         | Invalid metric ID                          |
| `INVALID_DATA_APP_API_KEY` | 401         | Missing or invalid data app                |
| `EMBED_PARAM_ERROR`        | 404         | Embed ID error                             |
| `METRIC_NOT_FOUND`         | 404         | Metric not found                           |
| `DATASOURCE_NAME_ERROR`    | 400         | Invalid datasource name (multi-datasource) |
| `DATAMART_NAME_ERROR`      | 400         | Invalid datamart name (multi-datamart)     |
| `RATE_LIMIT_EXCEEDED`      | 429         | Too many requests                          |
| `INTERNAL_SERVER_ERROR`    | 500         | Unexpected failure                         |

## Filtering Guide

### Dashboard Filters

Dashboard filters apply to the entire dashboard context and affect all metrics. Common use cases include:

* **Date range filtering**: Limit data to specific time periods
* **Category filtering**: Filter by region, department, product line, etc.
* **Global parameters**: Set values that affect multiple metrics

```json Example theme={"dark"}
{
  "dashboardFilter": {
    "date_range": {
      "start": "2024-01-01",
      "end": "2024-03-31"
    },
    "region": "north-america",
    "product_category": "electronics"
  }
}
```

### Metric Filters

Metric filters apply specifically to the metric being queried and can be used for:

* **Row-level security (RLS)**: Restrict data based on client permissions
* **Additional filtering**: Apply metric-specific conditions
* **Client isolation**: Ensure multi-tenant data separation

```json Example theme={"dark"}
{
  "metricFilter": {
    "department": "sales",
    "status": "active",
    "client_group": "enterprise"
  }
}
```

## Use Cases

### Export Dashboard Data

```javascript theme={"dark"}
async function exportDashboardData(embedId, clientId) {
  // Get all metrics
  const metricsResponse = await fetch(
    `https://api.usedatabrain.com/api/v2/data-app/metrics?embedId=${embedId}&clientId=${clientId}`,
    {
      headers: { 'Authorization': 'Bearer dbn_live_...' }
    }
  );
  const { data: metrics } = await metricsResponse.json();
  
  // Query each metric
  const allData = {};
  for (const metric of metrics) {
    const queryResponse = await fetch(
      'https://api.usedatabrain.com/api/v2/data-app/query',
      {
        method: 'POST',
        headers: {
          'Authorization': 'Bearer dbn_live_...',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          embedId,
          metricId: metric.metricId,
          clientId
        })
      }
    );
    const queryResult = await queryResponse.json();
    allData[metric.name] = queryResult.data;
  }
  
  return allData;
}
```

### Real-time Data Refresh

```javascript theme={"dark"}
async function refreshMetricData(embedId, metricId, clientId, filters) {
  const response = await fetch(
    'https://api.usedatabrain.com/api/v2/data-app/query',
    {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer dbn_live_...',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        embedId,
        metricId,
        clientId,
        dashboardFilter: filters
      })
    }
  );
  
  return await response.json();
}

// Refresh every 5 minutes
setInterval(async () => {
  const data = await refreshMetricData(
    'embed_123',
    'metric_456',
    'user_789',
    { date_range: { start: 'today', end: 'today' } }
  );
  updateDashboard(data);
}, 5 * 60 * 1000);
```

### Multi-Tenant Data Access

```javascript theme={"dark"}
async function getClientMetricData(embedId, metricId, clientId) {
  // Apply client-specific filters automatically
  const response = await fetch(
    'https://api.usedatabrain.com/api/v2/data-app/query',
    {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer dbn_live_...',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        embedId,
        metricId,
        clientId,
        metricFilter: {
          // RLS ensures clients only see their data
          client_id: clientId
        }
      })
    }
  );
  
  return await response.json();
}
```

## Best Practices

1. **Cache responses** - Cache query results when appropriate to reduce API calls and improve performance
2. **Use filters efficiently** - Apply filters at the query level rather than filtering data client-side
3. **Handle pagination** - For large datasets, implement pagination or limit results
4. **Error handling** - Implement robust error handling and retry logic
5. **Rate limiting** - Respect rate limits and implement exponential backoff
6. **Security** - Never expose API keys in client-side code; proxy requests through your backend

## Performance Tips

* **Minimize filter complexity** - Complex filters can slow down queries
* **Request only needed columns** - If possible, select only required columns
* **Use date ranges** - Limit queries to specific time periods
* **Cache when possible** - Cache frequently accessed data
* **Batch requests** - When querying multiple metrics, consider batching requests

## Quick Start Guide

<Steps>
  <Step title="Get embed and metric IDs">
    First, get your embed ID and metric ID from your DataBrain dashboard or via the List APIs:

    ```bash theme={"dark"}
    # List your embeds to find the embedId
    curl --request GET \
      --url https://api.usedatabrain.com/api/v2/data-app/embeds \
      --header 'Authorization: Bearer dbn_live_abc123...'
    ```
  </Step>

  <Step title="Fetch available metrics">
    Use the [Fetch Metrics by Embed](/developer-docs/helpers/api-reference/fetch-metrics-by-embed-and-client) endpoint to get a list of available metrics:

    ```bash theme={"dark"}
    curl --request GET \
      --url 'https://api.usedatabrain.com/api/v2/data-app/metrics?embedId=embed_123&clientId=user_789' \
      --header 'Authorization: Bearer dbn_live_abc123...'
    ```
  </Step>

  <Step title="Make your first query">
    Query a metric with minimal parameters:

    ```bash theme={"dark"}
    curl --request POST \
      --url https://api.usedatabrain.com/api/v2/data-app/query \
      --header 'Authorization: Bearer dbn_live_abc123...' \
      --header 'Content-Type: application/json' \
      --data '{
        "embedId": "embed_123",
        "metricId": "metric_456", 
        "clientId": "user_789"
      }'
    ```
  </Step>

  <Step title="Add filters for specific data">
    Include filters to narrow down your results:

    ```bash theme={"dark"}
    curl --request POST \
      --url https://api.usedatabrain.com/api/v2/data-app/query \
      --header 'Authorization: Bearer dbn_live_abc123...' \
      --header 'Content-Type: application/json' \
      --data '{
        "embedId": "embed_123",
        "metricId": "metric_456",
        "clientId": "user_789",
        "dashboardFilter": {
          "date_range": {
            "start": "2024-01-01",
            "end": "2024-01-31"
          }
        }
      }'
    ```
  </Step>

  <Step title="Process the results">
    Use the returned data in your application:

    ```javascript theme={"dark"}
    const queryData = await queryMetric({
      embedId: 'embed_123',
      metricId: 'metric_456',
      clientId: 'user_789'
    });

    console.log(`Found ${queryData.totalRecords} records`);
    console.log(`Query took ${queryData.timeTaken}ms`);
    queryData.data.forEach(row => {
      // Process each data row
      console.log(row);
    });
    ```
  </Step>
</Steps>

## Next Steps

<CardGroup cols={2}>
  <Card title="Fetch Metrics by Embed" href="/developer-docs/helpers/api-reference/fetch-metrics-by-embed-and-client">
    Get a list of available metrics before querying
  </Card>

  <Card title="Fetch Dashboards by Data App" href="/developer-docs/helpers/api-reference/fetch-dashboards-by-datapp">
    Retrieve available dashboards in your data app
  </Card>

  <Card title="Embed a Pre-built Dashboard/Metric" href="/developer-docs/helpers/api-reference/create-embed">
    Set up embed configurations for your data app
  </Card>

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