I created function in Google Apps Script, that works well when I run it in Google Apps Script. Output data returns to Google Sheets.
function testFunction11() {
var rng = SpreadsheetApp.getActiveRange();
var encodedAuthInformation = Utilities.base64Encode("username:key");
var headers = {"Authorization" : "Basic " + encodedAuthInformation};
var params = {
'method': 'GET',
'muteHttpExceptions': true,
'headers': headers
};
var res = UrlFetchApp.fetch("https://api.apiservice.com/api/v1/xxx?fields=somefields", params);
Logger.log(res.getContentText());
rng.setValue(res);
}
Output in cell:
[
{
"id": xxx,
"createdDate": "2019-02-01T04:54:00Z",
"reference": "XXX"
},
etc
Then I assign script to button, 'testFunction11'. And when I click button, it returns
{
"message": "An error has occurred."
}
It looks like response from API server.
My only hypothesis is that google sheet's button adds some headers, User-Agent or content-type to request, which not allowed in API server. And after some search, I guess I can't reassign User-Agent in request. Is that something right or I do it wrong?
EDIT 1:
Headers for each case console.log(UrlFetchApp.getRequest(url, params))
:
When clicking button in spreadsheet:
{headers={Authorization=Basic XXXXXXXXQVU6MWVhODlmZmFkN2U3NGNjOGJkOTc1YTE1ZjVhNTE3MzE=, X-Forwarded-For=178.xx.my.ip}, method=get, payload=, followRedirects=true, validateHttpsCertificates=true, useIntranet=false, contentType=null, url=https://api.apisite.com/api/v1/SalesOrders?fields=Id,Createddate,Reference&where=Createddate%3E2019-02-01T00:00:00Z}
And for script:
{headers={Authorization=Basic XXXXXXXXQVU6MWVhODlmZmFkN2U3NGNjOGJkOTc1YTE1ZjVhNTE3MzE=}, method=get, payload=, followRedirects=true, validateHttpsCertificates=true, useIntranet=false, contentType=null, url=https://api.apisite.com/api/v1/SalesOrders?fields=Id,Createddate,Reference&where=Createddate%3E2019-02-01T00:00:00Z}
So the button only adds X-Forwarded-For
.
When I tried manually add X-Forwarded-For: 'unknown'
there are error like this
There are attribute with impossible value: Header:X-Forwarded-For
Text of error in russian, so sorry for maybe not accurate translating. It's fun, because when I added Test: unknown
in same way, there are no error, but obviously not working. Looks like google don't allow to change this value.
Will try different headers in postman and maybe confirm that this header is the cause of the error. Thank you @TheMaster
EDIT 2:
I tried different headers via Postman. So, result is when I add to headers X-Forwarded-For
key with any value, it return "message": "An error has occurred."
When I don't add this key, it works well.
So, the question is any way to disable adding this header via Google Apps Script. It seems like not.