I think you might want to accomplish the following:
function fetch() {
var endpoint = 'login';
var url = 'https://example.com/api/'+endpoint;
var payload = {
'username' : "user",
'password' : "pass",
}
var options = {
'method' : 'post',
'payload': JSON.stringify(payload),
};
var urlResponse = UrlFetchApp.fetch(url, options);
return urlResponse;
}
function logResponse(){
Logger.log(fetch());
}
So you can use "return" keyword to return the value from function on its call.
Then you don't need to declare variable outside of the function (for example in global scope).
You just need to call and pass it as a parameter to your logResponse() function.
So, pay attention to these lines:
- in 1st function ->
return urlResponse;
- in 2nd function ->
Logger.log(fetch())
P.S. Of course declaring a variable in outer scope which is accessible for both function also works.
But my solution above seems a better option.
Also some suggestions:
- you can rename your function name from
fetch() to fetchUrl to be more explicit.
- also the variable declaration for
urlResponse in the first function is redundant and you can do just:
return UrlFetchApp.fetch(url, options);
Update:
Pavel, look at the Option 1 which Jeremy has suggested in the answer.
In short words, as a suggestion you can wrap your piece of code (depending on your environment) into Immediately-invoked function expression:
Take a look the following example (pay attention to the comments) ->
(function () {
// all the inside of this function is a shared scope for two function below
'use strict';
// this is a declared variable which is accessible for 2nd function
// the value assigned will be the result of calling the 1st function
var urlResponse = fetch();
function fetch() {
var endpoint = 'login';
var url = 'https://example.com/api/'+endpoint;
var payload = {
'username' : "user",
'password' : "pass"
};
var options = {
'method' : 'post',
'payload': JSON.stringify(payload)
};
// return the value
return UrlFetchApp.fetch(url, options);
}
function logResponse() {
// use the shared variable (the value of it is a result of calling fetch() function
Logger.log(urlResponse);
}
// then if you want to log your response
// call the function
logResponse();
})();
abeforefunction setVar(). If you don't, eachais encapsulated in each function, it's like having two differenta.