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:
Related
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:
If I make a document in Google drive and type some text, I can later go to file => Publish to the Web and get a link to a public webpage-style of the google doc, along with an embed link.
This is how its done manually. How can I do this automatically with a Node.JS server script (for example, using a Service Account) using the Goolgle Drive API? I couldn't find anything about this particular thing in their docs, is this possible? DO I need to make a google script instead? Is it even possible with that?
You want to publish the Google Document to web using googleapis with Node.js.
You want to retrieve the published URL.
You want to achieve this using the service account.
You have already had the service account and been able to use Drive API.
From your question and replying comments, I could understand like this. If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
Usage:
In order to use the following sample script, please do the following flow.
Prepare a Google Document.
In this case, as a test case, please create new Google Document to your Google Drive.
Share the created Google Document with the email of the service account as the writer.
Retrieve the file ID of the Google Document.
Set the variables to the following sample script.
Run the script.
In this case, "Revisions: update" of Drive API is used.
By this, the Google Document is published to the web and you can see the published URL at the console.
Sample script:
const { google } = require("googleapis");
// Please set the email and private key of service account.
const auth = new google.auth.JWT(
"### email of service account ###",
null,
"### private key of service account ###" ,
["https://www.googleapis.com/auth/drive"]
);
const fileId = "###"; // Please set the file ID.
const drive = google.drive({ version: "v3", auth });
const body = {
resource: {
published: true,
publishedOutsideDomain: true,
publishAuto: true
},
fileId: fileId,
revisionId: 1
};
drive.revisions.update(body, err => {
if (err) {
console.error(err);
return;
}
console.log(`https://docs.google.com/document/d/${fileId}/pub`);
});
Please set the private key like "-----BEGIN PRIVATE KEY-----\n###\n-----END PRIVATE KEY-----\n".
Note:
The published URL is https://docs.google.com/document/d/${fileId}/pub. In this case, the file ID is used. Because unfortunately, in the current stage, the URL like https://docs.google.com/document/d/e/2PACX-###/pubhtml cannot be retrieved by Google API.
Reference:
Revisions: update
I am using the basic Auth from laravel that you get from running the following command.
php artisan make:auth
I have an API written so that the backend on the server can update/create services and statuses. The issue i'm running into is that the Admin also has a UI on the web app and can create a service, or update its status manually. Therefore, I have an Auth level on the methods where you have to be logged in to use them.
Now when I call the method in postman it redirects me to the login page, I was wondering if there was a way around this Auth level strictly for an API?
I was told of a way to do pre-request scripts directly in postman but i'm fairly lost when it comes to the whole java script part of that and feel like there is an easier way to do it. I also already tried to do 'basic auth' with the username and password, it didnt seem to work though.
Thank you for the help in advance!
Edit: Here is the screenshot from my header.
I am presuming if you have the API in place you have an api_token set for the specific user. You can use that inside Postman in one of two ways.
You will goto the Headers tab and add:
Key: Authorization
Value: Bearer API_TOKEN_VALUE
Edited: Added the screenshot of postman
You can amend the url for the request and add the token:
url_to_api_endpoint?api_token=API_TOKEN_VALUE
On the api routes if you have ->middleware('auth:api') Laravel will read the authorization token from the header or using the query parameter and check it to the database value.
Adding the api_token to the user table
If you don't have an api_token field in your user table then add one. It is not the same as remember_token, they are different. So add to your user migration the following:
$table->string('api_token', 60)->unique();
You will need to update the users api_token using something like the following:
$user = User::find(1);
$user->update(['api_token' => str_random(60)]);
That 60 character string you will use where I put VALUE_OF_TOKEN_FROM_DB
I can't for the life of me append to my google sheet via http request. More specifically I can't seem to get the Oauth formatting right. I don't want/need a uri or prompt for permission as its just me managing my own spreadsheet. First, I was trying with just my api key, but then found out that if you're editing data you need to obtain an access token. That's when I started trying to obtain the token through oauth2 following the TERRIBLE google api documentation. That's where I hit a wall and have just about given up. It's such a simple concept, I just want to add data to my spreadsheet on drive from an online script (housed on scriptr.io), but Google yet again makes things so unneccessarily complicated and don't help matters with their convoluted, misleading, and scattered documentation. Can someone please help me in accomplishing this? Here's where I'm at or what progress I've made thus far.
I've figured out how to correctly format the call to add a row of data to the spreadsheet.
POST https://sheets.googleapis.com/v4/spreadsheets/-/values/Raw%20Data!A1:D1:append?valueInputOption=USER_ENTERED
//Header
Authorization: Bearer {oauth_token}
//Payload
{"range": "Raw Data!A1:D1","majorDimension": "ROWS","values": [["Test", "$15", "2", "3/15/2016"]]}
I know the above works because I've successfully added the data using the OAuth 2.0 Playground. However, when trying it outside of the playground (on a rest client) I keep getting errors trying to obtain the token.
POST https://www.googleapis.com/oauth2/v4/token
scope=https://www.googleapis.com/auth/spreadsheets
client_id=------&
client_secret=-----&
refresh_token=-----&
grant_type=refresh_token&
access_type=offline
I use the client id & client secret from my api console and I use the refresh token I got by authorizing the spreadsheet api in the oauth playground, but the above POST request leads to the following error
Error 400
{
"error": "unsupported_grant_type",
"error_description": "Invalid grant_type: "
}
Can someone please help me figure out how to correctly do this?
Sheets API Node.js Quickstart
I'm working on a web application that basically takes a bunch of user-submitted data from a google form that's been stored in a google sheet, pulls the data from the google sheet, and I eventually want to take that data and store it in an SQL database file so we can use the data in our program from there.
So I ran through the quickstart in the link above, it worked, awesome. I then changed their spreadsheet id to the one my google sheet has that I'm trying to pull data from:
var sheets = google.sheets('v4');
sheets.spreadsheets.values.get({
auth: auth,
spreadsheetId: '1EV8S8AaAmxF3vP0F6RWxKIUlvF6uFEmsrOFWA1oNBYI',
range: 'Class Data!A2:E',
},
Is there anything else I need to change in the quickstart code so that it will display my sheet's information? This is the link to my sheet: https://docs.google.com/spreadsheets/d/1EV8S8AaAmxF3vP0F6RWxKIUlvF6uFEmsrOFWA1oNBYI/edit?usp=sharing
and the string after the /d/ is my sheet's id.
Right now, trying to run the quickstart code with my sheet's id just produces the error: The API returned an error:
Error: Unable to parse range: Class Data!A2:E
Turns out you need to replace Class Data with the name of your sheet that you're using.. mine happened to be Form Responses 1 so when I changed it to that it worked
IF there is only one Worksheet in the Google Spreadsheet THEN
when defining your range, you can omit the Google Worksheet Name
In your example:
range: 'Class Data!A2:E',
The Google Worksheet Name is 'Class Data'.
You can find the Google Worksheet Name in the Tabs at the bottom of your Google Spreadsheet.
The default Google Worksheet Name is 'Sheet1'.