Created
May 4, 2022 15:32
-
-
Save balindersingh/fcc0809991a83a693db6a9c8ce827aeb to your computer and use it in GitHub Desktop.
Create records in Airtable from Google sheets using Google AppScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function addMenu() { | |
var ui = SpreadsheetApp.getUi(); | |
ui.createMenu('Air Table') | |
.addItem('Create a dummy record Airtable','createAirtableSingleTestRecord') | |
.addItem('Push current sheet to Airtable','createAirtableRecordFromCurrentSheet') | |
.addToUi(); | |
} | |
const Airtable_API_Key = "<YOUR_AIRTABLE_API_KEY>"; | |
const Airtable_API_Endpoint = "https://api.airtable.com/v0/"; | |
const Airtable_Base_Name = "<YOUR_AIRTABLE_API_KEY>"; | |
const Airtable_Table_Name = "Services"; | |
function createAirtableRecordFromCurrentSheet(){ | |
var rows = SpreadsheetApp.getActiveSheet().getDataRange().getValues(); | |
var columnHeaders = rows[0]; | |
let atRecords = []; | |
for (let rIndex = 1; rIndex < rows.length; rIndex++) { | |
let atFields = {}; | |
for (let cindex = 0; cindex < columnHeaders.length; cindex++) { | |
let colName = columnHeaders[cindex]; | |
atFields[colName] = rows[rIndex][cindex]; | |
} | |
atRecords.push({ fields: atFields}); | |
} | |
let atRecordData = { records : atRecords}; | |
var json = JSON.parse(postToAirtable(Airtable_Base_Name,Airtable_Table_Name,atRecordData)); | |
Logger.log(json); | |
} | |
function createAirtableSingleTestRecord(){ | |
var dt = new Date(); | |
var title = "test title gs "+dt.toISOString(); | |
var recordData = { | |
records: [ | |
{ | |
fields: { | |
Name: title, | |
Description: "description" | |
} | |
} | |
] | |
}; | |
var json = JSON.parse(postToAirtable(Airtable_Base_Name,Airtable_Table_Name,recordData)); | |
Logger.log(json); | |
} | |
// | |
// post to airtable (universal) | |
// | |
function postToAirtable(baseKey, tableName, payload) | |
{ | |
var options = | |
{ | |
method: 'POST', | |
headers: { | |
'Authorization' : 'Bearer ' + Airtable_API_Key, | |
'Content-Type' : 'application/json' | |
}, | |
payload : JSON.stringify(payload), | |
muteHttpExceptions : false, | |
followRedirects: true | |
}; | |
var response = UrlFetchApp.fetch(Airtable_API_Endpoint + baseKey + "/" + encodeURIComponent(tableName), options).getContentText(); | |
return(response); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment