> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://help.sigmacomputing.com/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://help.sigmacomputing.com/_mcp/server.

# Teams: Bulk Assign Members (JavaScript)

> This script is designed to bulk assign existing members to a specific team, utilizing the members' emails as identifiers.

This script is designed to bulk assign existing members to a specific team, using the email address of each member as an identifier. It operates by reading a list of email addresses from a `.member-emails` file, finding each member's ID through the Sigma API, then assigning each member to a designated team.

Each section of the script has inline comments provided.

Refer to the [Sigma REST API Recipes](https://quickstarts.sigmacomputing.com/guide/developers_api_code_samples/index.html?index=../..index#0) QuickStart for step-by-step instructions.

## Example script

```javascript JavaScript
// This script bulk assigns existing members to a team, based on the members's email, which is matched from the "../.member-emails" file.
// Load required modules and environment variables for script configuration.

require('dotenv').config({ path: 'sigma-api-recipes/.env' });
const getBearerToken = require('../get-access-token'); // Function to obtain an authentication token.
const axios = require('axios'); // HTTP client for making requests to Sigma's API.
const fs = require('fs'); // File system module to read the list of emails from a file.
const path = require('path'); // Module for handling file paths.

// Environment variables loaded from the .env file.
const baseURL = process.env.baseURL; // Base URL for Sigma's API endpoints.
const teamId = process.env.TEAMID; // Target team ID for assigning members.
const emailListPath = path.join(__dirname, '..', '.member-emails'); // Path to the file containing member emails.

// Function to find a member's ID by their email address.
async function findMemberIdByEmail(email, token) {
    const encodedEmail = encodeURIComponent(email); // Encode email to ensure it is URL-safe.
    const requestUrl = `${baseURL}/members?search=${encodedEmail}`; // Construct the request URL.
    console.log(`Searching for member by email with URL: ${requestUrl}`); // Log the request for debugging.
    try {
        const response = await axios.get(requestUrl, {
            headers: { Authorization: `Bearer ${token}` }, // Include the bearer token for authentication.
        });
        // Return the first matching member ID if found.
        return Array.isArray(response.data) && response.data.length > 0 ? response.data[0].memberId : null;
    } catch (error) {
        console.error(`Error searching for member by email (${email}):`, error);
        return null; // Return null if an error occurs or no member is found.
    }
}

// Function to add a member to a specified team by their member ID.
async function addMemberToTeam(memberId, teamId, token) {
    const requestUrl = `${baseURL}/teams/${teamId}/members`; // API endpoint for adding a member to a team.
    const payload = { add: [memberId], remove: [] }; // Payload specifying the member to add (and none to remove).
    const headers = { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' }; // Request headers.
    
    // Log the request details for debugging.
    console.log(`Adding member to team with URL: ${requestUrl}`);
 //   console.log(`Headers:`, JSON.stringify(headers, null, 2));
    console.log(`Payload:`, JSON.stringify(payload, null, 2));

    try {
        const response = await axios.patch(requestUrl, payload, { headers });
        console.log(`Member ${memberId} added to team ${teamId}. Response:`, response.data);
    } catch (error) {
        console.error(`Error adding member ${memberId} to team ${teamId}:`, error.response ? error.response.data : error);
    }
}

// Main function to process member emails and assign them to the specified team.
async function processMembers(teamId, token) {
    const emails = fs.readFileSync(emailListPath, 'utf-8').split(','); // Read and split the list of emails.
    for (const email of emails) {
        const memberId = await findMemberIdByEmail(email.trim(), token); // Get member ID by email.
        if (memberId) {
            await addMemberToTeam(memberId, teamId, token); // Add the member to the team.
        } else {
            console.log(`Member not found for email: ${email}`); // Log if no member ID is found for an email.
        }
    }
}

// Entry point of the script.
async function main() {
    const token = await getBearerToken(); // Fetch the bearer token.
    if (!token) {
        console.error('Failed to obtain bearer token.');
        return;
    }
    await processMembers(teamId, token); // Process member assignments.
}

main().catch(console.error); // Execute the main function and catch any errors.

```

## Endpoints used

1. Get authentication token: `getBearerToken` function
2. Find member by email: `${baseURL}/members?search=${encodedEmail}`
3. Add member to team: `${baseURL}/teams/${teamId}/members`