I'm new to google scripts and I want to fetch data from an URL when the user is logged in. I wrote some code but when I execute it the following error appears: SyntaxError: Unexpected token: T
I know that this question has been asked before, but I can't find a solution for my issue...
function myFunction() {
var endpoint = 'rule-sets';
var url = 'https://example.com/api/'+endpoint;
var restHeaders = {
'X-Application-Key': 'f3ez1a48f06838b7238z20cff80e010bf0c42cfp',
'Authorization':'Bearer bm9scnVuMDQ4Z2FvaWpvdHBqa2Y1djA5WWavTiElV5DyYjdxb3UxNnVyMzRoNWhsISPBmXNyZDFtMCYzMDk2JjE0NjE5MDI3NTYwODI=',
}
var options = {
'method' : 'get',
'headers': restHeaders,
'muteHttpExceptions': true,
};
var urlResponse = JSON.parse(UrlFetchApp.fetch(url, options));
Logger.log(urlResponse);
Logger.log(urlResponse.data.length);
}
Looking at https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app#methods signature it looks like it will be this:
var urlResponse = UrlFetchApp.fetch(url, options);
var jsonContent = JSON.parse(urlResponse.getContentText());
Logger.log(jsonContent);
Logger.log(jsonContent.data.length);
You were parsing the return value of fetch which is an object.
Related
PasteBin JSON
I would like to get this as Object it says jsonlint is valid but parsing is not anyone help would appreciate
"Data":[{...},{...},] // structure build like this
when i try
JSON.parse(jsonparamter) <-- Uncaught SyntaxError: Unexpected token A in JSON at position 71
at JSON.parse (<anonymous>)
at <anonymous>:1:6
There are multiple levels of JSON encoded data so you will have to create a loop to decode the elements deeper in the JSON nest. Use the below code to see an example of accessing Data.Adress.Value in this dictionary
// set up urls and headers for making HTTP req
corsurl = 'https://cors-anywhere.herokuapp.com/'
jsonurl = 'https://pastebin.com/raw/vuecweML'
headerNames = ['Content-Type','Accept']
headerValues = [ 'application/json', 'application/json']
// Modular get request function that I use
function getRequest (baseRestURL, APIPath, headerNames, headerValues, callback) {
var completeRestURL = baseRestURL + APIPath
console.log('REST API URL: ' + completeRestURL)
var method = 'GET'
var url = completeRestURL
var async = true
var request2 = new XMLHttpRequest()
request2.onload = function () {
console.log('ONLOAD')
var status = request2.status // HTTP response status, e.g., 200 for "200 OK"
console.log(status)
console.log(request2.responseText)
var response = request2.responseText
return callback(response)
}
request2.open(method, url, async)
for (var i in headerNames) {
request2.setRequestHeader(headerNames[i], headerValues[i])
}
request2.send(null)
}
// Our code of interest
getRequest(corsurl, jsonurl, headerNames, headerValues, response => {
parsed = JSON.parse(response).Data //parse our data the first time, and get the data attribute from dictionary
objects = JSON.parse(parsed) // parse a second time ( as data is JSON encoded twice )
selection = JSON.parse(objects[0].Address)[0].Value // parse a third time and select an attribute
document.getElementById('result').innerHTML = selection // Add it to our html to display
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<div id='result'> Loading </div>
I am a newbie in coding.
I am trying to create a function in google app script that acts like a dictionary and pulls out the meaning of the word passed as the argument. Its using the API of oxford dictionaries but its not working. Its showing the error 403. "var response = UrlFetchApp.fetch(url,headers);" shows the error.
function Word_meaning(word){
var url="https://odapi.oxforddictionaries.com:443/api/v1/entries/en/" + word + "/regions=us";
var headers =
{
'Accept': 'application/json',
'app_id': 'abc',
'app_key': '123'
};
var response = UrlFetchApp.fetch(url,headers);
var data = JSON.parse(response.getContentText());
Logger.log(data);
}
A couple of things - why do you include the port number in the API call? My API endpoint for querying Oxford Dictionaries looks different. Also, there's a dash in "od-api".
https://od-api.oxforddictionaries.com/api/v1/entries/en/{word_id}/regions={region}
Testing the link in the address bar, I get the expected server response of "Authorization required" while the URL you provided doesn't seem to exist.
Anyway, the error pops up because the optional 'params' object for the UrlFetchApp.fetch(url, params) method is not constructed properly. The "headers" property must be contained within that object. Somewhat ambiguous here, but please read:
https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app#fetch(String,Object)
I was able to get things up and running using the code below.
function getData(word, region){
var word = word || "leprechaun";
var region = region || "us";
var wordId = encodeURI(word);
var baseUrl = "https://od-api.oxforddictionaries.com/api/v1/entries/en/{word_id}/regions={region}";
var app_id = "app_id";
var app_key = "app_key";
var headers = {
"app_id": app_id,
"app_key": app_key
};
var options = {
"headers": headers,
"muteHttpExceptions": true
};
var url = baseUrl.replace("{word_id}", wordId)
.replace("{region}", region);
var res = UrlFetchApp.fetch(url, options);
var responseCode = res.getResponseCode();
if (responseCode == 200) {
var data = JSON.parse(res.getContentText());
} else {
Logger.log(res.getContentText());
}
}
Parse.Cloud.job("syncMetadataWithContentPortal", function(request, status) {
var apikey ="49eiivmz";
var uid = "t1g4Y2jC6S";
Parse.Cloud.httpRequest({
url: 'https://api.parse.com/1/functions/getContentMetaData',
method: 'GET',
headers : {
'Content-Type': 'application/json',
'X-Parse-Application-Id':'appkey',
'X-Parse-REST-API-Key':'restapikey',
},
body: {
apiKey : apikey
}
}).then(function(httpResponse) {
Parse.Cloud.useMasterKey();
status.message(httpResponse.text);
console.log(httpResponse.text);
var contents = JSON.parse(httpResponse.text);
var contentIdCollection = [];
for (var i = 0; i < contents.length; i++) {
contentIdCollection.push(contents[i].id);
}
status.success('Content Synced');
}, function(httpResponse) {
// console.error('Request failed with response code ' + httpResponse.status);
status.error('Request failed with response code ' + httpResponse.status)
});
});
So I have a job making httpRequest to call a function getContentMetaData which requires API key as a parameter.
How do I send parameters using GET method?
I got status as :Request failed with response code 405
Please help me how to solve this. Thanks in advance.
Don't use Parse.Cloud.httpRequest to call other cloud functions, instead you should be using Parse.Cloud.run
Your problem could also be related to your headers as you appear to be using string literals instead of variable references.
I am using Freebase JS api to fetch topic details. This is a simple function for that:
function simpleTopicDetail(topicIds){
path = 'freebase/v1/topic' + topicIds;
var opts = {
'method': 'GET',
'path': path,
'params': {'filter':'/common/topic/article'}
};
var request = gapi.client.request(opts);
request.execute(onFinalSuccess);
var onFinalSuccess = function(data){
console.log(data);
//do something with data
//parsing JSON resp to get a node value.
}
}
On debugging I see, it goes to onFinalSuccess and then nothing! Skips to the end. What's wrong here?
NOTE I'm using it in conjuction with YT API. It's a sepearte function though. Can it a problem?
You are refering to the call back function before it's assigned.
Try:
function simpleTopicDetail(topicIds){
path = 'freebase/v1/topic' + topicIds;
var opts = {
'method': 'GET',
'path': path,
'params': {'filter':'/common/topic/article'}
};
var request = gapi.client.request(opts);
request.execute(function(data){
console.log(data);
//do something with data
//parsing JSON resp to get a node value.
});
}
Have tried many options to update a product in ECWID using Google Apps Script UrlFetchApp.fetch() put method but not succeeded. Following are the different ways that I've written the code and tested, but am getting different type of errors.
I guess, am missing some small thing, which am not able to figure it out. Please help me to fix this issue.
API: ECWID Products API (http://kb.ecwid.com/w/page/25285101/Product%20API#RESTAPIMethodupdateaproduct)
Method: PUT (to update the product details)
Sample Code 1:-
function updateProducts(){
var products_authkey = "xxxxxxxx";
try{
var url ="https://app.ecwid.com/api/v1/xxxxx/product?id=xxxxxxxx&secure_auth_key="+products_authkey;
var payload = {price:62755};
var options ={method:"put",ContentType:"application/json",payload:payload};
var result = UrlFetchApp.fetch(url, options);
var response = result.getContentText();
}catch(e){
Browser.msgBox(e);
}
}
Error:-
"{ "error": "OTHER", "errorMessage": "Error parsing JSON: A JSONObject text must begin with '{' at character 0" }"
Version 2:-
Tried converting the object to json stringify, but the same error.
function updateProducts_version2(){
try{
var url ="https://app.ecwid.com/api/v1/xxxx/product?id=xxxxx&secure_auth_key="+products_authkey;
var payload = {price:62755};
var payload_json = Utilities.jsonStringify(payload);
var options ={method:"put",ContentType:"application/json",payload:payload_json,muteHttpExceptions:true};
var result = UrlFetchApp.fetch(url, options);
var response = result.getContentText();
var res_code = result.getResponseCode();
var x = 1;
}catch(e){
Browser.msgBox(e);
}
}
Error:-
"{ "error": "OTHER", "errorMessage": "Error parsing JSON: A JSONObject text must begin with '{' at character 0" }"
Version 3:- (Tried passing secure_auth_key using Authorization in headers)
function updateProducts_version3(){
try{
var url ="https://app.ecwid.com/api/v1/xxxxx/product?id=xxxxx";
var payload = {price:62755};
var headers = {Authorization: 'xxxxxxx'};
var options = {headers:headers,method:"put",ContentType:"application/json",payload:payload};
var options ={method:"put",ContentType:"application/json",payload:payload,muteHttpExceptions:true};
var result = UrlFetchApp.fetch(url, options);
var response = result.getContentText();
var res_code = result.getResponseCode();
var x = 1;
}catch(e){
Browser.msgBox(e);
}
}
Error:-
{ "error": "OTHER", "errorMessage": "API key not found in request parameters" }
Also to note that, I've tried using DevHttpClient chrome plugin, it's updating properly.
Which means that there's some problem the way we're using UrlFetch. Please help me in fixing this issue...
Thanks in advance...
Credentials are needed to test this, so that's up to you. You probably need to both stringify & encode the payload. You also had incorrect capitalization on contentType, which you could check with UrlFetchApp.getRequest().
function updateProducts_version2a(){
try{
var url ="https://app.ecwid.com/api/v1/xxxx/product?id=xxxxx&secure_auth_key="+products_authkey;
var payload = {price:62755};
var payload_json = encodeURIComponent(JSON.stringify(payload));
var options ={method:"put",contentType:"application/json",payload:payload_json,muteHttpExceptions:true};
var result = UrlFetchApp.fetch(url, options);
var response = result.getContentText();
var res_code = result.getResponseCode();
var x = 1;
}catch(e){
Browser.msgBox(e);
}
}
This next version seemed to work - by suppressing the price change and using a store's ID, it mimicked a product 'get', according to the docs you referenced. This time, the error message might be indicating some level of success: "This Ecwid account doesn't have access to Ecwid API. Please, consider upgrading it."
You'll notice that the URL has been separated out, with the basic header info of product ID and auth key together.
function updateProducts_version4(){
try{
var url ="https://app.ecwid.com/api/v1/xxxx/product";
var payload = encodeURIComponent(JSON.stringify({
price:62755
}));
var headers = {id:'xxxx',
secure_auth_key: 'xxxxxxx'
};
var options = {
headers:headers,
method:"put",
contentType:"application/json",
muteHttpExceptions:true,
payload:payload
};
var request = UrlFetchApp.getRequest(url, options); // Debug: check what would be fetched
var result = UrlFetchApp.fetch(url, options);
var response = result.getContentText();
var res_code = result.getResponseCode();
var respHeaders = result.getHeaders(); ///
debugger;
}catch(e){
Logger.log(e);
//Browser.msgBox(e);
}
}
Without your creds, that's as far as I can take it... tell us how that works for you.