I was trying to fetch data from Clearbit API and I get this message : " Exception: The parameters (String,(class),(class)) don't match the method signature for UrlFetchApp.fetch."
Before writing this post I tried to search online but couldn't find the answer.
I share with you my code :
function linkedInUrl(domain) {
let url = `https://company.clearbit.com/v2/companies/find?domain=${domain}`
const api_keys = ""
const header = {
method: 'GET',
headers: {'Authorization':'Bearer ' + api_keys}
}
options = {muteHttpExceptions: true};
var response = UrlFetchApp.fetch(url,header,options)
var data = JSON.parse(response.getContentText())
return "https://www.linkedin.com/"+data.linkedin.handle
}
function techUsed(domain) {
let url = `https://company.clearbit.com/v2/companies/find?domain=${domain}`
const api_keys = ""
const header = {
method: 'GET',
headers: {'Authorization':'Bearer ' + api_keys}
}
options = {muteHttpExceptions: true};
var response = UrlFetchApp.fetch(url,header,options)
var data = JSON.parse(response.getContentText())
tech = ""
for(let i = 0; i < data.tech.length; i++) {
tech += data.tech[i] +","
}
return tech
}
Does anyone have a clue ?
Thank you for your help.
The arguments of fetch(url, params) are url and params. I think that this is the reason for your current issue. So, please modify your script as follows.
From:
let url = `https://company.clearbit.com/v2/companies/find?domain=${domain}`
const api_keys = ""
const header = {
method: 'GET',
headers: {'Authorization':'Bearer ' + api_keys}
}
options = {muteHttpExceptions: true};
var response = UrlFetchApp.fetch(url,header,options)
To:
let url = `https://company.clearbit.com/v2/companies/find?domain=${domain}`;
const api_keys = "###"; // Please set your access token.
options = {
method: 'GET',
headers: { 'Authorization': 'Bearer ' + api_keys },
muteHttpExceptions: true
};
var response = UrlFetchApp.fetch(url, options);
Note:
In this case, your api_keys is valid value for using the API. Please be careful about this.
Unfortunately, I cannot know the response value from the API you want to use. So, if your script below var response = UrlFetchApp.fetch(url, options); occurs an error, please provide the sample value. By this, I would like to confirm your script.
Reference:
fetch(url, params)
You can try this :
function linkedInUrl(domain) {
let url = `https://company.clearbit.com/v2/companies/find?domain=${domain}`
const api_keys = ""
const header = {
method: 'GET',
headers: {'Authorization':'Bearer ' + api_keys}
}
options = {muteHttpExceptions: true};
var res
fetch(url,header,options) //api for the get request
.then(response => response.json())
.then(data => console.log('response',data))
}
Related
I have that listDevice function in a script to get the thermostat ID (same as here):
function listDevices() {
// specify the endpoint
const endpoint = '/enterprises/' + PROJECT_ID + '/devices';
// blank array to hold device data
let deviceArray = [];
// make request to smart api
const data = makeRequest(endpoint);
const deviceData = data.devices;
console.log(deviceData);
deviceData.forEach(device => {
const name = device.name;
const type = device.type;
deviceArray.push([name,type]);
});
// get the Sheet
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getActiveSheet();
// output the data
sheet.getRange(2,1,deviceArray.length,2).setValues(deviceArray);
}
It works fine with my Nest, but when trying to make it work for another person with multiple Nest thermostats, it gives this error:
TypeError: Cannot read properties of undefined (reading 'forEach')
Would you know why this script works for me, but when shared with someone it gives an error?
Here's the makeRequest(endpoint) function that is called by the function above:
function makeRequest(endpoint) {
// get the smart service
const smartService = getSmartService();
// get the access token
const access_token = smartService.getAccessToken();
//console.log(access_token);
// setup the SMD API url
const url = 'https://smartdevicemanagement.googleapis.com/v1';
//const endpoint = '/enterprises/' + PROJECT_ID + '/devices';
// setup the headers for the call
const headers = {
'Authorization': 'Bearer ' + access_token,
'Content-Type': 'application/json'
}
// set up params
const params = {
'headers': headers,
'method': 'get',
'muteHttpExceptions': true
}
// try calling API
try {
const response = UrlFetchApp.fetch(url + endpoint, params);
const responseBody = JSON.parse(response.getContentText());
return responseBody;
}
catch(e) {
console.log('Error: ' + e);
}
}
After replacing the makeRequest(endpoint) function with that one, the script works and provides me the devices ID without needing to run the listDevice function anymore:
function makeRequesttest() {
// get the smart service
const smartService = getSmartService();
// get the access token
const access_token = smartService.getAccessToken();
//console.log(access_token);
// setup the SMD API url
const url = 'https://smartdevicemanagement.googleapis.com/v1';
const endpoint = '/enterprises/' + PROJECT_ID + '/devices';
// setup the headers for the call
const headers = {
'Authorization': 'Bearer ' + access_token,
'Content-Type': 'application/json'
}
// set up params
const params = {
'headers': headers,
'method': 'get',
'muteHttpExceptions': true
}
// try calling API
try {
const response = UrlFetchApp.fetch(url + endpoint, params);
const responseBody = JSON.parse(response.getContentText());
Logger.log('response: ' + response);
return responseBody;
}
catch(e) {
console.log('Error: ' + e);
//throw e;
}
}
I am attempting to create a script that outputs a cell in the same row to discord based on a checkbox. I've written up so far the following, although I'm really not very good with javascript/Google Script. I cannot get past the auth requirements and do not see the mistake I am making.
const sheet = SpreadsheetApp.getActiveSpreadsheet()
function onEdit(e) {
var discordUrl = "Webhook";
var userName = 3
var channelMsg = userName
let checkboxColumnNo = 5
let range = e.range;
let value = range.getValue().toString();
let column = range.getColumn();
let row = range.getRow();
let sheetName = range.getSheet().getName()
if (column == checkboxColumnNo && value === "true") {userName;
}
var payload = JSON.stringify({content: "Whitelist add " + channelMsg });
var params = {headers: {'Content-Type': 'application/json','Accept': 'application/json'}, method: "POST",payload: payload,muteHttpExceptions: true};
var response = UrlFetchApp.fetch(discordUrl, params);
Logger.log(response.getContentText());
Logger.log(payload);
Logger.log(channelMsg);;
}
Just showing what my sheet layout looks like.
Comparing your code with something very similar that I've done I can only spot 1 difference which is the following:
Your code:
var params = {headers: {'Content-Type': 'application/json','Accept': 'application/json'}, method: "POST",payload: payload,muteHttpExceptions: true};
My code:
var params = {
headers: {
'Content-Type': 'application/json'
},
method: "POST",
payload: payload,
muteHttpExceptions: true
};
Difference:
In your header you have this which I don't, try removing it to see if it works.
'Accept': 'application/json'
Little bonus, here's a tool I use to make nice embedded messages for Discord:
https://leovoel.github.io/embed-visualizer/
I have a script that will post available stock adjust to Shopify but I don't know how to extend that and get the payload from cells in the sheet and ideally loop the payload so I can update more than one item at a time.
REF: https://shopify.dev/docs/admin-api/rest/reference/inventory/inventorylevel#adjust-2021-01
I want to have cells in the sheet for "location_id", "inventory_item_id", "available_adjustment" and loop these so I could have below for example.
"location_id"
"inventory_item_id"
"available_adjustment"
11594563
34516664746035
1
11595526
34516664746851
-1
11215528
34516664567861
5
11595574
34516664745685
6
This is the current script that is working but I need to manually change the payload and run one at a time where I want to be able to adjust a lot more in one hit.
var url = "https://**********.myshopify.com/admin/api/2021-01/inventory_levels/adjust.json";
var payloaddata = {
"location_id": "11594563",
"inventory_item_id": "34516664746035",
"available_adjustment": "-1"
};
var payload = JSON.stringify(payloaddata);
var username = "*********";
var password = "*********";
var response = UrlFetchApp.fetch(url, {
method: "POST",
payload: payload,
contentType: "application/json",
headers: { "Authorization": "Basic " + Utilities.base64Encode(username + ":" + password) }
});
Logger.log(response.getContentText());
var json = response.getContentText();
var data = JSON.parse(json);
Logger.log(data);
} ```
Assuming that your code is working then try this:
I also assume that you spreadsheet looks like your table with same headers and same order of columns
function shopifyPost() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('Sheet Name');
const [hA, ...rows] = sh.getDataRange().getValues();
const url = "https://**********.myshopify.com/admin/api/2021-01/inventory_levels/adjust.json";
rows.forEach((r, i) => {
let pld = {};
pld[hA[0]] = r[0];
pld[hA[1]] = r[1];
pld[hA[2]] = r[2];
let payload = JSON.stringify(pld);
let username = "*********";
let password = "*********";
let response = UrlFetchApp.fetch(url, {
method: "POST",
payload: payload,
contentType: "application/json",
headers: { "Authorization": "Basic " + Utilities.base64Encode(username + ":" + password) }
});
});
Logger.log(response.getContentText());
var json = response.getContentText();
var data = JSON.parse(json);
Logger.log(data);
}
The first line looked like this: (after stringifying it)
{"location_id":11594563,"inventory_item_id":34516664746035,"available_adjustment":1}
This is what my data sheet looked like:
location_id
inventory_item_id
available_adjustment
11594563
34516664746035
1
11595526
34516664746851
-1
11215528
34516664567861
5
11595574
34516664745685
6
I have successfully authenticated Google apps script to salesforce and can query records in Salesforce from Google apps script with the following from gsuitedevs:
function run() {
var service = getService();
if (service.hasAccess()) {
Logger.log("Success.");
var url = service.getToken().instance_url +
'/services/data/v24.0/chatter/users/me';
// Make the HTTP request using a wrapper function that handles expired
// sessions.
var response = withRetry(service, function() {
return UrlFetchApp.fetch(url, {
headers: {
Authorization: 'Bearer ' + service.getAccessToken(),
}
});
});
var result = JSON.parse(response.getContentText());
Logger.log(JSON.stringify(result, null, 2));
} else {
var authorizationUrl = service.getAuthorizationUrl();
Logger.log('Open the following URL and re-run the script: %s',
authorizationUrl);
}
}
However, when I run the following code, I get a 401:
function updateQuoteUrls3() {
var service = getService();
var accessToken = service.getAccessToken();
var quoteId = "a1Gf200000GkZex"; // ID
var folderUrl = "https://drive.google.com/drive/folders/DEFXXX"; // Google_Drive_Folde_URL__c
var sheetUrl = "https://docs.google.com/spreadsheets/d/XXX";
var instanceUrl = "https://na53.salesforce.com";
var queryUrl = "/services/data/v25.0/sobjects/i360__Quote__c/" + quoteId + ".json";
var payload = {
"Google_Drive_Folde_URL__c": folderUrl,
"Pricing_Sheet_URL__c": sheetUrl
};
var headers = {
Authorization: 'Bearer ' + service.getAccessToken(),
"Content-Type": "application/json"
};
var options = {
"method": "patch",
"contentType": "application/json",
"headers": headers,
"payload": JSON.stringify(payload)
};
var url = instanceUrl + queryUrl;
var response = UrlFetchApp.fetch(url, options);
return response; // HTTPresponse - https://developers.google.com/apps-script/reference/url-fetch/http-response
}
I cannot figure out why I am getting the following error:
returned code 401. Truncated server response: [{"message":"This session is not valid for use with the REST API","errorCode":"INVALID_SESSION_ID"}] (use muteHttpExceptions option to examine full response)
I new to this, have searched for hours, but have come up with nothing so far. Help is greatly appreciated.
I've been searching how to do this, but i didn't find anything. After a while, i came up with the script i'll post as an answer.
I'm posting this for myself and anyone who might find it useful.
You'll need to get a dropbox access token, that can be obtained after creating a dropbox app.
function send2dropbox(file) {
var dropboxTOKEN = 'XXXxxx';
var path = '/somePath/' + file.getName();
var dropboxurl = 'https://api.dropboxapi.com/2/files/save_url';
var fileurl = 'https://drive.google.com/uc?export=download&id=' + file.getId();
var headers = {
'Authorization': 'Bearer ' + dropboxTOKEN,
'Content-Type': 'application/json'
};
var payload = {
"path": path,
"url": fileurl
}
var options = {
method: 'POST',
headers: headers,
payload: JSON.stringify(payload)
};
var response = UrlFetchApp.fetch(dropboxurl, options);
return response;
}
You can find an example HERE