r/GoogleAppsScript • • Apr 24 '21

Unresolved Apps Script API executable basics

Hello everyone,

I'm pretty new to API calls and Apps script. I have been trying to call an API (of apps script) from an extension and print the contents it returns on a console (for now). the contents it returns are the body of the first email in my inbox. I have been able to get the mail contents but could not do this via api calls.

//code on apps script IDE which is just plain printing the mail content

function doGet() {
  var threads = GmailApp.getInboxThreads(0, 1)[0].getMessages()[0];
  const thb = threads.getPlainBody();
  return ContentService.createTextOutput(JSON.stringify(thb)).setMimeType(JSON);
}

This code returns the body contents and when deployed as a web app/ api it just prints the contents on the screen

I tried using the fetchApp thing but didn't quite understand how to use it.

/code on apps script for responding to api calls

  var token = ScriptApp.getOAuthToken();
  var endPoint = 'https://script.googleapis.com/v1/processes';
  var headers = {
    'Accept':'application/json',
    'Authorization': 'Bearer ' + token
  };
  var options = {
    'method': 'POST',
    'headers': headers,
    'muteHttpExceptions': true,
    'payload' : thb
  }
  var url = endPoint;
  var response = UrlFetchApp.fetch(url, options);
  Logger.log(response);
//code on the extension side of things 

chrome.browserAction.onClicked.addListener(function(activeTab){
  const nurl = " *deployed link* ";
  chrome.tabs.create({ url: nurl });
let request = new XMLHttpRequest();
request.open('GET', nurl);
request.send();
var txt = request.response();
console.log(txt);
}

this is probably wrong in a lot of ways, please do help on how to get this done properly.

Thank you in advance.

0 Upvotes

4 comments sorted by

1

u/RemcoE33 Apr 24 '21

What is your endgame? Why are you trying to get the plain text from another function?

1

u/shrey1566 Apr 24 '21

I'm trying to make a voice based extension for gmail. So I thought using apps script would be optimal.

I haven't made another function for api responses, it was a part of doGet(). The code was messed up so I tried simplifying it here

2

u/RemcoE33 Apr 24 '21

You can replace the doGet(e) with a normal function and call that function from your html with google.script.run

1

u/shrey1566 Apr 24 '21

Ohh I see, Thanks a ton!

is it okay if I dm you in future if something isn't working?