Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the server-side equivalent of $.ajax() in Google Apps Scripts?

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'));
     }
});
like image 416
Bayrem Ben Alaya Avatar asked May 21 '15 15:05

Bayrem Ben Alaya


People also ask

Can I use jQuery in Google App script?

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.

How do I use Appscript in HTML?

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.

Does Google scripts use JavaScript?

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.


Video Answer


2 Answers

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);
    }
}
like image 125
Bayrem Ben Alaya Avatar answered Oct 05 '22 16:10

Bayrem Ben Alaya


you need to use UrlFetchApp. see the official docs

like image 45
Zig Mandel Avatar answered Oct 05 '22 15:10

Zig Mandel