Create JSON.stringify payload from Google Sheets Cells - json

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

Related

Fetch data from API CLEARBIT with GOOGLE APP SCRIPTS -

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))
}

Google+Sheet+Script+JSON+Query+Salesbinder+"Login information disallowed"

Hi this question was already asked in a previous post and it was answer by Tanaike but when I'm using the suggested script I'm always getting the same error "Login information disallowed" the same problem from post (72164203) I tested this Get line
"https://APIKEY:x#mydomain.salesbinder.com/api/2.0/documents/.json?documentNumber=8006&contextId=5" in postman and it works. Here's the code I'm using but it just wont work for me any help would be greatly appreciated
function fetching() {
var USERNAME = 'API KEY';
var PASSWORD = 'x';
var url = 'https://API KEY:x#myDomain.salesbinder.com/api/2.0/documents/.json?documentNumber=8006&contextId=5"
var headers = {
"Authorization": "Basic " + Utilities.base64Encode(USERNAME + ':' + PASSWORD)
};
let response = UrlFetchApp.fetch(url, { headers });
Logger.log(response.getContentText());
}
Salesbinder API documentation available from this link"https://www.salesbinder.com/api/documents/"
Thanks
With this code I was able to get invoice data from Salesbinder API
function fetching() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Sheet1');
var InvNumber = sheet.getRange('A1').getValue();
var USERNAME = 'APIKey';
var PASSWORD = 'x';
var url = 'https://mydomain.salesbinder.com/api/2.0/documents.json?documentNumber='+InvNumber+'&contextId=5';
var headers = {
"Authorization": "Basic " + Utilities.base64Encode(USERNAME + ':' + PASSWORD)
};
let response = UrlFetchApp.fetch(url, { headers });
Logger.log(response.getContentText());
}

How to update jira status using google script?

I am new here, I am able to find how to update jira summary from google script as below :
function jiraupdate() {
var username = "username";
var password = "password";
var encCred = Utilities.base64Encode(username+":"+password);
var url = "https://{jira_host}/rest/api/2/issue/{jiraidorkey}";
var data = {"update":{"summary":[{"set":"test google script"}]}};
var payload = JSON.stringify(data);
var headers = {
"Accept":"application/json",
"Content-Type":"application/json",
"Authorization":"Basic " + encCred,
};
var options = {
"method":"PUT",
"contentType" : "application/json",
"headers": headers,
"payload" : payload
};
var response = UrlFetchApp.fetch(url, options);
Logger.log(response);
}
thanks to this post here
can anyone show me example how do i update jira status for example from todo to in-progress using google script?
i found it.
function jiraupdate() {
var username = "username";
var password = "password";
var encCred = Utilities.base64Encode(username+":"+password);
var url = "https://{jirahost}/rest/api/2/issue/{jiraidorkey}/transitions";
var data ={"transition":{"id":"221"}};
var payload = JSON.stringify(data);
var headers = {
"Accept":"application/json",
"Content-Type":"application/json",
"Authorization":"Basic " + encCred,
};
var options = {
"method":"POST",
"contentType" : "application/json",
"headers": headers,
"payload" : payload
};
var response = UrlFetchApp.fetch(url, options);
Logger.log(response);
}

Google Sheets to output variable to Discord

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/

How to transform the JSON response into a table in sheets

I'm sending a request to an API (in a Google Scripts), and I'm getting the response as a JSON text that looks like this:
[{"id":26319355,"name":"1. WAW -FIRST SESION","calendar":"Glovers
Click&Collect","duration":30,"isSeries":false,"slots":90,"slotsAvailable"
:89,"color":"#E3DE7D","price":"0.00","category":"WAW","description":"",
"calendarID":2978881,"serviceGroupID":2978881,"appointmentTypeID":10104780,
"calendarTimezone":"Europe\/Madrid","time":"2019-06-01T12:00:00+0200",
"localeTime":"June 1, 2019 12:00"},
{"id":26466803,"name":"1. WAW -FIRST SESION","calendar":"Glovers
Click&Collect","duration":30,"isSeries":false,"slots":90,"slotsAvailable"
:89,"color":"#E3DE7D","price":"0.00","category":"WAW","description":"",
"calendarID":2978881,"serviceGroupID":2978881,"appointmentTypeID":10104780,
"calendarTimezone":"Europe\/Madrid","time":"2019-06-07T14:00:00+0200",
"localeTime":"June 7, 2019 14:00"},
I want to paste this response as a table in my spreadsheet.
My script actually looks like this (where response is the response I get from the API request):
function CheckAv(row,acuityid,check,url,apiusername,apisecretkey,ss) {
var header = {
"contentType": "application/json",
"headers":{"Authorization" : " Basic " + Utilities.base64Encode(apiusername + ":" + apisecretkey)},
"method" : "GET"
}
muteHttpExceptions: true
var response = UrlFetchApp.fetch(url, header);
var data = JSON.parse(response.getContentText());
var text = response.getResponseCode();
Logger.log(text);
}
I assume it will be really easy but I can't find the solution.
You can cycle through your JSON structure and push each key and value to a specified row using the code below.
json = [{your: "JSON", data: "goes"}, {in : "here"}]
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ss.getSheets();
var sheet = ss.getActiveSheet();
var rows = [],
data;
for (i = 0; i < json.length; i++) {
for (j in json[i]) {
dataq = json[i][j];
Logger.log(dataq);
rows.push([j, dataq]);
}
dataRange = sheet.getRange(1, 1, rows.length, 2);
dataRange.setValues(rows);
}