Duplicate records being created when sending data to Airtable via API

I’m working on a script that transfers student data from our system to Airtable using their API. The data transfer works fine, but I’m getting duplicate entries created in Airtable even though my payload doesn’t contain any duplicates when I check it.

Here’s my code that identifies which students need to be added:

for (let student of studentList) {
    if (student.enrollment_status === 'active' || student.enrollment_status === 'pending') {
        const isNewStudent = !existingRecords.find(record => record.student_id === student.student_id);
        if (isNewStudent) {
            studentsToAdd.records.push({
                fields: {
                    ...student
                },
            });
        }
    }
    
    sendToAirtable('appXYZ123','StudentData', studentsToAdd)
}

And here’s my function for sending data to Airtable:

function sendToAirtable(baseId, table, data) {
    var requestOptions = {
        method: 'POST',
        headers: {
            'Authorization': 'Bearer ' + apiToken,
            'Content-Type': 'application/json',
            "Accept": "application/json"
        },
        payload: JSON.stringify(data)
    };
    var result = UrlFetchApp.fetch('https://api.airtable.com/v0/' + baseId + "/" + encodeURIComponent(table), requestOptions).getContentText();
    return result;
}

Any ideas why duplicates are still being created?

Had the exact same issue - drove me nuts for weeks! You’re calling sendToAirtable inside your loop for every student, not just new ones. Each loop iteration sends the entire studentsToAdd array to Airtable, and that array keeps growing. Move sendToAirtable outside the for loop so it only runs once after you’ve built your complete array. Also throw in some logging to see how many times your API call fires - bet it’s way more than you think.