Members: Create New (JavaScript)
Members: Create New (JavaScript)
This recipe demonstrates how to use the add new user endpoint to add new users to your Sigma organization
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 // This script creates a new member in Sigma after ensuring the email does not already exist. 2 3 // 1: Load environment variables from a specific .env file for configuration 4 require('dotenv').config({ path: 'sigma-api-recipes/.env' }); 5 6 // 2: Import the function to obtain a bearer token from the authenticate-bearer module 7 const getBearerToken = require('../get-access-token'); 8 9 // 3: Import Axios for making HTTP requests 10 const axios = require('axios'); 11 12 // 4: Load use-case specific variables from environment variables 13 const baseURL = process.env.baseURL; // Your base URL 14 const baseEmail = process.env.EMAIL; // Retrieve the base email from environment variables 15 16 // Dynamically generate a unique email using the base email in the format: baseEmail+mmddhhmm@sigmacomputing.com 17 const now = new Date(); 18 const timestamp = `${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}`; 19 const newMemberEmail = `${baseEmail.split('@')[0]}+${timestamp}@${baseEmail.split('@')[1]}`; 20 console.log(`Generated email for new member: ${newMemberEmail}`); 21 22 // Load additional member details from the environment variables 23 const newMemberFirstName = process.env.NEW_MEMBER_FIRST_NAME; 24 const newMemberLastName = process.env.NEW_MEMBER_LAST_NAME; 25 const newMemberType = process.env.NEW_MEMBER_TYPE; 26 27 async function memberExists(email, accessToken) { 28 const requestURL = `${baseURL}/members?search=${encodeURIComponent(email)}`; 29 console.log(`Checking if member exists with search parameter: ${email}`); 30 try { 31 const response = await axios.get(requestURL, { 32 headers: { 33 'Authorization': `Bearer ${accessToken}`, 34 'Accept': 'application/json', 35 } 36 }); 37 38 // Log the full response for debugging 39 console.log('Response data:', JSON.stringify(response.data, null, 2)); 40 41 // Check if any member in the results matches the email exactly 42 const members = response.data.entries || []; 43 const exists = members.some(member => member.email.toLowerCase() === email.toLowerCase()); 44 45 console.log(`Member check result: ${exists ? 'Exists' : 'Does not exist'}`); 46 return exists; 47 } catch (error) { 48 console.error('Error checking member existence:', error.response ? error.response.data : error.message); 49 throw new Error('Failed to check member existence.'); 50 } 51 } 52 53 // Function to create a new member 54 async function addNewMember() { 55 const accessToken = await getBearerToken(); 56 if (!accessToken) { 57 console.error('Failed to obtain Bearer token.'); 58 return; 59 } 60 61 // Log the environment variables to validate inputs 62 console.log(`New member details: 63 Email: ${newMemberEmail} 64 First Name: ${newMemberFirstName} 65 Last Name: ${newMemberLastName} 66 Member Type: ${newMemberType}`); 67 68 // Check if the member already exists 69 const exists = await memberExists(newMemberEmail, accessToken); 70 if (exists) { 71 console.log(`Member with email ${newMemberEmail} already exists. No action taken.`); 72 return; 73 } 74 75 const requestURL = `${baseURL}/members`; 76 console.log(`URL sent to Sigma: ${requestURL}`); 77 78 try { 79 // Make the API request to create the new member 80 const response = await axios.post(requestURL, { 81 email: newMemberEmail, 82 firstName: newMemberFirstName, 83 lastName: newMemberLastName, 84 memberType: newMemberType, // Ensure this is passed correctly 85 }, { 86 headers: { 87 'Content-Type': 'application/json', 88 'Authorization': `Bearer ${accessToken}` 89 } 90 }); 91 92 // Log the successful response 93 const { memberId, memberType: createdMemberType } = response.data; 94 console.log('New member added successfully:'); 95 console.log(`Member ID: ${memberId}`); 96 console.log(`Account Type: ${createdMemberType}`); 97 } catch (error) { 98 // Handle errors and log details 99 console.error('Error adding new member:', error.response ? error.response.data : error.message); 100 } 101 } 102 103 // Execute the function if this script is run directly 104 if (require.main === module) { 105 addNewMember(); 106 } 107 108 // Export the function for reuse 109 module.exports = addNewMember;
Response Example
1 New member details: 2 Email: phil+11201022@sigmacomputing.com 3 First Name: phil 4 Last Name: api 5 Member Type: Pro 6 create-new.js:62 7 Checking if member exists with search parameter: phil+11201022@sigmacomputing.com 8 create-new.js:29 9 Response data: { 10 "entries": [], 11 "nextPage": null 12 } 13 create-new.js:39 14 Member check result: Does not exist 15 create-new.js:45 16 URL sent to Sigma: https://aws-api.sigmacomputing.com/v2/members 17 create-new.js:76 18 New member added successfully: 19 create-new.js:94 20 Member ID: 3B1pLjqbSOfyk4YIBPMWLm6pyExOu 21 create-new.js:95 22 Account Type: undefined
Endpoints used
- Get authentication token:
${baseURL}/authURL - List recent documents:
${baseURL}/members/${memberId}/files/recents - Get all workbooks:
${baseURL}/workbooks?page=${nextPage} - List users:
${baseURL}/members?page=${page} - Add new user:
${baseURL}/members

