How to parse API data into google sheets - javascript

I have an API response that I'm trying to place in my spreadsheet.
I managed to figure out how to call it using the following code but it all goes to the first cell. How do I make each value go to a different cell?
function callCandles() {
var response = UrlFetchApp.fetch("https://api-pub.bitfinex.com/v2/candles/trade:1D:tBTCUSD/hist?limit=1000&start=1577841154000&end=1606785154000&sort=-1");
Logger.log(response.getContentText());
var fact = response.getContentText();
var sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange(1,1).setValue([fact])
}

This is the correct way to set the values in a sheet. Avoid using for loops with appendRow. It can be extremely slow for a relatively small amount of data.
Suggested solution:
function myFunction() {
var response = UrlFetchApp.fetch("https://api-pub.bitfinex.com/v2/candles/trade:1D:tBTCUSD/hist?limit=1000&start=1577841154000&end=1606785154000&sort=-1");
var fact = JSON.parse(response.getContentText());
var sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange(sheet.getLastRow()+1,1,fact.length,fact[0].length).setValues(fact);
}

Try something like this,
var response = UrlFetchApp.fetch("https://api-pub.bitfinex.com/v2/candles/trade:1D:tBTCUSD/hist?limit=1000&start=1577841154000&end=1606785154000&sort=-1");
Logger.log(response.getContentText());
var fact = JSON.parse(response.getContentText());
var sheet = SpreadsheetApp.getActiveSheet();
fact.forEach(row => {
sheet.appendRow(row);
});
Hope you got some idea.

Related

How to add if and date in google script

I am a beginner with code script. Can you help me with my function please?
I have bot and he send data to google sheets, he send name, phone, date and method of communication. I need that google sheets write in column C date when was get the data from phone. I only now get the date, but in addition i need if - else. "If the column C is not empty send their date since last request", in addition i think I need to add method forEach and method so that the data is updated automatically when phone is received. For this I think need trigger "doGet(e)" from google documentation
(spread sheet image)
Data get from webhook
Here is my code:
function getDate() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var numbers = ss.getActiveSheet().getRange("B2:B1000")
let dateGoogle = new Date();
var rr = ss.getActiveSheet().getRange("C1:C1000").setValue(dateGoogle);
}
Just in case. If you're able to run the function getDate() and all you need is to make it to fill cells in C column only for rows that have filled cells in B column it can be done this way:
function getDate() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var range = ss.getActiveSheet().getData();
var data = range.getValues();
let dateGoogle = new Date();
data.forEach(x => x[2] = (x[2] == '' && x[1] != '') ? dateGoogle : x[2]);
range.setValues(data);
}
If you ask how to run the function getData() via doGet() I have no answer.
Using a doPost()
function doPost(e) {
Logger.log(e.postData.contents);
Logger.log(e.postData.type);
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName("Sheet1");
let data = JSON.parse(e.postData.contents);
let row = [];
['name','phone','date','method'].forEach(k => row.push(data[k]));
Logger.log(JSON.stringify(row))
sh.appendRow(row);
}
Below function Simulate what I imagine the bot can do to send data. This one is sending the data as JSON.
function sendData(obj) {
const url = ScriptApp.getService().getUrl();
const params={"contentType":"application/json","payload":JSON.stringify(obj),"muteHttpExceptions":true,"method":"post","headers": {"Authorization": "Bearer " + ScriptApp.getOAuthToken()}};
UrlFetchApp.fetch(url,params);
}
function saveMyData() {
sendData({name:"name",phone:"phone1",date:"date1",method:"post"});
}
You will have to Deploy the doPost(e) as a webapp.

Put variable name in JSON Array (fetched by an api)

