What is the server equivalent of $ .ajax () in Google Apps scripting?

I want to make an HTTP request from server-side code in a Google Script app with a header Authorization

. Is there a Script Application API for sending HTTP requests?

What is the equivalent of this code in 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'));
     }
});

      

+3


source to share


2 answers


You can send HTTP requests using an object UrlFetchApp

. It has a method fetch(url, params)

that returns HTTPResponse

information about the HTTP fetch result.



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);
    }
}

      

+7


source


you need to use UrlFetchApp

. see official docs



+1


source







All Articles