Get Column Names by Page and Element (Javascript)

View as Markdown

This script automates the process of retrieving column names for all elements in each page of a workbook in Sigma.

Refer to the Sigma REST API Recipes QuickStart for step-by-step instructions.

Example script

Node
1// Load environment variables from a specific .env file for configuration
2require('dotenv').config({ path: 'sigma-api-recipes/.env' });
3
4// Import the function to obtain a bearer token from the authenticate-bearer module
5const getBearerToken = require('../get-access-token');
6
7// Import Axios for making HTTP requests
8const axios = require('axios');
9
10// Load use-case specific variables from environment variables
11const baseURL = process.env.baseURL; // Base URL for the Sigma API - AWS US
12const memberId = process.env.MEMBERID; // The unique identifier of the member, used to fetch their specific workbooks
13
14// Fetch List of Available Workbooks
15// This function fetches the list of workbooks available to a specific member, filtering by type 'workbook'
16async function fetchWorkbooks(memberId, accessToken) {
17 const url = `${baseURL}/members/${memberId}/files?typeFilters=workbook`;
18 console.log(`Fetching workbooks from: ${url}`); // Logs the constructed URL to console for verification
19 try {
20 const response = await axios.get(url, {
21 headers: {
22 'Authorization': `Bearer ${accessToken}`, // Uses the Bearer token for authorization
23 'accept': 'application/json' // Specifies that the response should be in JSON format
24 }
25 });
26
27 // Checks if 'entries' exists and is an array, then maps over it to return an array of workbook details
28 if (response.data && Array.isArray(response.data.entries)) {
29 return response.data.entries.map(workbook => ({
30 id: workbook.urlId, // Extracts the urlId as id of the workbook
31 name: workbook.name // Extracts the name of the workbook
32 }));
33 } else {
34 console.error('No entries found or unexpected response structure:', response.data);
35 return [];
36 }
37 } catch (error) {
38 console.error(`Error fetching workbooks: ${error}`); // Logs errors if the API call fails
39 if (error.response) {
40 console.error(`Response status: ${error.response.status}`); // Logs the HTTP status code of the response
41 console.error(`Response headers: ${JSON.stringify(error.response.headers)}`); // Logs the response headers
42 console.error(`Response body: ${JSON.stringify(error.response.data, null, 2)}`); // Logs the response body
43 } else {
44 console.error(`Error details: ${error.message}`); // Logs details of errors not related to HTTP responses
45 }
46 return [];
47 }
48}
49
50// Main function to manage the overall workflow
51async function main() {
52 const accessToken = await getBearerToken(); // Retrieves the access token
53 if (!accessToken) {
54 console.error('Failed to obtain Bearer token.'); // Logs an error if the token cannot be obtained
55 return;
56 }
57
58 const workbooks = await fetchWorkbooks(memberId, accessToken); // Fetches workbooks using the member ID and access token
59 if (workbooks.length > 0) {
60 workbooks.forEach((workbook, index) => {
61 const embedURL = `https://app.sigmacomputing.com/embed/1-CQjBrPzWu1JQiPaq2AfW2/workbook/${workbook.id}`;
62 console.log(`#${index + 1}: ${workbook.name}: ${embedURL}`);
63 });
64 } else {
65 console.log('No workbooks available for processing or embedding.'); // Logs a message if no workbooks are found
66 }
67}
68
69if (require.main === module) {
70 main(); // Executes the main function if the file is run directly
71}
72
73module.exports = main; // Exports the main function to allow it to be used in other modules

Endpoints used

  1. Get authentication token: getBearerToken function
  2. Get workbook details ${baseURL}/workbooks/${workbookId}
  3. Get workbook pages ${baseURL}/workbooks/${workbookId}/pages
  4. Get elements on a page ${baseURL}/workbooks/${workbookId}/pages/${pageId}/elements
  5. Get element columns ${baseURL}/workbooks/${workbookId}/elements/${elementId}/columns