How to migrate google sheets API v3 to google sheets Api v4 - javascript

I've been using a public google spreadsheet as a JSON endpoint for several of my web projects for some time now. I liked this approach because I could retrieve data from a public spreadsheet without needing any kind of authentication or tokens to get the data, all I needed to do was publish the spreadsheet and then fetch from a simple URL:
fetch(`https://spreadsheets.google.com/feeds/${mode}/${id}/${sheetNum}/public/values?alt=json`).then((res)=>console.log(res));
Google is deprecating sheets v3, and I'm confused about how to migrate to v4. From this answer I gather that I need to provide an access token which is created via the google cloud console. But do I need to create some kind of special "app" or "workplace" or will any old API token do? I tried the following:
Create a GCP project
Enable Google Sheets API
Hit Create Credentials
fetch data using the following URL scheme:
fetch(https://sheets.googleapis.com/v4/spreadsheets/SPREADSHEET_ID/values/RANGE?key=API_KEY)
But this is giving me a 403 response.

You are using the JSON Alt Type variant of the Google Data protocol. This protocol is dated and appears to no longer work reliably. The GData API Directory tells:
Google Spreadsheets Data API: GData version is still live. Replaced by the Google Sheets API v4.
Google Sheets API v4 is a modern RESTful interface that is typically used with a client library to handle authentication and batch processing of data requests. If you do not want to do a full-blown client implementation, David Kutcher offers the following v4 analog for the GData JSON Alt Type, using jQuery:
GData (old API, not recommended):
var url = 'https://spreadsheets.google.com/feeds/list/' +
spreadsheet_id + '/' + tab_ordinal + '/public/values?alt=json';
($.getJSON(url, 'callback=?')).success(function(data) {
// ...
};
V4 (new API, recommended):
var url = 'https://sheets.googleapis.com/v4/spreadsheets/' +
spreadsheet_id + '/values/' + tab_name +
'?alt=json&key=' + api_key;
($.getJSON(url, 'callback=?')).success(function(data) {
// ...
};
...where:
spreadsheet_id is the long string of letters and numbers in the address of the spreadsheet — it is the bit between /d/ and /edit
tab_ordinal is number of the sheet — the first sheet that appears in the tab bar is sheet number 1, the second one is 2, and so on
tab_name is the name of the sheet, i.e., the name you see in the tab bar at the bottom of the window when you have the spreadsheet open for editing
api_key is the API key you get from from Google Cloud Platform console
Note that the JSON output format differs between the two versions.
The old GData JSON Alt Type variant API requires that the spreadsheet is made public through File > Publish to the web. V4 requires that the file is shared with "anyone with the link can view" through File > Share.

FINDINGS
The URL scheme produces the error 403 because mostly likely the spreadsheet file isn't shared publicly like this:
I can also replicate the 403 error when my test sheet isn't shared publicly using the same URL scheme:
RECOMMENDATION:
You can double check the spreadsheet file you're accessing and check it's sharing permission, making sure it's set to Anyone with the link:
TEST RESULT
Publicly shared test sheet
After setting up the spreadsheet file's sharing permission to Anyone with the link using the same v4 URL scheme:

Related

How to Use or Create Hmac SHA256 in Online Excel Typescript Editor

We have a weather station that sends all its data to the manufacturers servers and allows API calls.
I have stumbled my way through creating a google apps script that successfully retrieves current weather conditions every 15 minutes and populates it in to a google spreadsheet. But we are wanting to use Microsoft Power BI to do analysis of this data for various reasons. So for ease of compatibility I want to recreate this in Microsoft Excel Online instead of having it in Google sheets.
And the part that I am stuck on is the hashing of certain collected parameters that the servers require for authentication. Specifically the Hmac SHA256 part. In Google App Script I have this:
var APISignature = Utilities.computeHmacSha256Signature(StringToHash,APISecret);
APISignature = APISignature.map(function(e) {return ("0" + (e < 0 ? e + 256 : e).toString(16)).slice(-2)}).join("");
(Which thankfully I was able to find online and to be honest I do not fully understand the mapping part of it)
Is there similair method or function that is available in Online Excel Typescript?

Binance API with Google Script

I am attempting to pull my trade history from Binance (using signed endpoint security) into google sheets so that I can keep records of all my trades using google scripts. I am stuck where I can't pull the data using the api keys. The below snippit is as far as I could get from my understaning of the Binance API and UrlFetchApp API.
var data = UrlFetchApp.fetch("https://api.binance.com/api/v3/myTrades", {headers : apiKey})
I also have found this post.
Binance API Website
You can't add the header in the url bar.
EDIT I see you are using UrlFetchApp. In that case, the correct syntax is
var headers = {'X-MBX-APIKEY': apiKey}
UrlFetchApp.fetch("https://api.binance.com/api/v3/myTrades", {'headers': headers})

Google Sheets API returns 404

I am following the Google Docs API for javascript example to the letter, and got the basic example working. I have an api key, a secret token and I have set which ip addresses can access the data (http://localhost).
The demo works, it shows an auth button and after authenticating I can download google's example data using:
// google data example
var sheetId = "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms"
// load and show data
gapi.client.sheets.spreadsheets.values.get({
spreadsheetId: sheetId,
range: 'Class Data!A2:E',
}).then(function(response) {
console.log("loaded data " + response);
});
The problem is that if I replace the sheet id with the id of my own google docs sheet, I get Failed to load resource: the server responded with a status of 404.
I have even made my own sheet public. You can view it straight in any browser without even logging in. But even then I can't load the data using the API! (I don't want my sheet to be public though).
What step am I missing to connect to my own data?
To actually make the Sheets Quickstart work for your own spreadsheet, make sure you've done these things:
Start a local webserver like python -m SimpleHTTPServer 8080 so you actually have a connection to the internet.
Provide the correct SpreadSheet ID
Provide the correct sheet name, as well as sheetname in A1Notation.
Provide the correct sheet range in A1 Notation.
(I also removed the API KEY variables)
And here's the screenshot that I got it working:

Google Maps API without key?

How do you utilize Google Maps v3 API without the key? I've seen it in this example but cannot figure out what specifically is causing it not to error out.
Edit: In case someone suggests it, the other answers on this topic on StackOverflow are outdated and no longer applicable.
A key is now required. Previously it wasn't required and sites that used the API without a key prior to June 22, 2016 have been grandfathered to allow them to continue to work.
See this blog post for additional information (relevant text below):
As of June 22, 2016 we are making the following changes to the Google Maps APIs Standard Plan:
We no longer support keyless access (any request that doesn't include an API key). Future product updates are only available for requests made with an API key. API keys allow us to contact developers when required and help us identify misbehaving implementations.
We have implemented a simple 25,000 map loads per day free limit to new Google Maps JavaScript API, Static Maps API, and Street View Image API implementations. The confusing 90-consecutive-day grace period for these APIs is being retired on October 12, 2016. With this change, developers can predictably plan for growth while media sites and US nonprofits can request more quota at no charge via our dedicated support programs.
We have reduced the daily map load maximum limit you can purchase for Google Maps JavaScript API, Static Maps API, and Street View Image API from 1,000,000 to 100,000 requests per API.* We believe higher-volume developers are best served with a Premium Plan license, which includes technical support and a Service Level Agreement, and with this change we've also created consistency between Standard Plan quotas across our maps and web service APIs.
We now count Google Maps JavaScript API client-side requests towards the daily limit of the associated web service API.*
The new policies will apply immediately to all Maps API implementations created on or after June 22nd, 2016.
Existing applications have been grandfathered based on their current usage to ensure that they continue to function both now and in the future. We will also be proactively contacting all existing API key users who, based on usage growth patterns, may be impacted in the future. If you’re an existing user, please take the time to read our Policy Update for Standard Plan summary for details on how each of these changes might affect your implementation.
Indeed the link you posted http://www.birdtheme.org/useful/v3largemap.html works without key (there is just a warning in the console).
It looks like Google is whitelisting some domain names to allow the use of API without key.
I tried to use the Google Maps API v3 to display OpenStreetMap tiles but it produces a "Google Maps API error: MissingKeyMapError" on my localhost while it is working on this site without API key: http://harrywood.co.uk/maps/examples/google-maps/apiv3.html
On most websites that don't use an API key, there is an error that prevent the use of Google Maps but you can bypass this censorship.
Solution if you don't own the server using Google Maps API without key:
Block the HTTP request sending the error with an addon like AdBlockPlus and the rule http://maps.googleapis.com/maps/api/js/AuthenticationService.Authenticate?*
This will give you access to Google Maps API tiles, markers, infoWindow popup...
But if you want to use the Geocoding API, you also have to remove your HTTP referer header with a browser addon like "Modify Headers".
Solution to add in your web page so every visitors can access Google Maps API without key:
Below is a JavaScript hack I created to use Google Maps API V3 without key and bypass the error message.
// hack Google Maps to bypass API v3 key (needed since 22 June 2016 http://googlegeodevelopers.blogspot.com.es/2016/06/building-for-scale-updates-to-google.html)
var target = document.head;
var observer = new MutationObserver(function(mutations) {
for (var i = 0; mutations[i]; ++i) { // notify when script to hack is added in HTML head
if (mutations[i].addedNodes[0].nodeName == "SCRIPT" && mutations[i].addedNodes[0].src.match(/\/AuthenticationService.Authenticate?/g)) {
var str = mutations[i].addedNodes[0].src.match(/[?&]callback=.*[&$]/g);
if (str) {
if (str[0][str[0].length - 1] == '&') {
str = str[0].substring(10, str[0].length - 1);
} else {
str = str[0].substring(10);
}
var split = str.split(".");
var object = split[0];
var method = split[1];
window[object][method] = null; // remove censorship message function _xdc_._jmzdv6 (AJAX callback name "_jmzdv6" differs depending on URL)
//window[object] = {}; // when we removed the complete object _xdc_, Google Maps tiles did not load when we moved the map with the mouse (no problem with OpenStreetMap)
}
observer.disconnect();
}
}
});
var config = { attributes: true, childList: true, characterData: true }
observer.observe(target, config);
This will give you access to Google Maps API tiles, markers, infoWindow popup...
For the Geocoding API, you also have to remove your HTTP referer with the HTML meta tag below.
<meta name="referrer" content="no-referrer"> <!-- don't send HTTP referer for privacy purpose and to use Google Maps Geocoding API without key -->
Starting June 11, 2018, you can no longer use GoogleMaps API without key.
source
I am able to put location indicator in websites without any api key or javascript code
I use Fancybox to show a google maps modal box very easily.
<head>
<script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/fancyapps/fancybox#3.5.6/dist/jquery.fancybox.min.css" />
<script src="https://cdn.jsdelivr.net/gh/fancyapps/fancybox#3.5.6/dist/jquery.fancybox.min.js"></script>
</head>
<body>
<a data-fancybox="" data-options="{"iframe" : {"css" : {"width" : "80%", "height" : "80%"}}}" href="https://www.google.com/maps/search/?api=1&query=centurylink+field" class="btn btn-primary">Open Modal Map</a>
</body>

How can I access Google Sheet spreadsheets only with Javascript?

I want to access Google Spreadsheets using JavaScript only (no .NET, C#, Java, etc.)
I came here and was shocked to know that there is NO API for JavaScript to access Google Sheets.
Please tell me how to access (CREATE/EDIT/DELETE) Google Sheets using JavaScript or any of its frameworks like jQuery.
I have created a simple javascript library that retrieves google spreadsheet data (if they are published) via the JSON api:
https://github.com/mikeymckay/google-spreadsheet-javascript
You can see it in action here:
http://mikeymckay.github.com/google-spreadsheet-javascript/sample.html
Jan 2018 UPDATE: When I answered this question last year, I neglected to mention a third way to access Google APIs with JavaScript, and that would be from Node.js apps using its client library, so I added it below.
It's Mar 2017, and most of the answers here are outdated -- the accepted answer now refers to a library that uses an older API version. A more current answer: you can access most Google APIs with JavaScript only. Google provides 2 (correction, 3) ways to do this today:
As mentioned in the answer by Dan Dascalescu, you can use Google Apps Script, the JavaScript-in-Google's-cloud solution. That is, non-Node server-side JS apps outside the browser that run on Google servers.
You code your apps in the Apps Script code editor, and they can access Google Sheets in two different ways:
The Spreadsheet Service (native object support; usage guide); native is easier but is generally older than...
The Google Sheets Advanced Service (directly access the latest Google Sheets REST API [see below]; usage guide)
Apps Script also powers add-ons, and you can extend Sheets UI functionality with Sheets add-ons (like these)
You can even write mobile add-ons which extend the Sheets app on Android
To learn more about using Apps Script, check out these videos I've created (most involve the use of Sheets)
You can also use the Google APIs Client Library for JavaScript to access the latest Google Sheets REST API on the client side.
Here are some generic samples of using the client library
The latest Sheets API (v4) was released at Google I/O 2016; it's much more powerful than all previous versions, giving developers programmatic access to most features found in the Sheets UI
Here is the JavaScript quickstart for the API to help you get started
Here are sample "recipes" (JSON payloads) for core API requests
If you're not "allergic" to Python (if you are, just pretend it's pseudocode ;) ), I made several videos with more "real-world" samples of using the API you can learn from and migrate to JS if desired (NOTE: even though it's Python code, most API requests have JSON & easily portable to JS):
Migrating SQL data to a Sheet (code deep dive post)
Formatting text using the Sheets API (code deep dive post)
Generating slides from spreadsheet data (code deep dive post)
Those and others in the Sheets API video library
The 3rd way to access Google APIs with JavaScript is from the Node.js client library on the server-side. It works similarly to using the JavaScript (client) client library described just above, only you'll be accessing the same API from the server-side. Here's the Node.js Quickstart example for Sheets. You may find the Python-based videos above to be even more useful as they too access the API from the server-side.
When using the REST API, you need to manage & store your source code as well as perform authorization by rolling your own auth code (see samples above). Apps Script handles this on your behalf, managing the data (reducing the "pain" as mentioned by Ape-inago in their answer), and your code is stored on Google's servers. But your functionality is restricted to what services App Script provides whereas the REST API gives developers much broader access to the API. But hey, it's good to have choices, right? In summary, to answer the OP original question, instead of zero, developers have three ways of accessing Google Sheets using JavaScript.
Here's the Gist.
You can create a spreadsheet using the Google Sheets API. There is currently no way to delete a spreadsheet using the API (read the documentation). Think of Google Docs API as the route to create and look-up documents.
You can add/remove worksheets within the spreadsheet using the worksheet based feeds.
Updating a spreadsheet is done through either list based feeds or cell based feeds.
Reading the spreadsheet can be done through either the Google Spreadsheets APIs mentioned above or, for published sheets only, by using the Google Visualization API Query Language to query the data (which can return results in CSV, JSON, or HTML table format).
Forget jQuery. jQuery is only really valuable if you're traversing the DOM. Since GAS (Google Apps Scripting) doesn't use the DOM jQuery will add no value to your code. Stick to vanilla.
I'm really surprised that nobody has provided this information in an answer yet. Not only can it be done, but it's relatively easy to do using vanilla JS. The only exception being the Google Visualization API which is relatively new (as of 2011). The Visualization API also works exclusively through a HTTP query string URI.
There's a solution that does not require one to publish the spreadsheet. However, the sheet does need to be 'Shared'. More specifically, one needs to share the sheet in a manner where anyone with the link can access the spreadsheet. Once this is done, one can use the Google Sheets HTTP API.
First up, you need an Google API key. Head here:
https://developers.google.com/places/web-service/get-api-key
NB. Please be aware of the security ramifications of having an API key made available to the public: https://support.google.com/googleapi/answer/6310037
Get all data for a spreadsheet - warning, this can be a lot of data.
https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}/?key={yourAPIKey}&includeGridData=true
Get sheet metadata
https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}/?key={yourAPIKey}
Get a range of cells
https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}/values/{sheetName}!{cellRange}?key={yourAPIKey}
Now armed with this information, one can use AJAX to retrieve data and then manipulate it in JavaScript. I would recommend using axios.
var url = "https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}/?key={yourAPIKey}&includeGridData=true";
axios.get(url)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
2016 update: The easiest way is to use the Google Apps Script API, in particular the SpreadSheet Service. This works for private sheets, unlike the other answers that require the spreadsheet to be published.
This will let you bind JavaScript code to a Google Sheet, and execute it when the sheet is opened, or when a menu item (that you can define) is selected.
Here's a Quickstart/Demo. The code looks like this:
// Let's say you have a sheet of First, Last, email and you want to return the email of the
// row the user has placed the cursor on.
function getActiveEmail() {
var activeSheet = SpreadsheetApp.getActiveSheet();
var activeRow = activeSheet.getActiveCell().getRow();
var email = activeSheet.getRange(activeRow, 3).getValue();
return email;
}
You can also publish such scripts as web apps.
edit: This was answered before the google doc's api was released. See Evan Plaice's answer and Dan Dascalescu's answer for more up-to-date
information.
It looks lke you can, but it's a pain to use. It involves using the Google data API.
http://gdatatips.blogspot.com/2008/12/using-javascript-client-library-w-non.html
"The JavaScript client library has helper methods for Calendar, Contacts, Blogger, and Google Finance. However, you can use it with just about any Google Data API to access authenticated/private feeds. This example uses the DocList API."
and an example of writing a gadget that interfaces with spreadsheets: http://code.google.com/apis/spreadsheets/gadgets/
'JavaScript accessing Google Docs' would be tedious to implement and moreover Google documentation is also not that simple to get it. I have some good links to share by which you can achieve js access to gdoc:
http://code.google.com/apis/documents/docs/3.0/developers_guide_protocol.html#UploadingDocs
http://code.google.com/apis/spreadsheets/gadgets/
http://code.google.com/apis/gdata/docs/js.html
http://www.mail-archive.com/google-help-dataapi#googlegroups.com/msg01924.html
May be these would help you out..
Sorry, this is a lousy answer. Apparently this has been an issue for almost two years so don't hold your breath.
Here is the official request that you can "star"
Probably the closest you can come is rolling your own service with Google App Engine/Python and exposing whatever subset you need with your own JS library. Though I'd love to have a better solution myself.
In this fast changing world most of these link are obsolet.
Now you can use Google Drive Web APIs:
Java
PHP
Javacript
.NET
Python
Ruby
and others...
you can do it by using Sheetsee.js and tabletop.js
example from git
another Example
You can read Google Sheets spreadsheets data in JavaScript by using the RGraph sheets connector:
https://www.rgraph.net/canvas/docs/import-data-from-google-sheets.html
Initially (a few years ago) this relied on some RGraph functions to work its magic - but now it can work standalone (ie not requiring the RGraph common library).
Some example code (this example makes an RGraph chart):
<!-- Include the sheets library -->
<script src="RGraph.common.sheets.js"></script>
<!-- Include these two RGraph libraries to make the chart -->
<script src="RGraph.common.key.js"></script>
<script src="RGraph.bar.js"></script>
<script>
// Create a new RGraph Sheets object using the spreadsheet's key and
// the callback function that creates the chart. The RGraph.Sheets object is
// passed to the callback function as an argument so it doesn't need to be
// assigned to a variable when it's created
new RGraph.Sheets('1ncvARBgXaDjzuca9i7Jyep6JTv9kms-bbIzyAxbaT0E', function (sheet)
{
// Get the labels from the spreadsheet by retrieving part of the first row
var labels = sheet.get('A2:A7');
// Use the column headers (ie the names) as the key
var key = sheet.get('B1:E1');
// Get the data from the sheet as the data for the chart
var data = [
sheet.get('B2:E2'), // January
sheet.get('B3:E3'), // February
sheet.get('B4:E4'), // March
sheet.get('B5:E5'), // April
sheet.get('B6:E6'), // May
sheet.get('B7:E7') // June
];
// Create and configure the chart; using the information retrieved above
// from the spreadsheet
var bar = new RGraph.Bar({
id: 'cvs',
data: data,
options: {
backgroundGridVlines: false,
backgroundGridBorder: false,
xaxisLabels: labels,
xaxisLabelsOffsety: 5,
colors: ['#A8E6CF','#DCEDC1','#FFD3B6','#FFAAA5'],
shadow: false,
colorsStroke: 'rgba(0,0,0,0)',
yaxis: false,
marginLeft: 40,
marginBottom: 35,
marginRight: 40,
key: key,
keyBoxed: false,
keyPosition: 'margin',
keyTextSize: 12,
textSize: 12,
textAccessible: false,
axesColor: '#aaa'
}
}).wave();
});
</script>
For this type of thing you should use Google Fusion Tables. The API is designed for that purpose.

Categories

Resources