I need to create API requests from within Airtable’s scripting environment. The API endpoint I’m working with needs an Authorization header that includes a Base64 encoded version of my credentials in the format api:USERNAME:API_TOKEN.
The problem is that btoa() isn’t available in Airtable’s environment. I found a custom Base64 implementation online and tried using it:
var EncodingHelper = {
charset: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
convertToBase64: function(input) {
var output = "";
var char1, char2, char3, enc1, enc2, enc3, enc4;
var index = 0;
input = EncodingHelper.processUtf8(input);
while (index < input.length) {
char1 = input.charCodeAt(index++);
char2 = input.charCodeAt(index++);
char3 = input.charCodeAt(index++);
enc1 = char1 >> 2;
enc2 = ((char1 & 3) << 4) | (char2 >> 4);
enc3 = ((char2 & 15) << 2) | (char3 >> 6);
enc4 = char3 & 63;
if (isNaN(char2)) {
enc3 = enc4 = 64;
} else if (isNaN(char3)) {
enc4 = 64;
}
output += this.charset.charAt(enc1) + this.charset.charAt(enc2) +
this.charset.charAt(enc3) + this.charset.charAt(enc4);
}
return output;
},
processUtf8: function(text) {
text = text.replace(/\r\n/g, "\n");
var result = "";
for (var i = 0; i < text.length; i++) {
var code = text.charCodeAt(i);
if (code < 128) {
result += String.fromCharCode(code);
} else if (code > 127 && code < 2048) {
result += String.fromCharCode((code >> 6) | 192);
result += String.fromCharCode((code & 63) | 128);
} else {
result += String.fromCharCode((code >> 12) | 224);
result += String.fromCharCode(((code >> 6) & 63) | 128);
result += String.fromCharCode((code & 63) | 128);
}
}
return result;
}
};
const credentials = 'MY_USER:MY_TOKEN';
var encodedCredentials = EncodingHelper.convertToBase64(credentials);
let apiResponse = await fetch('https://example-api.com/data', {
method: 'GET',
headers: {
'Authorization': 'Basic ' + encodedCredentials
}
});
But I’m still getting 401 errors. I even tested the encoding locally with btoa() and used that result directly, but same issue. Any ideas what might be wrong with my Base64 encoding approach in Airtable?