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

# Publish/Unpublish Metric

> Publish or unpublish metrics in an embed configuration to control which metrics are visible to end users.

Control the visibility of metrics within an embed by publishing or unpublishing them. Published metrics are visible to end users, while unpublished metrics remain hidden but can be published later.

<Note>
  This endpoint allows you to dynamically control metric visibility without deleting metrics or modifying embed configurations. Useful for staged rollouts, A/B testing, or hiding metrics temporarily.
</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).

## 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 embed configuration ID where the metric is located.

  <Expandable title="Finding embed IDs">
    * Use the [List Embeds API](/developer-docs/helpers/api-reference/list-embed) to get all embed IDs
    * Check the response when creating an embed
    * Available in your data app embed configurations
  </Expandable>
</ParamField>

<ParamField body="metricId" type="string" required>
  The ID of the metric to publish or unpublish.

  <Expandable title="Finding metric IDs">
    * Use the [Fetch Metrics by Embed API](/developer-docs/helpers/api-reference/fetch-metrics-by-embed-and-client) to get metric IDs
    * Available in metric URLs in your dashboard
    * Returned when creating metrics via API
  </Expandable>
</ParamField>

<ParamField body="isPublished" type="boolean" required>
  Set the publication status of the metric.

  * `true`: Publish the metric (make it visible to end users)
  * `false`: Unpublish the metric (hide it from end users)

  <Expandable title="Publication behavior">
    - **Published metrics**: Visible in the embed, can be accessed by end users
    - **Unpublished metrics**: Hidden from the embed, but not deleted
    - **State preservation**: Metric configuration remains intact when unpublished
    - **Quick toggle**: Can be republished instantly without recreating
  </Expandable>
</ParamField>

## Response

<ResponseField name="id" type="string">
  The metric ID that was successfully updated on success.