I am very new to Javascript but I will try to put this in convenient way. I am having this api where I am fetching the rank of a crypto (Ripple; currently ranked 7 and is subject to change overtime ), code below:
function myFunction() {
var url = "https://api.coinpaprika.com/v1/coins/xrp-xrp";
var XRPresponse = UrlFetchApp.fetch(url);
var XRPjson = XRPresponse.getContentText();
var XRPdata = JSON.parse(XRPjson);
var XRPrank = XRPdata.rank;
}
Now this is another function for an api where I extract other infos (having 5000+ crytos listed, including ripple)
function myXRP() {
var url = "https://api.coinpaprika.com/v1/tickers";
var response = UrlFetchApp.fetch(url);
var json = response.getContentText();
var data = JSON.parse(json);
var XRP = data[7].symbol;
// Here instead of [7], I need to put the value extracted from XRPrank above so that whenever the rank is changed I get the latest value on data.[].
If someone could please advise.
In JavaScript there are several ways to achieve what you are looking for. The following is an adaptation of your current code with what I think are the minimal changes that you have to do, 1. use return followed by XRPrank 2. Call myFunction from myXRP and replace the data index by XRPrank.
function myFunction() {
var url = "https://api.coinpaprika.com/v1/coins/xrp-xrp";
var XRPresponse = UrlFetchApp.fetch(url);
var XRPjson = XRPresponse.getContentText();
var XRPdata = JSON.parse(XRPjson);
var XRPrank = XRPdata.rank;
return XRPrank; // add this
}
function myXRP() {
var url = "https://api.coinpaprika.com/v1/tickers";
var response = UrlFetchApp.fetch(url);
var json = response.getContentText();
var data = JSON.parse(json);
var XRPrank = myFunction(); // add this
// var XRP = data[7].symbol; instead of this
var XRP = data[XRPrank].symbol; // use this
}
Resources
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions

Use GAS to Fetch URL, Then Take Screenshot (or Convert HTML to PDF/JPG)

My Goal
I am, in short, attempting to create a script that visits a list of URLs and takes a screenshot of what is on the URL. For context, my goal is to save a snapshot that shows an image is listed on free stock photo sites (like pexels.com and unsplash.com).
My Code So Far
Here is what I have so far:
function stockDatabasePDF(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('stock db');
//make the pdf from the sheet
var data = sheet.getRange('A2:A').getValues(); //these are your URLs to check
for ( var i = 0; i < data.length; i++ ) {
if ( data[i][0] !== "" ) { //this means if your data (urls) are NOT blank
var theurl = data[i][0];
var token = ScriptApp.getOAuthToken();
var docurl = UrlFetchApp.fetch(theurl, { headers: { 'Authorization': 'Bearer ' + token } });
var pdf = docurl.getBlob().setName('name').getAs('application/pdf');
}
//save the file to folder on Drive
var fid = '1eHvWjIYyOeB9MQDwovzyXxx8CEIK5aOt';
var folder = DriveApp.getFolderById(fid);
var pdfs = folder.createFile(pdf).getUrl(); //both creates the file and copies the url
}
}
Just FYI... What is in range A2:A is the URLs to the stock photo sites, for example:
https://www.pexels.com/photo/person-riding-brown-horse-3490257/
https://unsplash.com/photos/Cz_SNZZyHgI
The issue
This script seems to ALMOST work. But it runs into one of two problems:
I get a 403 response code (forbidden request)
The screenshot takes, but no images/css/etc. is included.
Here is an example of that
To Close
Any help here would be greatly appreciated. Please let me know if I left anything out or if anyone has any questions. Thank you all!

Pass variable between two functions

I want to write a app which generates a spreadsheet in my google-drive with the user input data with google-app scripts.
For doing so I have several JavaScript-functions I want to execute one after the other:
function createSpreadsheet(name){
var ss=SpreadsheetApp.create(name);
var ssID = ss.getID()
}
function writeData(data){
var s = ss.getSheets()[0];
s.getRange('A1').setValue(data);
}
which are called by the frond-end script via:
<script>
function parse_to_backend(){
var name = document.getElementById("user_name").value;
var data = document.getElementById("user_data").value;
google.script.run.createSpreadsheet(name);
google.script.run.writeData(data);
};
</script>
how can I achieve that the writeData knows ssID the ID of the spreadsheet (I can not return values to the frontend with google.script.run and parse it as an argument)?
You want to create new Spreadsheet from HTML side.
You want to put the value to the created Spreadsheet from HTML side.
In your situation, you don't want to put writeData() in createSpreadsheet(). Namely, you want to individually use both functions.
If my understanding is correct, how about this answer? Please think of this as just one of several answers.
At first, the modification point is as follows.
Modification point:
When you run the script as follows,
google.script.run.createSpreadsheet(name);
google.script.run.writeData(data);
Function of writeData() is run before the function of createSpreadsheet() is finished, because google.script.run works by the asynchronous process. In order to avoid this, in this sample script, withSuccessHandler() is used.
About the modified script, I introduce 2 patterns. Please select one of them.
Pattern 1:
In this pattern, file ID is returned from createSpreadsheet() and the value is put to the created Spreadsheet using the file ID.
Code.gs: Google Apps Script
function createSpreadsheet(name){
var ss = SpreadsheetApp.create(name);
var ssID = ss.getId();
return ssID;
}
function writeData(id, data){
var ss = SpreadsheetApp.openById(id);
var s = ss.getSheets()[0];
s.getRange('A1').setValue(data);
}
index.html: HTML and Javascript
<script>
function parse_to_backend(){
var name = document.getElementById("user_name").value;
var data = document.getElementById("user_data").value;
google.script.run.withSuccessHandler((id) => {
google.script.run.writeData(id, data);
}).createSpreadsheet(name);
};
</script>
Pattern 2:
In this pattern, file ID is saved by PropertiesService and the value is put to the created Spreadsheet using the file ID got from PropertiesService. In this case, the file ID is saved to PropertiesService. So the created Spreadsheet can be also used by other action of Javascript using the file ID got from PropertiesService.
Code.gs: Google Apps Script
function createSpreadsheet(name){
var ss = SpreadsheetApp.create(name);
var ssID = ss.getId();
PropertiesService.getScriptProperties().setProperty("ssID", ssID);
}
function writeData(data){
var id = PropertiesService.getScriptProperties().getProperty("ssID");
var ss = SpreadsheetApp.openById(id);
var s = ss.getSheets()[0];
s.getRange('A1').setValue(data);
}
index.html: HTML and Javascript
<script>
function parse_to_backend(){
var name = document.getElementById("user_name").value;
var data = document.getElementById("user_data").value;
google.script.run.withSuccessHandler(() => {
google.script.run.writeData(data);
}).createSpreadsheet(name);
};
</script>
References:
Class google.script.run
withSuccessHandler()
Class PropertiesService
If I misunderstood your question and this answer was not what you want, I apologize.

Google Scripts - How to call the correct sheet

I´m learning how to use the Google Scripts, I saw a video on the youtube and I wrote this code based on the video. It will be a dashboard, but the problem I have is: In this spreadsheet, I have more than one Sheet. How can I "tell" the code which sheet it would have to check? In my case the Sheet ID is 8.
I think this would be the only "mistake" in the code!
Thanks for helping!
function doGet() {
// Identify the spreadsheet where the data is stored.
var ss = SpreadsheetApp.openById('0AjizIuAuEzaydFlsRDRrTkZSekROaWNZNV9QbjRDdUE')
var data = ss.getDataRange();
// Create all the filters
var clienteFilter = Charts.newNumberRangeFilter().setFilterColumnIndex(1).build();
var pedidoFilter = Charts.newNumberRangeFilter().setFilterColumnIndex(2).build();
var necessidadeFilter = Charts.newCategoryFilter().setFilterColumnIndex(3).build();
var entregaFilter = Charts.newCategoryFilter().setFilterColumnIndex(4).build();
var notaconsultorFilter = Charts.newNumberRangeFilter().setFilterColumnIndex(5).build();
var notaentregadorFilter = Charts.newNumberRangeFilter().setFilterColumnIndex(6).build();
var recomendariaFilter = Charts.newCategoryFilter().setFilterColumnIndex(8).build();
var atencaoFilter = Charts.newCategoryFilter().setFilterColumnIndex(9).build();
var servicosFilter = Charts.newCategoryFilter().setFilterColumnIndex(10).build();
var entregadorFilter = Charts.newCategoryFilter().setFilterColumnIndex(11).build();
// Create all the charts
var pieChart = Charts.newPieChart()
.setDataViewDefinition(Charts.newDataViewDefinition().setColumns([11,6]))
.build();
// Create the dashboard
var dashboard = Charts.newDashboardPanel().setDataTable(data)
.bind([clienteFilter, pedidoFilter, necessidadeFilter, entregaFilter, notaconsultorFilter, notaentregadorFilter, recomendariaFilter, atencaoFilter, servicosFilter, entregadorFilter],[pieChart])
.build();
// Create the webapp and bind together the filters and charts
var app = UiApp.createApplication();
var filterPanel = app.createVerticalPanel();
var chartPanel = app.createHorizontalPanel();
filterPanel.add(clienteFilter).add(pedidoFilter).add(necessidadeFilter).add(entregaFilter).add(notaconsultorFilter).add(notaentregadorFilter).add(recomendariaFilter).add(atencaoFilter).add(servicosFilter).add(entregadorFilter).setSpacing(10);
chartPanel.add(pieChart).setSpacing(10);
// Format the dashboard layout
dashboard.add(app.createVerticalPanel().add(filterPanel).add(chartPanel));
app.add(dashboard);
return app;
}
in your code , ss comes for a spreadSheet object, which is -way of speaking - the "parent" of the included sheets.
This class (spreadsheet object) has a couple of methods to get sheets that are described in the documentation, for example getSheetByName('name of the sheet') or getSheets() which returns an array of sheet objects. In this case you can chose which one you use with getSheets()[number]

Categories

Resources