How to expose a web API to a google apps script - google-apps-script

I have a google apps spreadsheet, and I want to write a script that can be accessed via any browser, will generate a response using data from the spreadsheet, and return it to the browser.
I put in a lot of data in the spreadsheet that is required for my app. I want to automate the process of getting the data from the spreadsheet and integrating into the app before creating a build. Right now I run the script manually, download the result, and copy it into the app's data folder.
Ideas?

You can interact with your script via HTTP Post
doPost Trigger
Here is a little example of a doPost function
function doPost(e){
return ContentService.createTextOutput(SpreadsheetApp.openById(id).getSheetByName(name).getDataRange().getValues())
}

Related

How to call an API running locally from Apps Script

I am building a Container Bound Script using AppsScript wrt Google Sheets.
I am taking input by adding a menu on the google sheet as shown below,
And when clicked, prompted with a HTML form, in which we can upload a PDF, which is saved on Google Drive and the information regarding the file upload in saved on the google sheets, but I also want to send to a FastAPI running locally on my machine.
File Information stored on Google Sheets
Code for saving on Google Drive
function uploadFilesToGoogleDrive(data,name,type){
var datafile = Utilities.base64Decode(data)
//create a new blob with decode data, name, type
var blob2 = Utilities.newBlob(datafile, type, name);
var folder = DriveApp.getFolderById("<url>");
//Create new file (property of final user)
var newFile = folder.createFile(blob2);
var rowData = [
newFile.getName(),
newFile.getUrl(),
newFile.getDateCreated()
];
SpreadsheetApp.getActive().getSheetByName("sheet1").appendRow(rowData);
return newFile.getUrl()
}
For sending data to external API I came across Run app script function from website/localhost and Upload files from google drive to external api using google apps script
I am not getting a method through which I can send to API running locally without localtunnel.
It's not possible to run a Google Apps Scripts project locally, Google Apps Scripts projects run on Google Servers.
You can find more information here.
In your case, the only viable way I can think of for you to can call an API being served locally, would be to expose the appropriate endpoints from your API to the web. That way, the Google Servers responsible to run your script will have access to your API.
I understand that perhaps this solution is against the purpose of having an API server locally (since it won't be locally anymore), however Google Apps Script is designed to work on the Cloud.
In any case, you may find the Apps Script Class UrlFetchApp useful for making HTTP requests for your own API of any other.

How to make a button in a Google Apps Script web app that executes a function in that project?

I would like publish a web app coded in Google Apps Script in a Google Page that has a button that runs a certain function within that Apps Script project. It is assumed that only my Google Account would use that button and my goal is to create and process spreadsheets when the button is pressed (creating a new spreadsheet using data from another one).
How to do this? I managed to deploy and publish a web app and I've also managed it's interaction with a given spreadsheet (displaying data from a sheet so far). My issue is that I do not know where to start with coding a button that does things.
I believe your goal as follows.
You want to create new Spreadsheet when a button on Web Apps, which was created by Google Apps Script, is clicked.
From My issue is that I do not know where to start with coding a button that does things., you want to know the method for achieving above process.
In this case, I think that google.script.run can be used. When google.script.run is used, the communication between HTML side and Google Apps Script side can be run.
As a simple script for achieving above goal, I would like to introduce as follows.
Sample script:
HTML&Javascript side: index.html
Please copy and paste the following script to the script editor as index.html.
<button onclick="sample()">Create Spreadsheet</button>
<script>
function sample() {
google.script.run.createSpreadsheet();
}
</script>
In this case, when a button is clicked, sample() is run.
Google Apps Script side: Code.gs
Please copy and paste the following script to the script editor as Code.gs.
function doGet() {
return HtmlService.createHtmlOutputFromFile("index");
}
function createSpreadsheet() {
// do something for "creating a new spreadsheet using data from another one"
SpreadsheetApp.create("sample name");
}
From I managed to deploy and publish a web app and I've also managed it's interaction with a given spreadsheet (displaying data from a sheet so far)., I think that you have already been able to deploy the Web Apps.
In this sample script, when you open the Web Apps, you can see a button. When you click the button, google.script.run.createSpreadsheet() is run. By this, createSpreadsheet() at Google Apps Script side is run. As the result, new Spreadsheet is created. (In this case, the created Spreadsheet is put to the root folder.)
Note:
When you modified the script of Web Apps, please redeploy the Web Apps as new version. By this, the latest script is reflected to the Web Apps. Please be careful this.
I think that the various sample scripts using google.script.run can be seen at Stackoverflow. These are useful for understanding how to use it.
References:
Class google.script.run
Web Apps

Authorizing Google Charts to access private spreadsheets

I am trying to create a Web App using Google Apps Script to query data from my Google Sheet using Google Charts.
I have been able to successfully query the spreadsheet when the Google Sheet is publicly shared, however since the spreadsheet contains confidential info I would rather do it privately using authorizations.
The reason why I want to use Google Charts visualisation functions (as opposed to the server side Spreadsheet App) is because of the speed of querying large data sets.
I have tried following the steps in the above documentation. That is, creating a client id then using the gapi.auth library to authenticate myself but I continue to receive an error.
When i add the authorization library and first part of the code from the documentation (with console.log simply to see where it get's up to):
<script src="https://apis.google.com/js/auth.js?onload=init"></script>
<script>
var clientId = '1234.apps.googleusercontent.com';
var scopes = 'https://spreadsheets.google.com/feeds';
function init() {
console.log("here");
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true},handleAuthResult);
}
</script>
I receive the following error:
1289869776-mae_html_user_bin_i18n_mae_html_user.js:41 dropping
postMessage.. was from unexpected window
Any guidance is appreciated.
Since you are creating your web app using Google Apps Script, it's not necessary to "authorize Google Charts to access private charts" because you could use Google Apps Script services and methods to get the data from the spreadsheets and pass them to Google Charts.
On Converting from UiApp + Chart Service to Html Service + Google Visualization API it's shown how to convert the old dashboard example from from UiApp + Chart Service to HtmlService + Google Visualization API. This illustrates how to create a Google Apps Script web app that builds a chart from Google Spreadsheet data without "requiring authorization" as it's "implicitly" handled by Google Apps Script.
From the above link
Two functions cooperate to retrieve the dashboard’s data and display it. As soon as the visualization API is loaded, the sendQuery() function is invoked. Using the google.script.run facility, it sends its request to the server-side getSpreadsheetData() function. This is an asynchronous operation, so two callbacks are provided, a successHandler and a failureHandler. One or the other will receive the result of the server call, depending on the outcome.
H/T to jfllmartin, author of an answer to Converting my google dashboard app from the UI service to the HTML service where the above link was shared.
Related
How to create google dashboard including piechart and range select filter from a spreadsheet?
Display Spreadsheet data in Sites with Html Service
can I suggest you change from using Google sheets to using firebase with Google sheets or just Firebase, and then with Google appscript in the back end.
I often use a Google script to problematically update Firebase with data from the Google sheet. I then enjoy the speed and security of Firebase to deliver a super fast user experience.
There are two go to pages for using Firebase in appscript. The example page and the quick start.
Furthermore, I gave up using Google's own charting library and starting using high charts or chartJS, as they are more accessible.