</ResponseField>

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

  <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 - Publish Metric theme={"dark"}
    curl --request PUT \
      --url https://api.usedatabrain.com/api/v2/data-app/metrics/publish \
      --header 'Authorization: Bearer dbn_live_abc123...' \
      --header 'Content-Type: application/json' \
      --data '{
        "embedId": "embed_abc123",
        "metricId": "metric_xyz789",
        "isPublished": true
      }'
    ```

    ```bash cURL - Unpublish Metric theme={"dark"}
    curl --request PUT \
      --url https://api.usedatabrain.com/api/v2/data-app/metrics/publish \
      --header 'Authorization: Bearer dbn_live_abc123...' \
      --header 'Content-Type: application/json' \
      --data '{
        "embedId": "embed_abc123",
        "metricId": "metric_xyz789",
        "isPublished": false
      }'
    ```

    ```javascript Node.js - Publish Metric icon="fa-brands fa-node-js" theme={"dark"}
    const response = await fetch('https://api.usedatabrain.com/api/v2/data-app/metrics/publish', {
      method: 'PUT',
      headers: {
        'Authorization': 'Bearer dbn_live_abc123...',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        embedId: 'embed_abc123',
        metricId: 'metric_xyz789',
        isPublished: true
      })
    });

    const result = await response.json();
    console.log('Metric published:', result.id);
    ```

    ```javascript Node.js - Batch Publish icon="fa-brands fa-node-js" theme={"dark"}
    // Publish multiple metrics sequentially
    async function publishMetrics(embedId, metricIds, isPublished = true) {
      const results = [];
      
      for (const metricId of metricIds) {
        const response = await fetch(
          'https://api.usedatabrain.com/api/v2/data-app/metrics/publish',
          {
            method: 'PUT',
            headers: {
              'Authorization': 'Bearer dbn_live_abc123...',
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({ embedId, metricId, isPublished })
          }
        );
        
        const result = await response.json();
        results.push({ metricId, success: !result.error });
      }
      
      return results;
    }

    // Usage
    const metrics = ['metric_1', 'metric_2', 'metric_3'];
    const results = await publishMetrics('embed_abc123', metrics, true);
    console.log('Published metrics:', results);
    ```

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

    response = requests.put(
        'https://api.usedatabrain.com/api/v2/data-app/metrics/publish',
        headers={
            'Authorization': 'Bearer dbn_live_abc123...',
            'Content-Type': 'application/json'
        },
        json={
            'embedId': 'embed_abc123',
            'metricId': 'metric_xyz789',
            'isPublished': True
        }
    )

    result = response.json()

    if result.get('error'):
        print(f"Publish failed: {result['error']['message']}")
    else:
        print(f"Metric published: {result['id']}")
    ```

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

    def publish_metrics(embed_id, metric_ids, is_published=True):
        """Publish or unpublish multiple metrics"""
        results = []
        
        for metric_id in metric_ids:
            response = requests.put(
                'https://api.usedatabrain.com/api/v2/data-app/metrics/publish',
                headers={
                    'Authorization': 'Bearer dbn_live_abc123...',
                    'Content-Type': 'application/json'
                },
                json={
                    'embedId': embed_id,
                    'metricId': metric_id,
                    'isPublished': is_published
                }
            )
            
            result = response.json()
            results.append({
                'metricId': metric_id,
                'success': 'error' not in result
            })
        
        return results

    # Usage
    metrics = ['metric_1', 'metric_2', 'metric_3']
    results = publish_metrics('embed_abc123', metrics, True)
    print(f"Published {sum(r['success'] for r in results)} metrics")
    ```

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

    uri = URI('https://api.usedatabrain.com/api/v2/data-app/metrics/publish')
    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 = {
      embedId: 'embed_abc123',
      metricId: 'metric_xyz789',
      isPublished: true
    }.to_json

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

    if result['error']
      puts "Publish failed: #{result['error']['message']}"
    else
      puts "Metric published: #{result['id']}"
    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 PublishMetric {
        public static void main(String[] args) throws Exception {
            HttpClient client = HttpClient.newHttpClient();
            
            String requestBody = """
                {
                    "embedId": "embed_abc123",
                    "metricId": "metric_xyz789",
                    "isPublished": true
                }
                """;
            
            HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://api.usedatabrain.com/api/v2/data-app/metrics/publish"))
                .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 PublishMetricRequest struct {
        EmbedId     string `json:"embedId"`
        MetricId    string `json:"metricId"`
        IsPublished bool   `json:"isPublished"`
    }

    func main() {
        reqData := PublishMetricRequest{
            EmbedId:     "embed_abc123",
            MetricId:    "metric_xyz789",
            IsPublished: true,
        }
        
        jsonData, _ := json.Marshal(reqData)
        
        req, _ := http.NewRequest("PUT", 
            "https://api.usedatabrain.com/api/v2/data-app/metrics/publish", 
            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("Metric published successfully")
    }
    ```

    ```php PHP icon="fa-brands fa-php" theme={"dark"}
    <?php
    $url = 'https://api.usedatabrain.com/api/v2/data-app/metrics/publish';
    $data = [
        'embedId' => 'embed_abc123',
        'metricId' => 'metric_xyz789',
        'isPublished' => true
    ];

    $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 "Publish failed: " . $result['error']['message'];
    } else {
        echo "Metric published: " . $result['id'];
    }
    ?>
    ```
  </RequestExample>

  <ResponseExample>
    ```json 200 - Success theme={"dark"}
    {
      "id": "metric_xyz789"
    }
    ```

    ```json 400 - Validation Error theme={"dark"}
    {
      "error": {
        "code": "INVALID_REQUEST_BODY",
        "message": "\"embedId\" 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 - Invalid Metric or Embed theme={"dark"}
    {
      "error": {
        "code": "INVALID_METRIC_ID",
        "message": "Invalid metric id or embed id"
      }
    }
    ```

    ```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** - Metric publication status updated              |
| `400`       | **Bad Request** - Invalid request parameters            |
| `401`       | **Unauthorized** - Invalid or missing API key           |
| `500`       | **Internal Server Error** - Server error or invalid IDs |

## Possible Errors

| Error Code                 | HTTP Status | Description                   |
| -------------------------- | ----------- | ----------------------------- |
| `INVALID_REQUEST_BODY`     | 400         | Missing or invalid parameters |
| `INVALID_DATA_APP_API_KEY` | 401         | Invalid API key               |
| `INVALID_METRIC_ID`        | 500         | Invalid metric or embed ID    |
| `INTERNAL_SERVER_ERROR`    | 500         | Server error                  |
