I'm getting an error response from the API that I'm using, but Google scripts seems to truncate the message. How can I see the full message in Google scripts?
This is the message:
Request failed for https://api.myintervals.com/task/ returned code 400. Truncated server response: {"personid":"180761","status":"Bad Request","code":400,"error":{"code":18,"message":"Validation error has occurred (missing required field/paramet... (use muteHttpExceptions option to examine full response) (line 171, file "IntervalsPull")
Just as #DrSatan1 pointed in the comment, pass muteHttpExceptions option in the parameter to suppress the exception and get the error returned as HTTPResponse.
options = {muteHttpExceptions: true};
var response = UrlFetchApp.fetch("https://api.myintervals.com/task/", options);
Logger.log(response.getContentText());
Now view your logs to see the complete error response.
While setting response to logger or console works, even that will be truncated if the response is too long. You may have to set the response to Drive in such cases.
options.muteHttpExceptions = true;
const res = UrlFetchApp.fetch(url, options);
console.log(res.getResponseCode());
console.log(res);
DriveApp
.getFoldersByName('test'/*A folder in Drive*/)
.next()
.createFile(res.getBlob().setName('response'))
Related
I have been trying to import a JSON file from SEC EDGAR but have been unsuccessful. It shows the following error:
Exception: request failed for https://data.sec.gov returned code 403. Truncated server response: <html xmlns="http://www.w... (use muteHttpExceptions option to examine full response) (line 220)
The function that I have been using can be found here (with no modifications): https://github.com/bradjasper/ImportJSON
It is working normally for other sites, the only one so far that I had problem is the SEC EDGAR site: https://data.sec.gov/api/xbrl/companyconcept/CIK0000320193/us-gaap/AccountsPayableCurrent.json
The reason is :
Your Request Originates from an Undeclared Automated Tool. To allow for equitable access to all users, SEC reserves the right to limit requests originating from undeclared automated tools. Your request has been identified as part of a network of automated tools outside of the acceptable policy and will be managed until action is taken to declare your traffic.
function getStatusCode(url='https://data.sec.gov/api/xbrl/companyconcept/CIK0000320193/us-gaap/AccountsPayableCurrent.json'){
var options = {
'muteHttpExceptions': true,
'followRedirects': false
};
var url_trimmed = url.trim();
var response = UrlFetchApp.fetch(url_trimmed, options);
Logger.log (response.getResponseCode());
Logger.log (response.getContentText())
}
the only way I know is to copy manually the json in a cell then parse it
For GET and POST requests for a private server I work with I use in Google Sheets, do something like this, and I get a proper response. I use that response to update data and just as importantly for error checking by evaluating response.getResponeCode().
function postDataToServer(params){
let myjdService = getService();
let orgId = getOrgIdForSelectedOrg();
let link = https://GoodURLForPrivateDataIWorkWithALot/neededurlParameter/anotherNeededURLParameter;
let options = {
'method': 'put',
'payload': JSON.stringify(params),
'headers': {
'Accept': 'application/vnd.PRIVATE.v3+json',
'Content-Type': 'application/vnd.PRIVATE.v3+json',
'authorization': 'Bearer ' + myPrivateService.getAccessToken()
}
};
let response = UrlFetchApp.fetch(link, options);
return response.getResponseCode();
For all the GET and POST requests I do, I get a response. And from that response I can parse a response code. But for the specific server I work with, when I edit a record using PUT, a successful edit returns this:
204 No Content
And further, the last line return response.getResponseCode() returns an error the response is undefined.
Here's the error I get for doing anything with response:
ReferenceError: response is not defined
The PUT is working. I only know this because 1) when I check if edits are made with the server, they are 2) testing the PUT in Postman at least shows me the words "204 No Content" and 3) the documentation says that's exactly what I should expect.
But I still would like to find out how to evaluate this no-content response in my Google Sheets App for proper error tracking. At least some way to get the string "204". Any ideas? I can't even get Google Sheets to do say 204.
I have 2 questions about Google App Script Services getResponseCode() method.
1) "Unexpected Error"
When I run the getResponseCode() method, I got "Unexpected Error...".
https://developers.google.com/apps-script/reference/url-fetch/http-response#getResponseCode()
var response = UrlFetchApp.fetch(url, {muteHttpExceptions: true});
responseCode = response.getResponseCode();
Unexpected error: https://www.example.com/
※I can't tell the url for business reasons.
HTTP response status codes don't include "Unexpected Error".
https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
Please tell me what response codes actually return, when this error occurs?
2) getResponseCode() method didn't work as expected
When I run the code below, I got "200".
I expected "301" in response to the "http://google.com/" request.
function myFunction() {
var response = UrlFetchApp.fetch("http://google.com/");
Logger.log(response.getResponseCode());
}
I think getResponseCode() method doesn't return actual http status codes.
Please tell me why I got "200" instead of "301".
get 301 response in browser
get 200 response instead of 301
This happens because the request is following the redirect. Take a look at the available parameters in the UrlFetchApp.fetch() method. You'll see followRedirects, which defaults to true.
Make this small change and you'll get the expected 301.
function myFunction() {
var response = UrlFetchApp.fetch("http://google.com/", { followRedirects: false });
Logger.log(response.getResponseCode());
}
I'm new to Google Apps Scripts and I've been trying to make a simple Get call to a URL. I make this call from my browser: https://accounting.sageone.co.za/api/1.1.1/Supplier/Get?apikey={4CFEEFE1-CE04-425F-82C3-DCB179C817D5}&companyid=164740 and get the respons I'm looking for. I now try to make the call from Google Apps Scripts using the following code:
function myFunction() {
var url = 'https://accounting.sageone.co.za/api/1.1.1/Supplier/Get?apikey={4CFEEFE1-CE04-425F-82C3-DCB179C817D5}&companyid=164740
var response = UrlFetchApp.fetch(url);
Logger.log(response);
}'
I get a respons stating '
Message details
Invalid argument: https://accounting.sageone.co.za/api/1.1.1/Supplier/Get?apikey={4CFEEFE1-CE04-425F-82C3-DCB179C817D5}&companyid=164740 (line 4, file "Code")'
I've tried a whole bunch of permutations with no luck...
When using UrlFetchApp, you need to enter your URL parameters as part of a request parameters rather than in the URL itself. For a GET request these go directy as part of the parameters, for a POST request the parameters would be part of a payload object. Reference Documentation
Here is a modified function:
function myFunction() {
var url = 'https://accounting.sageone.co.za/api/1.1.1/Supplier/Get'
var params = {
"method": 'GET',
"apikey": "{4CFEEFE1-CE04-425F-82C3-DCB179C817D5}",
"companyid": "164740"
}
var response = UrlFetchApp.fetch(url, params);
Logger.log(response)
}
Note: This corrects your method, however, the server still requires further authentication. If you run into issues with that, ask another questions specific to that issue as well.
After calling realtime.loadAppDataDocument I receive the error:
XMLHttpRequest cannot load https://drive.google.com/load?
access_token=ya29.AHES6ZRoDqY0PmpHlbUjniB8wIl… Kzw
&id=1xAp1SMlamIfjnUGO9pDwfNF5IphdtnZsCw36KalJss27wy00LJ-rCN9MpcHMx408Xg.
Origin http://localhost:4567 is not allowed by Access-Control-Allow-Origin.
However if I call realtime.load with a fileid it works. See code extract below
if (fileId === null) {
// this call fails
gapi.drive.realtime.loadAppDataDocument(onFileLoaded, initializeStorageModel, handleErrors);
} else {
// this call succeeds
gapi.drive.realtime.load(fileId, onFileLoaded, initializeStorageModel, handleErrors);
}
Variables being used before this point (passed to google for the access token):
LOAD_APIS = 'auth:client,drive-realtime,drive-share';
SCOPE = [
'https://www.googleapis.com/auth/drive.appdata',
'https://www.googleapis.com/auth/drive.file'
];
LOAD_CLIENT_APIS = ['drive', 'v2'];
Does anyone know how to get the method realtime.loadAppDataDocument to work?
Update: I think the request may be actually receiving a 401 response (but because the CORS header isn't sent with the 401 response the Access-Control-Allow-Origin error is called)
Google pushed some changes to the Realtime API which has fixed the problem.