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

# Get Semantic Layer

> Retrieve the semantic layer configuration for a datamart, including table descriptions, column metadata, and completion score.

Retrieve the full semantic layer for a given datamart. The response includes table and column metadata (descriptions, synonyms, column types), feedback text, a completion score, and the last-updated timestamp.

<Note>
  This endpoint returns data for datamarts that exist in your organization — even if no semantic layer has been configured yet. In that case, tables are returned with `null`/empty semantic fields.
</Note>

## Authentication

This endpoint requires a **service token** in the Authorization header. Data app API tokens are not permitted and will be rejected with a `403` error.

To access your service token:

1. Go to your Databrain dashboard and open **Settings**.
2. Navigate to **Settings**.
3. Find the **Service Tokens** section.
4. Click the **"Generate Token"** button to generate 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>

## Query Parameters

<ParamField query="datamartName" type="string" required>
  The name of the datamart whose semantic layer you want to retrieve. Must match an existing datamart in your organization.

  <Expandable title="Finding datamart names">
    * Use the [List Datamarts API](/developer-docs/helpers/api-reference/list-datamarts) to get all datamart names
    * Names are case-sensitive and must match exactly
  </Expandable>
</ParamField>

## Response

<ResponseField name="data" type="object">
  The semantic layer data for the requested datamart.

  <Expandable title="data properties">
    <ResponseField name="data.datamartName" type="string">
      Name of the datamart.
    </ResponseField>

    <ResponseField name="data.tables" type="array">
      Array of table objects with semantic metadata.

      <Expandable title="table properties">
        <ResponseField name="name" type="string">
          Table name from the datasource.
        </ResponseField>

        <ResponseField name="schemaName" type="string | null">
          Schema name, or `null` if not set.
        </ResponseField>

        <ResponseField name="description" type="string | null">
          Human-readable description of the table.
        </ResponseField>

        <ResponseField name="synonyms" type="string[]">
          Alternative names for the table. Empty array if none set.
        </ResponseField>

        <ResponseField name="miscellaneousInfo" type="string | null">
          Additional context for AI query generation.
        </ResponseField>

        <ResponseField name="columns" type="array">
          Array of column objects with semantic metadata.

          <Expandable title="column properties">
            <ResponseField name="name" type="string">
              Column name from the datasource.
            </ResponseField>

            <ResponseField name="datatype" type="string | null">
              The underlying SQL datatype of the column.
            </ResponseField>

            <ResponseField name="description" type="string | null">
              Human-readable description of the column.
            </ResponseField>

            <ResponseField name="synonyms" type="string[]">
              Alternative names for the column.
            </ResponseField>

            <ResponseField name="miscellaneousInfo" type="string | null">
              Additional context for AI query generation.
            </ResponseField>

            <ResponseField name="columnType" type="string | null">
              Semantic column type. One of: `String`, `Long String`, `String (Custom)`, `ENUM`, `Mapper`, `Range`, `Expression`, `Identifier`, `Number`, `JSON`.
            </ResponseField>

            <ResponseField name="columnTypeConfig" type="object | string | null">
              Stored column-type configuration as saved via the API (object maps for ENUM-like types, `{ lowerLimit, upperLimit }` for Range, strings for Expression/JSON, or `null`).
            </ResponseField>

            <ResponseField name="isIdentifier" type="boolean">
              Whether this column is marked as an identifier.
            </ResponseField>

            <ResponseField name="isNotIndexed" type="boolean">
              Whether this column is excluded from AI indexing.
            </ResponseField>
          </Expandable>
        </ResponseField>
      </Expandable>
    </ResponseField>

    <ResponseField name="data.feedback" type="string | null">
      Global feedback text providing context to the AI about this datamart.
    </ResponseField>

    <ResponseField name="data.completionScore" type="number">
      A score from 0 to 100 indicating how thoroughly the semantic layer is configured.
    </ResponseField>

    <ResponseField name="data.lastUpdated" type="string | null">
      ISO 8601 timestamp of the last semantic layer update, or `null` if never updated.
    </ResponseField>
  </Expandable>
</ResponseField>

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

## Examples

