Members: List All (JavaScript)

View as MarkdownOpen in Claude

Returns all users to a JSON-formatted file, using pagination parameter from the .env file (limit).

Each section of the script has inline comments provided.

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

Example script

JavaScript
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');
9const fs = require('fs'); // Import File System for saving output
10
11// Load use-case specific variables from environment variables
12const baseURL = process.env.baseURL; // Your base URL
13const limit = process.env.LIMIT || 200; // Get limit from .env, default to 200
14
15// Define an asynchronous function to list members.
16async function listMembers() {
17 // Obtain a bearer token using the previously imported function.
18 const accessToken = await getBearerToken();
19 if (!accessToken) {
20 console.log('Failed to obtain Bearer token.');
21 return;
22 }
23
24 let allMembers = []; // Store all retrieved members
25 let nextPage = null; // Initialize pagination token
26
27 try {
28 while (true) {
29 // Construct the API URL with pagination
30 let membersURL = `${baseURL}/members?limit=${limit}`;
31 if (nextPage) {
32 membersURL += `&page=${encodeURIComponent(nextPage)}`;
33 }
34
35 console.log(`Fetching members from: ${membersURL}`);
36
37 // Make API request
38 const response = await axios.get(membersURL, {
39 headers: {
40 'Authorization': `Bearer ${accessToken}`,
41 'Accept': 'application/json'
42 }
43 });
44
45 // Check if API response contains entries
46 const members = response.data.entries || [];
47 console.log(`Fetched ${members.length} members in this batch.`);
48
49 // Append fetched members to allMembers
50 allMembers = allMembers.concat(members);
51 console.log(`Total members collected so far: ${allMembers.length}`);
52
53 // Check if there's a nextPage token
54 nextPage = response.data.nextPage || null;
55 if (!nextPage) break; // Stop if there are no more pages
56 }
57
58 console.log(`Total Members Retrieved: ${allMembers.length}`);
59
60 // Save to a JSON file for verification
61 fs.writeFileSync('members_output.json', JSON.stringify(allMembers, null, 2));
62 console.log("Full member list saved to members_output.json");
63
64 } catch (error) {
65 console.error('Error listing members:', error.response ? error.response.data : error);
66 }
67}
68
69// Execute the function to list members.
70listMembers();

Endpoints used

  1. Get authentication token: ${baseURL}/authURL
  2. List recent documents: ${baseURL}/members/${memberId}/files/recents
  3. Get all workbooks: ${baseURL}/workbooks?page=${nextPage}
  4. List members: ${baseURL}/members?page=${page}