I have searched a lot for this already, and I honestly can't believe that I haven't been able to find the answer, even if it's "You can't do that".
I have created a bound Google Apps Script Project inside of a Google Sheet. That project contains a function called getVidViews source:
function getVidViews(id){
//id = k3y1hJPVavY
let res = YouTube.Videos.list('statistics',{'id':id});
return res.items[0].statistics.viewCount;
}
If I run this code from the Project Editor IDE and un-comment the line where I set id. I'm redirected to authorize oAuth scopes, and the function executes exactly how I want.
However, I want to have a spreadsheet where I have the id in cell A1 and I want to paste the result of the call in B1.
I should be able to accomplish this by pasting an id in A1 and using the formula =getVidViews(A1) in B1
When I do this, I get the error:
GoogleJsonResponseException: API call to youtube.videos.list failed
with error: The request is missing a valid API key.
I cannot figure why it is requesting an API key here, but not in the code editor. Also, I know that Google Apps Scripts create a hidden GCP project, but don't know if I can add an API key to that project for use in this instance.
Please point me in the right direction.
Custom functions only support certain services and YouTube isn't one of them.
Here's a deep dive into custom functions if you are interested.
I have created a Google Script that contains a main function I wish to call. Upon reading up on the documentation on this, I learn that, like any other API, an authorization token is required. I find and install Google's OAuth2 library directly into the Google Apps Script environment, and upon reading the documentation there, I am left asking: will the client need to login with their Google account to get an OAuth2 token, just to use my API? If not, how do I do such? (The API documentation doesn't quite explain how to accomplish this.)
I am ultimately trying to create a "Contact Us" form, in Angular, that hits this API.
How can I access the contents of a (new-style) Google sheet a JSON? My aim is to access the values from JavaScript, so I need to be able to download the JSON via HTTP.
Example: how can I download the data from this sheet as JSON?
I tried to find the answer via a web search, but ultimately failed:
Many tutorials on the web start with the instruction to find the key=... value in the url. The URL I got when I exported the sheet is https://docs.google.com/spreadsheets/d/1mhv1lpzufTruZhzrY-ms0ciDVKYiFJLWCMpi4OOuqvI/pubhtml?gid=1822753188&single=true and has no key=... in it.
The answer to "Accessing A Public Google Sheet" seems to indicate that I should try https://docs.google.com/spreadsheets/d/1mhv1lpzufTruZhzrY-ms0ciDVKYiFJLWCMpi4OOuqvI/export?format=csv&id=1mhv1lpzufTruZhzrY-ms0ciDVKYiFJLWCMpi4OOuqvI&gid=1822753188 to get a CSV version, but this does not work for me: I get a sign-in page instead of the data.
I found approaches using Google Apps Scripts, but these seem to require some user action in the browser instead of giving a download link.
If you want to use the latest API (v4), you'll need to do the following:
Generate a spreadsheets API key (see instructions below).
Make your sheet publicly accessible.
Use a request of the form:
https://sheets.googleapis.com/v4/spreadsheets/SPREADSHEET_ID/values/RANGE?key=API_KEY
You'll then get a clean JSON response back:
{
"range": "Sheet1!A1:D5",
"majorDimension": "ROWS",
"values": [
["Item", "Cost", "Stocked", "Ship Date"],
["Wheel", "$20.50", "4", "3/1/2016"],
["Door", "$15", "2", "3/15/2016"],
["Engine", "$100", "1", "30/20/2016"],
["Totals", "$135.5", "7", "3/20/2016"]
],
}
Note that if you want to specify the entire contents of a page, an identifier such as Sheet1 is perfectly valid.
See Basic Reading for more information.
As of v4 API, all requests must be accompanied by an identifier (e.g. API key):
Requests to the Google Sheets API for public data must be accompanied by an identifier, which can be an API key or an access token.
Follow the steps in the linked document to create an API key on the credentials page.
Make sure to:
Create a new app on Google Cloud Platform.
Create a new API key.
Add the Google Sheets API. (API Manager > Dashboard > Enable API)
Note that you can still access public data without forcing the user to log in:
In the new Sheets API v4, there is no explicit declaration of visibility. API calls are made using spreadsheet IDs. If the application does not have permission to access specified spreadsheet, an error is returned. Otherwise the call proceeds.
Note that you do not need to publish the sheet to the web. All you need to do is make sure anyone with the link can access the sheet.
(I.e. when you click Create credentials on the Google Sheets API, choose Other non-UI, User data, and it says "User data cannot be accessed from a platform without a UI because it requires user interaction for sign-in." you can safely ignore that message. The API Key is all you really need, since this is public data.)
Common error messages:
The request is missing a valid API key.
You didn't include the key= param in your call.
API key not valid. Please pass a valid API key.
Google developers console
You supplied an incorrect API key. Make sure that you typed in your key correctly. If you don't have a key yet, go to the Google developers console and create one.
API Key not found. Please pass a valid API key.
Google developer console API key
Your API Key is probably correct, but you most likely didn't add the Google Sheets permission. Go to the Google developer console API key page and add the sheets permission.
The caller does not have permission
Your sheet isn't set to be publicly accessible.
I have finally (kind of) solved my problem. Just for future reference, and in case somebody else runs into the same troubles, here the solution I came up with:
To make the worksheet publicly accessible, one needs to make the worksheet publicly accessible. This is done in the Google Sheets web interface, using the menu entries File > Publish to the web ... > link > publish. It is possible to either publish the whole spreadsheet or individual worksheets.
An API to access data from Google Sheets programmatically is described on the Google Sheets API web pages. This API uses URLS of the form https://spreadsheets.google.com/feeds/.../key/worksheetId/.... Slightly oddly, the meaning of key and worksheetId seems not to be explained in the API documentation.
My experiments show that the key value can be found by taking part of the URLs used to access the sheet via the web interface (see also here). The key is everything after the /d/, until the next slash. For the spreadsheet in the question, the key is thus 1mhv1lpzufTruZhzrY-ms0ciDVKYiFJLWCMpi4OOuqvI. The worksheetId seems to be an integer, giving the position of the worksheet in the spreadsheet. For the example in the question one has to know that the sheet shown is the second worksheet, the worksheetId in this case is 2.
The API defined public and private requests. To access an exported resource without authentication, public requests must be used.
The API calls to get data from the spreadsheet are explained in the section "Retrieving a list-based feed" (click on the "Protocol" tab in the examples). The URL required extract the data from the spreadsheet in the question is
https://spreadsheets.google.com/feeds/list/1mhv1lpzufTruZhzrY-ms0ciDVKYiFJLWCMpi4OOuqvI/2/public/full
A HTTP GET request to this URL returns that data as XML. (I have not found a way to get the data as JSON.)
The usual protections agains cross-site requests make it difficult to access the data via JavaScript XML RPC calls in a web app. One way around this problem is to proxy the API calls through the web server (e.g. using nginx's proxy_pass directive).
The above steps are at least a partial solution to the problem in the question. The only difficulty is that the data is returned as XML rather than as JSON. Since the API documentation does not mention JSON, maybe it is not possible any more to extract the data in this format?
Edit: (Aug 17, 2021) With the rollout of Sheets v4, the endpoint in the original answer has been deprecated. The updated endpoint and sample script included below:
Updated solution
Credits to the original answer here.
"https://docs.google.com/spreadsheets/d/" + spreadsheetId + "/gviz/tq?tqx=out:json&gid=0";
You don't technically have to include the gid if you just want the first sheet, but you can specify another sheet if you'd like using that parameter.
Here's a sample script to retrieve values of Spreadsheet as JSON, and then parsed as header row and values.
var sf = "https://docs.google.com/spreadsheets/d/1l7VfPOI3TYtPuBZlZ-JMMiZW1OK6rzIBt8RFd6KmwbA/gviz/tq?tqx=out:json";
$.ajax({url: sf, type: 'GET', dataType: 'text'})
.done(function(data) {
const r = data.match(/google\.visualization\.Query\.setResponse\(([\s\S\w]+)\)/);
if (r && r.length == 2) {
const obj = JSON.parse(r[1]);
const table = obj.table;
const header = table.cols.map(({label}) => label);
const rows = table.rows.map(({c}) => c.map(({v}) => v));
console.log(header);
console.log(rows);
}
})
.fail((e) => console.log(e.status));
Original solution
Note: This no longer works as Sheets v3 was deprecated in August 2021.
Here's how to get the JSON using those same URL parameters:
"https://spreadsheets.google.com/feeds/list/" + spreadsheetID + "/od6/public/values?alt=json";
Creds to #jochen on the answer with the path all the way up to XML "https://spreadsheets.google.com/feeds/list/" + spreadsheetID + "/od6/public/" + sheetID;
As #jochen's answer explains, this sheetID is based on the order of the sheets in the spreadsheet.
A faster solution here is to use this https://gist.github.com/ronaldsmartin/47f5239ab1834c47088e to wrap around your existing spreadsheet.
You first need to change your sheet access to Anyone with link can View
Add the id and sheet html param to the URL below.
https://script.google.com/macros/s/AKfycbzGvKKUIaqsMuCj7-A2YRhR-f7GZjl4kSxSN1YyLkS01_CfiyE/exec
Eg: your id is your sheet id which is
1mhv1lpzufTruZhzrY-ms0ciDVKYiFJLWCMpi4OOuqvI
and your sheet which is
Sheet2
In your case you can actually see your data here as json at
https://script.google.com/macros/s/AKfycbzGvKKUIaqsMuCj7-A2YRhR-f7GZjl4kSxSN1YyLkS01_CfiyE/exec?id=1mhv1lpzufTruZhzrY-ms0ciDVKYiFJLWCMpi4OOuqvI&sheet=Sheet2
To be safe, you should deploy the code sheetAsJson.gs in the github gist above as your own in your Google Drive.
Here is the solution
Note your sheet id in the document url (don't use the published url to find the id!)
Publish your sheet, just as html page
Use the id from step 1,
and put it in this url https://spreadsheets.google.com/feeds/cells/{id}/1/public/full?alt=json
The /1 indicates the first sheet in your document
I have create automations with Zapier that get prospect informations and write it in new rows in a spreadsheet.
This new sheet is composed by :
column A : name
Column B: domain
I want to call an API that gets email : "VoilĂ Norbert" , and returns the email (or the error) into the Column C.
The Norbert API works as follow:
Make a POST request to https://www.voilanorbert.com/api/v1/
With three parameters : name, domain and token
It return JSON format with the email or an error
I have installed the importJSON code gist.github.com/chrislkeller/5719258 .
I have tried to use the Zapier WebHook, it works, but I can't write the result in my spreadsheet.
I have tried to use this script https://gist.github.com/mhawksey/1276293 in the google script, but it does not work because I don't know where to put the API URL that is need to be called.
Do you know how to call a POST API with parameters in google spreadsheet that search the parameters into the spreadsheet, and that put the JSON result into the spreadsheet
I'm not a developper (sadly). I think it could be useful for everybody that need to enrich their data into google spreadsheet using API call with parameters.
You have an Apps Script code bound to your spreadsheet. gs code runs on Google's Servers. In order to communicate with the Norbert API (Or any API), you must use the UrlFetchApp class.
https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app
And in particular, the fetch() method:
https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app#fetch(String,Object)
I want to retrieve all the user data of my domain in a spreadsheet, so far i am able to retrieve first name email id last name ,storage quota and password change when next time i log in. But I am unable to get details like Apps enabled,License,Contact Sharing,Email Routing - Google Apps Email,Email Routing - Inherit routes , Mobile Devices,Date Snapshot,Date Change,Change Comment,Action done by etc.
I am basically not able to get any API for this all i am getting some JSON or XML codes but what if i entirely want it in GAS only no other files.
Some of what you are looking for is best requested via the Admin SDK. You may want to also check out other Google Data APIs in more detail, you could put together some good reporting tools.
Many of the APIs can be used in Google Apps Script by using the UrlFetch service. There's an OAuth flow built in that service that is quite nice for OAuth 1 flows, and it's not too bad to create a decent Google OAuth 2 flow with UrlFetch as well.
Then you can make authenticated requests to those APIs and handle the responses accordingly with Apps Script.