<Panel>
  <RequestExample>
    ```bash cURL theme={"dark"}
    curl --request GET \
      --url 'https://api.usedatabrain.com/api/v2/data-app/datamarts/semantic-layer?datamartName=sales-analytics' \
      --header 'Authorization: Bearer dbn_live_abc123...'
    ```

    ```javascript Node.js icon="fa-brands fa-node-js" theme={"dark"}
    const datamartName = 'sales-analytics';
    const response = await fetch(
      `https://api.usedatabrain.com/api/v2/data-app/datamarts/semantic-layer?datamartName=${encodeURIComponent(datamartName)}`,
      {
        method: 'GET',
        headers: {
          'Authorization': 'Bearer dbn_live_abc123...'
        }
      }
    );

    const result = await response.json();
    console.log('Tables:', result.data.tables.length);
    console.log('Completion:', result.data.completionScore);
    ```

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

    response = requests.get(
        'https://api.usedatabrain.com/api/v2/data-app/datamarts/semantic-layer',
        headers={
            'Authorization': 'Bearer dbn_live_abc123...'
        },
        params={
            'datamartName': 'sales-analytics'
        }
    )

    result = response.json()
    print(f"Tables: {len(result['data']['tables'])}")
    print(f"Completion: {result['data']['completionScore']}%")
    ```

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

    uri = URI('https://api.usedatabrain.com/api/v2/data-app/datamarts/semantic-layer')
    params = { datamartName: 'sales-analytics' }
    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)
    result = JSON.parse(response.body)
    puts "Tables: #{result['data']['tables'].length}"
    ```

    ```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 java.net.URLEncoder;
    import java.nio.charset.StandardCharsets;

    public class GetSemanticLayer {
        public static void main(String[] args) throws Exception {
            HttpClient client = HttpClient.newHttpClient();

            String datamartName = URLEncoder.encode("sales-analytics", StandardCharsets.UTF_8);
            String url = String.format(
                "https://api.usedatabrain.com/api/v2/data-app/datamarts/semantic-layer?datamartName=%s",
                datamartName
            );

            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.body());
        }
    }
    ```

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

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

    func main() {
        baseURL := "https://api.usedatabrain.com/api/v2/data-app/datamarts/semantic-layer"
        params := url.Values{}
        params.Add("datamartName", "sales-analytics")

        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, _ := client.Do(req)
        defer resp.Body.Close()

        var result map[string]interface{}
        json.NewDecoder(resp.Body).Decode(&result)
        fmt.Printf("Response: %v\n", result)
    }
    ```

    ```php PHP icon="fa-brands fa-php" theme={"dark"}
    <?php
    $params = http_build_query([
        'datamartName' => 'sales-analytics'
    ]);

    $url = 'https://api.usedatabrain.com/api/v2/data-app/datamarts/semantic-layer?' . $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 "Tables: " . count($response['data']['tables']);
    ?>
    ```
  </RequestExample>

  <ResponseExample>
    ```json 200 - Success theme={"dark"}
    {
      "data": {
        "datamartName": "sales-analytics",
        "tables": [
          {
            "name": "orders",
            "schemaName": "public",
            "description": "Customer purchase orders",
            "synonyms": ["purchases", "transactions"],
            "miscellaneousInfo": null,
            "columns": [
              {
                "name": "order_id",
                "datatype": "integer",
                "description": "Unique order identifier",
                "synonyms": ["id", "order number"],
                "miscellaneousInfo": null,
                "columnType": "Identifier",
                "columnTypeConfig": null,
                "isIdentifier": true,
                "isNotIndexed": false
              },
              {
                "name": "status",
                "datatype": "varchar",
                "description": "Current order status",
                "synonyms": ["order status", "state"],
                "miscellaneousInfo": null,
                "columnType": "ENUM",
                "columnTypeConfig": null,
                "isIdentifier": false,
                "isNotIndexed": false
              },
              {
                "name": "amount",
                "datatype": "numeric",
                "description": "Total order amount in USD",
                "synonyms": ["total", "price"],
                "miscellaneousInfo": null,
                "columnType": "Number",
                "columnTypeConfig": null,
                "isIdentifier": false,
                "isNotIndexed": false
              }
            ]
          }
        ],
        "feedback": "This datamart covers e-commerce sales data. Amounts are in USD.",
        "completionScore": 75,
        "lastUpdated": "2026-03-15T10:30:00.000Z"
      }
    }
    ```

    ```json 200 - No Semantic Data theme={"dark"}
    {
      "data": {
        "datamartName": "raw-datamart",
        "tables": [
          {
            "name": "events",
            "schemaName": "public",
            "description": null,
            "synonyms": [],
            "miscellaneousInfo": null,
            "columns": [
              {
                "name": "event_id",
                "datatype": "integer",
                "description": null,
                "synonyms": [],
                "miscellaneousInfo": null,
                "columnType": null,
                "columnTypeConfig": null,
                "isIdentifier": false,
                "isNotIndexed": false
              }
            ]
          }
        ],
        "feedback": null,
        "completionScore": 0,
        "lastUpdated": null
      }
    }
    ```

    ```json 400 - Missing datamartName theme={"dark"}
    {
      "error": {
        "code": "INVALID_DATAMART",
        "message": "datamartName query parameter is required"
      }
    }
    ```

    ```json 400 - Datamart Not Found theme={"dark"}
    {
      "error": {
        "code": "INVALID_DATAMART",
        "message": "Datamart 'nonexistent' not found"
      }
    }
    ```

    ```json 403 - Data App Token theme={"dark"}
    {
      "error": {
        "code": "AUTHENTICATION_ERROR",
        "message": "Semantic Layer API requires a service token, not a data app API token"
      }
    }
    ```
  </ResponseExample>
</Panel>

## HTTP Status Code Summary

| Status Code | Description                                                  |
| ----------- | ------------------------------------------------------------ |
| `200`       | **OK** — Semantic layer retrieved successfully               |
| `400`       | **Bad Request** — Missing or invalid datamartName            |
| `401`       | **Unauthorized** — Invalid or missing API token              |
| `403`       | **Forbidden** — Data app token used instead of service token |
| `500`       | **Internal Server Error** — Server error occurred            |

## Possible Errors

| Error Code              | HTTP Status | Description                                       |
| ----------------------- | ----------- | ------------------------------------------------- |
| `INVALID_DATAMART`      | 400         | datamartName is missing or datamart doesn't exist |
| `AUTHENTICATION_ERROR`  | 403         | Data app token used instead of service token      |
| `INTERNAL_SERVER_ERROR` | 500         | Server error                                      |

## Next Steps

<CardGroup cols={2}>
  <Card title="Create Semantic Layer" icon="plus" href="/developer-docs/helpers/api-reference/create-semantic-layer">
    Add semantic metadata to your datamart
  </Card>

  <Card title="Update Semantic Layer" icon="pen" href="/developer-docs/helpers/api-reference/update-semantic-layer">
    Modify existing semantic layer metadata
  </Card>

  <Card title="Semantic Layer Guide" icon="book" href="/guides/datasources/semantic-layer">
    Learn how to configure the semantic layer in the UI
  </Card>

  <Card title="List Datamarts" icon="list" href="/developer-docs/helpers/api-reference/list-datamarts">
    Find datamart names in your organization
  </Card>
</CardGroup>