Crud Webapp Google Apps Script

Is it possible create Crud Webapp with Google Apps Script. I need to create a web table able to update and get values from Google spreadsheet?
yes its possible, you can insert, update a row, delete and retreive a row using google app scripts
try this link https://github.com/AishwaryT/Google-app-script-crud
let me know if you face any problem.
Yes absolutely it is possible.
Write a code in Google app script for CRUD operation over the Google spreadsheet (like Insert, Update, delete). accept the parameters using doGet() / doPost() method to insert/update data into the Google spreadsheet and return the updated data or any response in the JSON/XML or in the string format, deploy your app script (with "anyone even anonymous"), copy the URL of the deployed script and call to that URL from your your web application (in java script AJAX call) and get response from app script to your application.
Reference :https://developers.google.com/apps-script/

Calling Google Apps Script Gadget from custom Google Gadget?

Using a Google Site with an embedded Google Apps Script, I'm displaying some data from a database using JDBC. The Google Apps Script uses doGet to load an HTML page:
function doGet() {
return HtmlService.createHtmlOutputFromFile('index');
}
...the index.html page in turn calls a function in my Apps Script to get some database data:
google.script.run.withSuccessHandler(mySuccessHandler).getSomeDBData();
When the mySuccesshandler is called, I render the data with the JQuery.
This works. However, embedded Google Apps Scripts have a statically defined height. A post on SO suggested developing a custom Google Gadget which dynamically resizes when content changes.
But I can't find any examples, or confirmation that I can port my current Google Apps Script to my own Gadget. The documentation on working with remote content doesn't mention databases.
I tried placing the call to my App Script in the Gadget XML file:
google.script.run.withSuccessHandler(mySuccessHandler).getSomeDBData();
However, this failed with cannot call run of undefined. So is there any way I can call a GAS from a custom Google Widget?
You cant mix them like that, they are different and disconnected (for example how would the xml gadget know which apps script to call in your attempt?).
The easiest would be to use the apps script solely as a data provider like json from a contentService in doGet. From the xml gadget you do an ajax get to the apps script published url & any needed parameters.
To avoid auth hassles publish script to run as you with anonymous access.