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
// This script creates a new member in Sigma after ensuring the email does not already exist.// 1: Load environment variables from a specific .env file for configurationrequire('dotenv').config({ path: 'sigma-api-recipes/.env' });// 2: Import the function to obtain a bearer token from the authenticate-bearer moduleconst getBearerToken = require('../get-access-token');// 3: Import Axios for making HTTP requestsconst axios = require('axios');// 4: Load use-case specific variables from environment variablesconst baseURL = process.env.baseURL; // Your base URLconst baseEmail = process.env.EMAIL; // Retrieve the base email from environment variables// Dynamically generate a unique email using the base email in the format: baseEmail+mmddhhmm@sigmacomputing.comconst now = new Date();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')}`;const newMemberEmail = `${baseEmail.split('@')[0]}+${timestamp}@${baseEmail.split('@')[1]}`;console.log(`Generated email for new member: ${newMemberEmail}`);// Load additional member details from the environment variablesconst newMemberFirstName = process.env.NEW_MEMBER_FIRST_NAME;const newMemberLastName = process.env.NEW_MEMBER_LAST_NAME;const newMemberType = process.env.NEW_MEMBER_TYPE;async function memberExists(email, accessToken) {const requestURL = `${baseURL}/members?search=${encodeURIComponent(email)}`;console.log(`Checking if member exists with search parameter: ${email}`);try {const response = await axios.get(requestURL, {headers: {'Authorization': `Bearer ${accessToken}`,'Accept': 'application/json',}});// Log the full response for debuggingconsole.log('Response data:', JSON.stringify(response.data, null, 2));// Check if any member in the results matches the email exactlyconst members = response.data.entries || [];const exists = members.some(member => member.email.toLowerCase() === email.toLowerCase());console.log(`Member check result: ${exists ? 'Exists' : 'Does not exist'}`);return exists;} catch (error) {console.error('Error checking member existence:', error.response ? error.response.data : error.message);throw new Error('Failed to check member existence.');}}// Function to create a new memberasync function addNewMember() {const accessToken = await getBearerToken();if (!accessToken) {console.error('Failed to obtain Bearer token.');return;}// Log the environment variables to validate inputsconsole.log(`New member details:Email: ${newMemberEmail}First Name: ${newMemberFirstName}Last Name: ${newMemberLastName}Member Type: ${newMemberType}`);// Check if the member already existsconst exists = await memberExists(newMemberEmail, accessToken);if (exists) {console.log(`Member with email ${newMemberEmail} already exists. No action taken.`);return;}const requestURL = `${baseURL}/members`;console.log(`URL sent to Sigma: ${requestURL}`);try {// Make the API request to create the new memberconst response = await axios.post(requestURL, {email: newMemberEmail,firstName: newMemberFirstName,lastName: newMemberLastName,memberType: newMemberType, // Ensure this is passed correctly}, {headers: {'Content-Type': 'application/json','Authorization': `Bearer ${accessToken}`}});// Log the successful responseconst { memberId, memberType: createdMemberType } = response.data;console.log('New member added successfully:');console.log(`Member ID: ${memberId}`);console.log(`Account Type: ${createdMemberType}`);} catch (error) {// Handle errors and log detailsconsole.error('Error adding new member:', error.response ? error.response.data : error.message);}}// Execute the function if this script is run directlyif (require.main === module) {addNewMember();}// Export the function for reusemodule.exports = addNewMember;
Response Example
New member details:Email: phil+11201022@sigmacomputing.comFirst Name: philLast Name: apiMember Type: Procreate-new.js:62Checking if member exists with search parameter: phil+11201022@sigmacomputing.comcreate-new.js:29Response data: {"entries": [],"nextPage": null}create-new.js:39Member check result: Does not existcreate-new.js:45URL sent to Sigma: https://aws-api.sigmacomputing.com/v2/memberscreate-new.js:76New member added successfully:create-new.js:94Member ID: 3B1pLjqbSOfyk4YIBPMWLm6pyExOucreate-new.js:95Account 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

