I deployed a Google Apps Script Web App which uses a service account to access the Google Directory. I deployed it that everyone has access to the app and that the app runs under the user executing it.
I would like to trigger this web app by calling the POST trigger from another app script which is part of a Google form. Something like this:
function onPost(){
var data = {
'name': 'Bob Smith',
'age': 35,
'pets': ['fido', 'fluffy']
};
var options = {
'method' : 'post',
'contentType': 'application/json',.
'payload' : JSON.stringify(data)
};
var resp = UrlFetchApp.fetch('https://script.google.com/a/my.domain.com/m.../exec', options);
}
However, I get back:
Exception: Request failed for https://script.google.com returned code 401.
When I try to use the GET trigger with some query parameters the response back looks like a google sign in page.
How can I trigger my web app from another app script all in the same domain?
Updated code with token:
function onPost(){
var token = ScriptApp.getOAuthToken();
var data = {
'name': 'Bob Smith',
'age': 35,
'pets': ['fido', 'fluffy']
};
var options = {
'headers':'Bearer '+token,
'method' : 'post',
'contentType': 'application/json',.
'payload' : JSON.stringify(data)
};
var resp = UrlFetchApp.fetch('https://script.google.com/a/my.domain.com/m.../exec', options);
}
401
is an " unauthorized" error, you have to, well, authorize the request. Only if you deploy as "me" and "anyone, even anonymous" will you get a public API. If you want the script to be run under user's authority, though, then you need to authorize it. You can get the bearer token withgetOAuthToken()
, btw. That would mean your users will have to give your first application permission to do staff on their behalf (must be sufficient to run the services in the Web App) – Oleg Valter