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'));
}
});
It is possible to use jQuery from Google Apps Script, but only through the HtmlService, and only in client-side scripts. It's mentioned in the HtmlService Best Practices documentation.
To add an HTML file to your Apps Script project, open the Script Editor and choose File > New > HTML File. Within the HTML file, you can write most standard HTML, CSS, and client-side JavaScript. The page will be served as HTML5, although some advanced features of HTML5 are not available, as explained in Restrictions.
Google Apps Script is a rapid application development platform that makes it fast and easy to create business applications that integrate with Google Workspace. You write code in modern JavaScript and have access to built-in libraries for favorite Google Workspace applications like Gmail, Calendar, Drive, and more.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With