### Install SigNoz with Docker Compose Source: https://docs.usedatabrain.com/guides/signoz-integration Quick start guide to clone the SigNoz repository and start the services using Docker Compose. ```bash # Clone SigNoz repository git clone -b main https://github.com/SigNoz/signoz.git cd signoz/deploy/ # Start SigNoz docker compose -f docker/clickhouse-setup/docker-compose.yaml up -d ``` -------------------------------- ### GET Response Example Source: https://docs.usedatabrain.com/developer-docs/helpers/api-reference/whitelist-domains Example JSON response when successfully retrieving whitelisted domains. An empty array is returned if no domains are currently set. ```json { "data": ["app.example.com", "*.customer.com", "localhost:3000"] } ``` -------------------------------- ### Create Guest Token (Java) Source: https://docs.usedatabrain.com/developer-docs/helpers/api-reference/token Illustrates how to create a guest token in Java using the standard HttpClient. This example requires additional setup for JSON serialization and HTTP request handling. ```java 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.List; ``` -------------------------------- ### Node.js - List All Workspaces Source: https://docs.usedatabrain.com/developer-docs/helpers/api-reference/list-workspaces Retrieve all workspaces using Node.js. This example demonstrates how to make a GET request and parse the JSON response. Remember to use your valid API key. ```javascript const response = await fetch('https://api.usedatabrain.com/api/v2/workspace', { method: 'GET', headers: { 'Authorization': 'Bearer dbn_live_abc123...' } }); const result = await response.json(); console.log(result.data); // Array of all workspaces ``` -------------------------------- ### Fetch Dashboards with Ruby Source: https://docs.usedatabrain.com/developer-docs/helpers/api-reference/fetch-dashboards-by-datapp This Ruby example uses the `net/http` library to make a GET request for dashboards. It demonstrates setting the Authorization header and query parameters for filtering and pagination. ```ruby require 'net/http' require 'json' uri = URI('https://api.usedatabrain.com/api/v2/data-app/dashboards') params = { isPagination: 'true', pageNumber: '1', dashboardNames: 'Sales Dashboard,Marketing 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) data = JSON.parse(response.body) puts "Dashboards: #{data['data']}" ``` -------------------------------- ### Migrate POST Request to GET Request Source: https://docs.usedatabrain.com/developer-docs/helpers/api-reference/fetch-dashboards-by-datapp Example demonstrating the migration from a POST request with a complex body to a GET request using query parameters for fetching a specific dashboard. ```javascript const response = await fetch('https://api.usedatabrain.com/api/v2/data-app/dashboards', { method: 'POST', headers: { 'Authorization': 'Bearer dbn_live_...', 'Content-Type': 'application/json' }, body: JSON.stringify({ isPagination: true, pageNumber: 1, filters: { dashboardNames: ['Sales Dashboard'] } }) }); ``` ```javascript const params = new URLSearchParams({ isPagination: 'true', pageNumber: '1', dashboardNames: 'Sales Dashboard' }); const response = await fetch(`https://api.usedatabrain.com/api/v2/data-app/dashboards?${params}`, { method: 'GET', headers: { 'Authorization': 'Bearer dbn_live_...' } }); ``` -------------------------------- ### Run Development Server Source: https://docs.usedatabrain.com/developer-docs/quick-start/embedding-tutorial Start your local development server to view the embedded dashboard. Use 'npm run dev' or 'npm start'. ```bash npm run dev # or npm start ``` -------------------------------- ### Authentication Example Source: https://docs.usedatabrain.com/developer-docs/helpers/api-reference/delete-datamart Example using curl to demonstrate how to authenticate your request to delete a datamart using a service token in the Authorization header. ```bash curl --request DELETE \ --url 'https://api.usedatabrain.com/api/v2/data-app/datamart?datamartName=sales-analytics' \ --header 'Authorization: Bearer dbn_live_abc123...' ``` -------------------------------- ### Example cURL Request with Authentication Source: https://docs.usedatabrain.com/developer-docs/helpers/api-reference/list-embed This example demonstrates how to authenticate your API requests using an API key in the Authorization header. It also shows how to include pagination parameters. ```bash curl --request GET \ --url 'https://api.usedatabrain.com/api/v2/data-app/embeds?isPagination=true&pageNumber=1' \ --header 'Authorization: Bearer dbn_live_abc123...' ``` -------------------------------- ### Install Databrain Plugin for Solid.js Source: https://docs.usedatabrain.com/developer-docs/framework-specific-guide/solid Use npm to install the Databrain plugin. This command should be run in your project's root directory. ```bash npm install @databrainhq/plugin ``` -------------------------------- ### Main Server Setup Source: https://docs.usedatabrain.com/developer-docs/helpers/api-reference/proxy-authentication Sets up the HTTP server to listen on port 3000 and handle requests to the /proxy-auth endpoint using the proxyHandler. ```Go func main() { http.HandleFunc("/proxy-auth/", proxyHandler) log.Println("Proxy server running on port 3000") log.Fatal(http.ListenAndServe(":3000", nil)) } ``` -------------------------------- ### Enable GET Method Pagination Source: https://docs.usedatabrain.com/developer-docs/helpers/api-reference/fetch-dashboards-by-datapp Use this query parameter to enable pagination when fetching dashboards via GET. Start with pageNumber=1. ```http GET /api/v2/data-app/dashboards?isPagination=true&pageNumber=1 ``` -------------------------------- ### Create Guest Token (Go) Source: https://docs.usedatabrain.com/developer-docs/helpers/api-reference/token Example of creating a guest token using Go's standard http library. ```go package main import ( "bytes" "encoding/json" "net/http" ) type RLSValue struct { CustomerID string `json:"customer_id"` Region string `json:"region"` } type RLSSetting struct { MetricID string `json:"metricId"` Values RLSValue `json:"values"` } type Params struct { RLSSettings []RLSSetting `json:"rlsSettings"` } type RequestBody struct { ClientID string `json:"clientId"` DataAppName string `json:"dataAppName"` Params Params `json:"params"` ExpiryTime int `json:"expiryTime"` } func main() { requestBody := RequestBody{ ClientID: "user-456", DataAppName: "sales-dashboard", Params: Params{ RLSSettings: []RLSSetting{ { MetricID: "metric_123", Values: RLSValue{ CustomerID: "456", Region: "north-america", }, }, }, }, ExpiryTime: 3600000, } jsonData, _ := json.Marshal(requestBody) req, _ := http.NewRequest("POST", "https://api.usedatabrain.com/api/v2/guest-token/create", 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() } ``` -------------------------------- ### Get Datamarts with Pagination Source: https://docs.usedatabrain.com/developer-docs/helpers/api-reference/list-datamarts Retrieve datamarts with pagination enabled. Specify the page number to get a specific set of results. This example fetches the first page. ```javascript // Get first page of datamarts const datamarts = await listDatamarts({ isPagination: true, pageNumber: 1 }); console.log(`Page 1 datamarts: ${datamarts.data.length}`); ``` -------------------------------- ### Create Workspace in Go Source: https://docs.usedatabrain.com/developer-docs/helpers/api-reference/create-workspace This Go program demonstrates how to create a workspace by making an HTTP POST request. It includes setting up the request body and headers. ```go package main import ( "bytes" "encoding/json" "fmt" "net/http" ) type WorkspaceRequest struct { Name string `json:"name"` ConnectionType string `json:"connectionType"` DatasourceName string `json:"datasourceName,omitempty"` DatamartName string `json:"datamartName,omitempty"` } func main() { reqData := WorkspaceRequest{ Name: "Sales Analytics", ConnectionType: "DATASOURCE", DatasourceName: "postgres-main", } jsonData, _ := json.Marshal(reqData) req, _ := http.NewRequest("POST", "https://api.usedatabrain.com/api/v2/workspace", 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("Workspace created successfully") } ``` -------------------------------- ### List Workspaces with Pagination in Go Source: https://docs.usedatabrain.com/developer-docs/helpers/api-reference/list-workspaces This Go example demonstrates how to fetch all workspaces, handling pagination automatically. It iterates through pages until no more workspaces are returned. ```go package main import ( "encoding/json" "fmt" "io" "net/http" ) type WorkspaceResponse struct { Data []Workspace `json:"data"` Error interface{} `json:"error"` } type Workspace struct { Name string `json:"name"` } func fetchAllWorkspaces(apiKey string) ([]Workspace, error) { var allWorkspaces []Workspace pageNumber := 1 for { url := fmt.Sprintf( "https://api.usedatabrain.com/api/v2/workspace?isPagination=true&pageNumber=%d", pageNumber, ) req, _ := http.NewRequest("GET", url, nil) req.Header.Set("Authorization", "Bearer "+apiKey) client := &http.Client{} resp, err := client.Do(req) if err != nil { return nil, err } body, _ := io.ReadAll(resp.Body) resp.Body.Close() var result WorkspaceResponse json.Unmarshal(body, &result) if len(result.Data) == 0 { break } allWorkspaces = append(allWorkspaces, result.Data...) pageNumber++ } return allWorkspaces, nil } func main() { workspaces, _ := fetchAllWorkspaces("dbn_live_abc123...") fmt.Printf("Total workspaces: %d\n", len(workspaces)) } ``` -------------------------------- ### Fetch Metrics API Request Example Source: https://docs.usedatabrain.com/developer-docs/helpers/api-reference/fetch-metrics-by-embed-and-client This example demonstrates how to make a GET request to the /api/v2/data-app/metrics endpoint using curl. Ensure your API key is included in the Authorization header. ```bash curl --request GET \ --url https://api.usedatabrain.com/api/v2/data-app/metrics \ --header 'Authorization: Bearer dbn_live...' ``` -------------------------------- ### Create Dashboard Request (Go) Source: https://docs.usedatabrain.com/developer-docs/helpers/api-reference/cloud-databrain-endpoint Example of how to make a POST request to create a dashboard in a workspace using Go. Ensure you set the Authorization and Content-Type headers. ```go func main() { reqData := DashboardRequest{ WorkspaceName: "my-workspace", IsPagination: true, PageNumber: 1, } jsonData, _ := json.Marshal(reqData) req, _ := http.NewRequest("POST", "https://api.usedatabrain.com/api/v2/workspace/dashboards", 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)) } ``` -------------------------------- ### Create Guest Token (Ruby) Source: https://docs.usedatabrain.com/developer-docs/helpers/api-reference/token Example of creating a guest token using Ruby's Net::HTTP library. ```ruby require 'net/http' require 'json' uri = URI('https://api.usedatabrain.com/api/v2/guest-token/create') 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 = { clientId: 'user-456', dataAppName: 'sales-dashboard', params: { rlsSettings: [ { metricId: 'metric_123', values: { customer_id: '456', region: 'north-america' } } ] }, expiryTime: 3600000 }.to_json response = http.request(request) ``` -------------------------------- ### Get Semantic Layer using Ruby Source: https://docs.usedatabrain.com/developer-docs/helpers/api-reference/get-semantic-layer This Ruby example demonstrates how to fetch the semantic layer using the `net/http` library. Ensure your API token is correctly provided in the Authorization header. ```ruby 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}" ``` -------------------------------- ### Create Data App using Go Source: https://docs.usedatabrain.com/developer-docs/helpers/api-reference/create-data-app This Go program shows how to create a Data App by making an HTTP POST request. It includes defining request structures, marshaling JSON, and setting necessary headers. ```go package main import ( "bytes" "encoding/json" "fmt" "net/http" ) type CreateDataAppRequest struct { Name string `json:"name"` } type CreateDataAppResponse struct { Name string `json:"name"` Error interface{} `json:"error"` } func main() { requestBody := CreateDataAppRequest{ Name: "Customer Portal Analytics", } jsonData, _ := json.Marshal(requestBody) req, _ := http.NewRequest("POST", "https://api.usedatabrain.com/api/v2/data-app", bytes.NewBuffer(jsonData)) req.Header.Set("Authorization", "Bearer service_token_xyz...") req.Header.Set("Content-Type", "application/json") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() var result CreateDataAppResponse json.NewDecoder(resp.Body).Decode(&result) fmt.Printf("Created Data App: %s\n", result.Name) } ``` -------------------------------- ### Fetch Metric Data using Java (Setup) Source: https://docs.usedatabrain.com/developer-docs/helpers/api-reference/fetch-metric-data-by-dataapp This Java snippet provides the necessary imports for making HTTP requests and handling JSON responses to interact with the Data App API. Further implementation details would follow. ```java 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; ``` -------------------------------- ### Get Semantic Layer using Node.js Source: https://docs.usedatabrain.com/developer-docs/helpers/api-reference/get-semantic-layer Fetch the semantic layer data using Node.js. This example demonstrates how to construct the request and parse the JSON response. Remember to use your valid API token. ```javascript 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); ``` -------------------------------- ### List Schedule Reports (Ruby) Source: https://docs.usedatabrain.com/developer-docs/helpers/api-reference/list-schedule-reports-by-embed This Ruby example shows how to make a GET request to list scheduled reports using the Net::HTTP library. It constructs the URL with query parameters and sets the Authorization header. ```ruby require 'net/http' require 'json' uri = URI('https://api.usedatabrain.com/api/v2/data-app/embeds/reports') params = { embedId: 'embed_abc123', clientId: 'client_xyz789', isPagination: 'true', pageNumber: '1' } 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 "Scheduled reports: #{data['data']}" ``` -------------------------------- ### Create Guest Token (Java) Source: https://docs.usedatabrain.com/developer-docs/helpers/api-reference/token Example of creating a guest token using Java's HttpClient and ObjectMapper. ```java HttpClient client = HttpClient.newHttpClient(); ObjectMapper mapper = new ObjectMapper(); Map requestBody = Map.of( "clientId", "user-456", "dataAppName", "sales-dashboard", "params", Map.of( "rlsSettings", List.of( Map.of( "metricId", "metric_123", "values", Map.of( "customer_id", "456", "region", "north-america" ) ) ) ), "expiryTime", 3600000 ); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.usedatabrain.com/api/v2/guest-token/create")) .header("Authorization", "Bearer dbn_live_abc123...") .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(mapper.writeValueAsString(requestBody))) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` -------------------------------- ### Install and Run Databrain MCP Server Source: https://docs.usedatabrain.com/changelog/product-changelog Use this command to set up the Databrain MCP Server. It helps manage embedded analytics through your AI assistant. ```bash npx @databrainhq/mcp-server ``` -------------------------------- ### Get Semantic Layer using Java Source: https://docs.usedatabrain.com/developer-docs/helpers/api-reference/get-semantic-layer Example of retrieving the semantic layer using Java's built-in `HttpClient`. This code snippet includes necessary imports and demonstrates how to set up the request with the API token. ```java 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 response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.body()); } } ``` -------------------------------- ### List Data Apps Request Example Source: https://docs.usedatabrain.com/developer-docs/helpers/api-reference/list-data-apps Use this Ruby code to make a GET request to the Data App API to retrieve a list of data apps. Ensure you replace 'service_token_xyz...' with your actual service token. ```ruby uri = URI('https://api.usedatabrain.com/api/v2/data-app') params = { isPagination: 'true', pageNumber: '1' } 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 service_token_xyz...' response = http.request(request) result = JSON.parse(response.body) puts "Found Data Apps: #{result['data'].length}" result['data'].each do |app| puts "- #{app['name']} (#{app['embedCount']} embeds)" end ``` -------------------------------- ### Create Guest Token (Python) Source: https://docs.usedatabrain.com/developer-docs/helpers/api-reference/token A Python example using the requests library to create a guest token. Demonstrates the inclusion of advanced parameters like rlsSettings and expiryTime. ```python import requests response = requests.post( 'https://api.usedatabrain.com/api/v2/guest-token/create', headers={ 'Authorization': 'Bearer dbn_live_abc123...', 'Content-Type': 'application/json' }, json={ 'clientId': 'user-456', 'dataAppName': 'sales-dashboard', 'params': { 'rlsSettings': [ { 'metricId': 'metric_123', 'values': { 'customer_id': '456', 'region': 'north-america' } } ] }, 'expiryTime': 3600000 } ) ``` -------------------------------- ### Create API Token using Go Source: https://docs.usedatabrain.com/developer-docs/helpers/api-reference/create-api-token This Go program illustrates creating an API token. It's essential to keep the generated API key confidential and store it securely. ```go package main import ( "bytes" "encoding/json" "fmt" "net/http" ) type CreateApiTokenRequest struct { DataAppName string `json:"dataAppName"` Name string `json:"name"` } type CreateApiTokenResponse struct { Key string `json:"key"` Error interface{} `json:"error"` } func main() { requestBody := CreateApiTokenRequest{ DataAppName: "Customer Portal Analytics", Name: "Production API Key", } jsonData, _ := json.Marshal(requestBody) req, _ := http.NewRequest("POST", "https://api.usedatabrain.com/api/v2/data-app/api-tokens", bytes.NewBuffer(jsonData)) req.Header.Set("Authorization", "Bearer service_token_xyz...") req.Header.Set("Content-Type", "application/json") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() var result CreateApiTokenResponse json.NewDecoder(resp.Body).Decode(&result) fmt.Printf("New API Key: %s\n", result.Key) // Store this key securely! } ``` -------------------------------- ### List Data Apps (Java) Source: https://docs.usedatabrain.com/developer-docs/helpers/api-reference/list-data-apps This Java example uses the built-in HttpClient to make a GET request to the Data App API. It includes pagination parameters and prints the raw response body. Remember to replace the placeholder token. ```java import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.net.URI; public class ListDataApps { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); String url = "https://api.usedatabrain.com/api/v2/data-app" + "?isPagination=true&pageNumber=1"; HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(url)) .header("Authorization", "Bearer service_token_xyz...") .GET() .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println("Response: " + response.body()); } } ``` -------------------------------- ### List Data Apps (Node.js) Source: https://docs.usedatabrain.com/developer-docs/helpers/api-reference/list-data-apps This Node.js example shows how to make a GET request to the Data App API to retrieve a list of data apps and log their names and embed counts. It uses the Fetch API and requires a valid service token. ```javascript const response = await fetch('https://api.usedatabrain.com/api/v2/data-app', { method: 'GET', headers: { 'Authorization': 'Bearer service_token_xyz...' } }); const data = await response.json(); console.log('Found Data Apps:', data.data.length); data.data.forEach(app => { console.log(`- ${app.name} (${app.embedCount} embeds)`); }); ``` -------------------------------- ### List Datamarts (Java) Source: https://docs.usedatabrain.com/developer-docs/helpers/api-reference/list-datamarts This Java example uses `java.net.http.HttpClient` to fetch datamarts. It shows how to set the request URI and authorization header. ```java import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.net.URI; public class DataBrainDatamartAPI { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); String url = "https://api.usedatabrain.com/api/v2/data-app/datamarts?isPagination=true&pageNumber=1"; HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(url)) .header("Authorization", "Bearer dbn_live_abc123...") .GET() .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println("Response: " + response.body()); } } ``` -------------------------------- ### Filter Dashboards by Name (JSON Example) Source: https://docs.usedatabrain.com/developer-docs/helpers/api-reference/fetch-dashboards-by-datapp Example of a JSON array used to filter dashboards by their names. This is a configuration example for the `filters.dashboardNames` parameter. ```json ["Sales Dashboard", "Marketing Analytics", "Customer Insights"] ``` -------------------------------- ### Create Workspace with Datamart Connection Source: https://docs.usedatabrain.com/developer-docs/helpers/api-reference/create-workspace This cURL example demonstrates creating a workspace linked to a datamart. ```bash curl --request POST \ --url https://api.usedatabrain.com/api/v2/workspace \ --header 'Authorization: Bearer dbn_live_abc123...' \ --header 'Content-Type: application/json' \ --data '{ \ "name": "Customer Insights", \ "connectionType": "DATAMART", \ "datamartName": "customer-data-mart" \ }' ``` -------------------------------- ### Success Response Example Source: https://docs.usedatabrain.com/developer-docs/helpers/api-reference/delete-datasource This is an example of a successful response when a datasource is deleted. ```json { "id": "uuid-of-deleted-datasource", "message": "Datasource deleted successfully" } ``` -------------------------------- ### Fetch Dashboards using POST (Java - Incomplete) Source: https://docs.usedatabrain.com/developer-docs/helpers/api-reference/fetch-dashboards-by-datapp This is an incomplete Java example for fetching dashboards using the legacy POST method. It sets up the HTTP client and request but lacks the body construction and response handling. ```java 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; import java.util.List; import java.util.Arrays; ``` -------------------------------- ### Snowflake Credentials Example Source: https://docs.usedatabrain.com/developer-docs/helpers/api-reference/create-datasource Example of credential fields required for a Snowflake datasource. ```json { "host": "your-account.snowflakecomputing.com", "username": "your_username", "role": "your_role" } ``` -------------------------------- ### Authorization Header Example Source: https://docs.usedatabrain.com/developer-docs/helpers/api-reference/import-dashboard Example of the Authorization header format using a service token. ```text Authorization: Bearer dbn_live_... ``` -------------------------------- ### Create Guest Token (Simple) Source: https://docs.usedatabrain.com/developer-docs/token Example of creating a guest token using cURL. ```APIDOC ## Create Guest Token (Simple) ### Description This example demonstrates how to create a guest token using a cURL command. It includes the necessary headers and a basic JSON payload. ### Method POST ### Endpoint `https://api.usedatabrain.com/api/v2/guest-token/create` ### Request Example ```bash curl --request POST \ --url https://api.usedatabrain.com/api/v2/guest-token/create \ --header 'Authorization: Bearer dbn_live_abc123...' \ --header 'Content-Type: application/json' \ --data '{ \ "clientId": "user-456", \ "dataAppName": "sales-dashboard" \ }' ``` ``` -------------------------------- ### Fetch Metrics Request Example (PHP) Source: https://docs.usedatabrain.com/developer-docs/helpers/api-reference/fetch-metrics-by-embed-and-client This PHP snippet demonstrates how to make a request to fetch metrics. It includes setting up stream context options and handling the JSON response. ```php ``` ``` -------------------------------- ### API Response Examples Source: https://docs.usedatabrain.com/developer-docs/helpers/api-reference/create-api-token These examples show the structure of successful and error responses when creating an API token. ```json { "key": "550e8400-e29b-41d4-a716-446655440000" } ``` ```json { "error": { "code": "INVALID_REQUEST_BODY", "message": "\"dataAppName\" is required" } } ``` ```json { "error": { "code": "DATA_APP_NOT_FOUND", "message": "Data app not found" } } ``` ```json { "error": { "code": "AUTHENTICATION_ERROR", "message": "Invalid Service Token" } } ``` ```json { "error": { "code": "INTERNAL_SERVER_ERROR", "message": "INTERNAL_SERVER_ERROR" } } ``` -------------------------------- ### Complete Request Body Example Source: https://docs.usedatabrain.com/developer-docs/helpers/api-reference/token An example of a complete request body demonstrating various filter types and configurations. ```APIDOC ## Request Body ### Complete Example ```json theme={"dark"} { "dashboardId": "dashboard_abc123", "values": { "name": "Eric", "country": ["USA", "CANADA"], "timePeriod": { "startDate": "2024-01-01", "endDate": "2024-03-23" }, "price": { "min": 1000, "max": 5000 }, "region": { "sql": "SELECT \"name\" FROM \"public\".\"countries\" WHERE isEnabled=true", "columnName": "name" } }, "isShowOnUrl": false } ``` ``` -------------------------------- ### Example Usage with Client ID, Filters, and Secrets Source: https://docs.usedatabrain.com/guides/features/python-editor-console Demonstrates setting predefined variables, accessing secrets, making an API request, and assigning the response to the 'result' variable. ```python # Assuming client_id and metric_filters are predefined client_id = '12345' metric_filters = {'salesDate': {'startDate': datetime.date(2021, 1, 1), 'endDate': datetime.date(2021, 12, 31)}} # Accessing a secret api_url = secrets['API_URL'] # Making a GET request response = requests.get(f"{api_url}/data?client_id={client_id}").json() # Assigning response to result result = response ``` -------------------------------- ### List Datasources (Python) Source: https://docs.usedatabrain.com/developer-docs/helpers/api-reference/list-datasources This Python example uses the `requests` library to list all datasources. It includes basic error checking and prints the names of the datasources. ```python import requests # List all datasources response = requests.get( 'https://api.usedatabrain.com/api/v2/datasource', headers={ 'Authorization': 'Bearer dbn_live_abc123...' } ) data = response.json() if data.get('error'): print('Error:', data['error']) else: print(f'Found {len(data["data"])} datasources:') for datasource in data['data']: print(f" - {datasource['name']}") ``` -------------------------------- ### Example Error: Upstream Fetch Failed Source: https://docs.usedatabrain.com/developer-docs/helpers/api-reference/proxy-authentication This is an example of an error response when the proxy fails to fetch data from the upstream service. ```json { "error": { "message": "upstream fetch failed" } } ``` -------------------------------- ### Create Workspace with Datasource Connection (Node.js) Source: https://docs.usedatabrain.com/developer-docs/helpers/api-reference/create-workspace Use this Node.js example to create a workspace connected to a datasource via the API. ```javascript const response = await fetch('https://api.usedatabrain.com/api/v2/workspace', { method: 'POST', headers: { 'Authorization': 'Bearer dbn_live_abc123...', 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'Sales Analytics', connectionType: 'DATASOURCE', datasourceName: 'postgres-main' }) }); const result = await response.json(); console.log(result); ``` -------------------------------- ### API Key Rotation Response Examples Source: https://docs.usedatabrain.com/developer-docs/helpers/api-reference/rotate-api-key These JSON examples illustrate successful and error responses when rotating an API key. ```json { "key": "7c9e6679-7425-40de-944b-e07fc1f90ae7" } ``` ```json { "error": { "code": "INVALID_REQUEST_BODY", "message": "\"expireAt\" is required" } } ``` ```json { "error": { "code": "AUTHENTICATION_ERROR", "message": "API Key is not provided or Invalid!" } } ``` ```json { "error": { "code": "AUTHENTICATION_ERROR", "message": "API Key is invalid or expired!" } } ``` ```json { "error": { "code": "INVALID_DATA_APP_API_KEY", "message": "invalid or expired API KEY, data app not found" } } ``` ```json { "error": { "code": "INTERNAL_SERVER_ERROR", "message": "INTERNAL_SERVER_ERROR" } } ``` -------------------------------- ### Install DataBrain Plugin Source: https://docs.usedatabrain.com/developer-docs/quick-start/embedding-tutorial Install the DataBrain plugin using npm, yarn, or pnpm. This package is required to embed dashboards. ```bash npm install @databrainhq/plugin ``` ```bash yarn add @databrainhq/plugin ``` ```bash pnpm add @databrainhq/plugin ``` -------------------------------- ### Create Workspace with Multi-Datamart Connection Source: https://docs.usedatabrain.com/developer-docs/helpers/api-reference/create-workspace This cURL example shows how to create a workspace for multiple datamarts. ```bash curl --request POST \ --url https://api.usedatabrain.com/api/v2/workspace \ --header 'Authorization: Bearer dbn_live_abc123...' \ --header 'Content-Type: application/json' \ --data '{ \ "name": "Multi-Datamart Analytics", \ "connectionType": "MULTI_DATAMART" \ }' ``` -------------------------------- ### Create Workspace with Datamart, AI, and Theme Settings Source: https://docs.usedatabrain.com/developer-docs/helpers/api-reference/create-workspace This advanced cURL example creates a workspace with a datamart connection, AI features enabled, and custom theme settings. ```bash curl --request POST \ --url https://api.usedatabrain.com/api/v2/workspace \ --header 'Authorization: Bearer dbn_live_abc123...' \ --header 'Content-Type: application/json' \ --data '{ \ "name": "Executive AI Workspace", \ "connectionType": "DATAMART", \ "datamartName": "finance-datamart", \ "llmName": "gpt-4o", \ "aiCopilotLlms": ["gpt-4o", "gpt-4.1-mini"], \ "isEnableMetricSuggestions": true, \ "isEnableMetricSummary": true, \ "summaryType": "custom", \ "customSummaryPrompt": "Summarize KPIs with variance drivers and weekly action items.", \ "themeName": "Executive Theme" \ }' ``` -------------------------------- ### Honeycomb High-Cardinality Query Example Source: https://docs.usedatabrain.com/guides/honeycomb-integration Example Honeycomb query to analyze errors and performance for the databrain-api service, grouping by userId and http.route. ```sql WHERE service.name = databrain-api AND http.status_code >= 500 AND userId EXISTS GROUP BY userId, http.route CALCULATE COUNT, P95(duration_ms) ``` -------------------------------- ### Create Guest Token (PHP) Source: https://docs.usedatabrain.com/developer-docs/helpers/api-reference/token Example of creating a guest token using PHP's cURL library. ```php 'user-456', 'dataAppName' => 'sales-dashboard', 'params' => [ 'rlsSettings' => [ [ 'metricId' => 'metric_123', 'values' => [ 'customer_id' => '456', 'region' => 'north-america' ] ] ] ], 'expiryTime' => 3600000 ]; curl_setopt_array($curl, [ CURLOPT_URL => 'https://api.usedatabrain.com/api/v2/guest-token/create', CURLOPT_RETURNTRANSFER => true, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS => json_encode($data), CURLOPT_HTTPHEADER => [ 'Authorization: Bearer dbn_live_abc123...', 'Content-Type: application/json' ], ]); $response = curl_exec($curl); curl_close($curl); ?> ``` -------------------------------- ### Honeycomb Initialization Log Example Source: https://docs.usedatabrain.com/guides/honeycomb-integration Example log message indicating successful OpenTelemetry initialization for the Databrain API service in Honeycomb. ```json { "level": "info", "message": "[Telemetry] OpenTelemetry initialized - service: databrain-api, endpoint: https://api.honeycomb.io:443" } ``` -------------------------------- ### API Response Examples Source: https://docs.usedatabrain.com/developer-docs/helpers/api-reference/update-datasource These examples show possible responses from the update datasource API, including success and various error scenarios. ```json { "name": "production-postgres" } ``` ```json { "error": { "code": "INVALID_REQUEST_BODY", "message": "Invalid credentials for postgres: \"host\" is required", "status": 400 } } ``` ```json { "error": { "code": "DATASOURCE_NAME_ERROR", "message": "Invalid datasource name", "status": 400 } } ``` ```json { "error": { "code": "CREDENTIAL_TEST_FAILED", "message": "Failed to connect to datasource", "status": 400 } } ``` ```json { "error": { "code": "AUTHENTICATION_ERROR", "message": "AUTHENTICATION_ERROR", "status": 401 } } ``` ```json { "error": { "code": "TENANCY_SETTINGS_UPDATE_FAILED", "message": "Failed to update tenancy settings", "status": 500 } } ```