I want to perform an HTTP request from server-side code in a Google App Script with an Authorization
header. Is there an App Script API for sending HTTP requests?
What's the equivalent of this code in a Google Apps Script?
var api = "URL";
$.ajax({
type: 'GET',
url: api,
contentType: 'application/json',
dataType:'json',
data: {},
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', makeBaseAuth('username', 'password'));
}
});
You can send HTTP requests using the UrlFetchApp
object. It has a fetch(url, params)
method that returns a HTTPResponse
with information about the result of the HTTP fetch.
function testapi(){
var encode = Utilities.base64Encode('username:password', Utilities.Charset.UTF_8);
Logger.log(encode);
var option = {
headers : {
Authorization: "Basic "+ encode
}
}
var url = "URL";
var response = UrlFetchApp.fetch(url, option).getContentText()
response = JSON.parse(response);
for (var key in response){
Logger.log(key);
}
}
you need to use UrlFetchApp
. see the official docs