For my Nodejs project I'm using Google drive API for file sharing. But the problem is, the URL I'm getting from API is not a shareable link. So I have to go to the drive and switch on the sharing. Is there a way to get the shareable link or switch on the sharing with the java script code? Please give me a solution for this.
The comments were very helpful indeed, this solution is for the v3 of Google Drive and the Google Doc v1. I was using jwt auth for Service Account and the alternativeLink using Drive v2 is not sharable.
I'm assuming the auth process is known and complete. I'm writing the code in blocks so using await, promises, or callbacks is reader choice
First, you need to create a document:
google.docs({version: 'v1', auth});
docs.documents.create({title: "Your Title"}, (error, response) => {
if (error) return;
//So now you have the documentId
const {data: {documentId}} = response;
});
Now with the documentId we need to add a permission to the doc. The key is to grant permission to anyone. The doc explains anyone doesn't need an email or a user.
const resource = {"role": "reader", "type": "anyone"};
drive.permissions.create({fileId:documentId, resource: resource}, (error, result)=>{
if (error) return;
//If this work then we know the permission for public share has been created
});
Now we are almost ready, we only need the URL. Gladly the sharable URL has a stable format, so we can compose it by our selves without the need for an extra request:
https://docs.google.com/document/d/${documentId}}/view
Node.js Google Api changes quickly, in case of any confusion, I'm using "googleapis": "^38.0.0",
Related
I am trying to get a simple JSON package from putting the URL of my Google spreadsheet so I can use it on my webpage; I am using my Google Cloud Console API as it is said on the documentation of the v4 Google API format, but I still get the error of "Unauthorized API"
Documentation: https://developers.google.com/sheets/api/guides/migration#v4-api
I am using this URL:
https://sheets.googleapis.com/v4/spreadsheets/SHEET_ID/values/Sheet1?key=API_KEY
My google sheet is set as published on the web. And also I am the creator of the google sheet.
What could I be missing? I am new to API's!
First Edit:
Answering the comment of ABDULLOKH MUKHAMMADJONOV
Here is the code I am using to make a GET request to the google sheet, you can see the Sheet ID is there, and also the API of the google cloud platform.
fetch("https://sheets.googleapis.com/v4/spreadsheets/1S652uS2FLVoZ1m3apb6R4H783v6GkV58HbQ6Idec5aY/values/Sheet1?key=AIzaSyCpFZ7mcqMNc6Q_bP6h1kCEfAi6c_fd8AM", {"method": "get"})
.then( (httpResponse) => {
if (httpResponse.ok) {
console.log(httpResponse.json());
return httpResponse.json();
} else {
return Promise.reject("Fetch did not succeed");
}
} )
.then(json => console.log(json.someKey))
.catch(err => console.log(err));
This code is from the Wix code editor.
The caller doesnt not have permissions
Means that the user you are authenticated as does not have permission to do what it is you are trying to do.
The method
https://sheets.googleapis.com/v4/spreadsheets/SHEET_ID/values/Sheet1?key=API_KEY
I believe is this method spreadsheets.values/get if you check the documentation you will notice that it requires authorization with one of these scopes
You appear to only be sending an api key. You need to be authorized to access that sheet. You cant access it with an API key that only grants access to public data.
Ok, so I investigated about the OAuth 2.0 authentication and authorization for using Google Sheet's REST API. I added one of the needed scopes.
But I am stuck at the point on how to do the authorization process...
I am looking at this google documentation - How to use Google OAuth 2.0 authorization
But I haven't been able to get to the answer I seek. I am stuck at the part where it says "When your application needs access to user data, it asks Google for a particular scope of access." I do now know how to code this request or to do this request through the Insomnia software.
I am trying to do the GET request with a wix testing website, and also with Insomnia, but I haven't been able to achieve it.
These are the images from Insomnia, which tell me "Invalid authorization URL"
Insomnia's OAuth 2.0 authentication parameters
Insomnia's API Query parameter
I'm a teacher and have been teaching myself enough code in order to use Apps Script. I have read about and somewhat understand the idea of OAuth and see in principle how it should be able to be used to connect the Zoom API and Sheets API in order to make an attendance taking app. However, I don't get how to do some of the basics. For example, what to put in the OAuth redirect URL when making my App. Or even how to call the Zoom API from Sheets. Can I even use Javascript in order to call it? I haven't found much online that doesn't assume the basic knowledge. Also, most of the stuff online uses JWT, but I want to be able to share it far and wide so I think I need OAuth. Anyone know of a guide or something I can use to get started?
Based on answer's suggestion, I got the following code to work on Postman. Not sure how to change it for Apps Script.
function myFunction() {
var myHeaders = new Headers();
myHeaders.append("Authorization", "Bearer eyJ0eXAiOiJKVMTIzNn0.9Ol6oPrmbzvby5ch5-okkl7FMRG465Nu_zM0MVd91Ig");
myHeaders.append("Cookie", "_zm_date_format=dd/mm/yy; cred=2AFAF4FB9881D6BE9A38BD86B63DF1CC");
var requestOptions = {
method: 'GET',
headers: myHeaders,
redirect: 'follow'
};
UrlFetchApp.fetch("https://api.zoom.us/v2/report/meetings/92672781820/participants?page_size=30", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
}
Note: Bearer changed and switched it to UrlFetchApp
I'm not familiar with the Zoom API, but in taking a quick read of the documentation it appears they support both public and private apps. If you are new to this, my recommendation would be to first create a private app using JWT and get it working for yourself; after that, you can create a public app and employ OAuth so that others can install it. If you want to stick with Apps Script, you can look into the Google Apps Script OAuth library.
After you create your app within Zoom and select JWT, it will provide you with an api key as well as app secret for your app - these are the credentials you will use in your API requests. Check out their documentation for how to make simple requests to the API using your credentials.
If you are new to APIs in general, a good place to start is to download Postman. This will enable you to test your API requests using your credentials and confirm everything is working. After you have a working request created in Postman, you can click on 'code' on the right and it will generate the Javascript code you can use to make calls to the Zoom API within Apps Script. Use Javascript - Fetch as it's the most similar to Apps Script's own UrlFetchApp class. You will have to make some minor modifications to the pasted code from Postman to get it working in Apps Script.
For writing attendance to the Google Sheet, there should be some examples online of how to parse a JSON response from an API, push it to an array, and then setValue() within the Sheet. Hopefully the above is enough to get you started.
I am trying to get a list of all files in a google team drive. The code is as follows:
drive.files.list({
auth: oauth2Client,
corpora: "teamDrive",
includeTeamDriveItems: true,
supportsTeamDrives: true,
teamDriveId: someId
}, (err, response) => {
if (err) {
console.error("The API returned an error: " + err;
return;
}
console.log(response);
});
However, this only returns files located in my own drive, and not those located in the shared drive.
I then went to files.list documentation and, using the "Try this API" box on the side, entered the exact same information (along with the same scope, https://www.googleapis.com/auth/drive), and authenticated with the same google account. This returned the files located in the team drive, as expected.
So, what am I doing wrong in my code that would cause it to not return the files in the team drive, and what changes do I have to make in order to make it work?
Found the cause and solution thanks to this issue on the github page.
Basically, the quickstart guide google provides tells you to use the package google-auth-library#0.*, which is a huge mistake. It seems as though v0.* of the google-auth-library incorrectly handles parameters that you pass, meaning they don't get included in the request. Fortunately, the googleapis package includes its own, more recent, version of google-auth-library, so you can just use that for authentication. Once that's changed, the code in my original question works as expected.
I am working on Excel Web Add-In. I am using OfficeDev/office-js-helpers library for authenticating user. Following code is working fine. But I don't know how to get user's email, user name etc.
Is there any function available in OfficeDev/office-js-helpers through which I can get user info ?
if (OfficeHelpers.Authenticator.isAuthDialog()) {
return;
}
var authenticator = new OfficeHelpers.Authenticator();
// register Microsoft (Azure AD 2.0 Converged auth) endpoint using
authenticator.endpoints.registerMicrosoftAuth('clientID');
// for the default Microsoft endpoint
authenticator
.authenticate(OfficeHelpers.DefaultEndpoints.Microsoft)
.then(function (token) {
/* My code after authentication and here I need user's info */ })
.catch(OfficeHelpers.Utilities.log);
Code sample will be much helpful.
This code only provides you the token for the user. In order to obtain information about the user, you'll need to make calls into Microsoft Graph API. You can find a full set of documentation on that site.
If you're only authenticating in order to get profile information, I'd recommend looking at Enable single sign-on for Office Add-ins (preview). This is a much cleaner method of obtaining an access token for a user. It is still in preview at the moment so it's feasibility will depend on where you're planning to deploy your add-in.
Once you have the Microsoft token, you can send a request to https://graph.microsoft.com/v1.0/me/ to get user information. This request must have an authorization header containing the token you got previously.
Here is an example using axios :
const config = { 'Authorization': `Bearer ${token.access_token}` };
axios.get(`https://graph.microsoft.com/v1.0/me/`, {
headers: config
}).then((data)=> {
console.log(data); // data contains user information
};
Can I access Google Analytics data using a service account in a client-side application? If not, are there other ways of achieving the same outcome?
Must be entirely client-side, and must not require users to authenticate (hence the desire to use a service account).
Yes you can in https://code.google.com/apis/console make sure you say that its a Service account it will give you a key file to download. With that you dont need a user to click ok to give you access.
For a service acccount to work you need to have a key file. Anyone that has access to that key file will then be able to access your Analytics data. Javascript is client sided which means you will need to send the key file. See the Problem? You are handing everyone access to your account. Even if you could get a service account to work using javascript for security reasons its probably not a very good idea.
You can use the official (and alpha) Google API for Node.js to generate the token. It's helpful if you have a service account.
On the server:
npm install -S googleapis
ES6:
import google from 'googleapis'
import googleServiceAccountKey from '/path/to/private/google-service-account-private-key.json' // see docs on how to generate a service account
const googleJWTClient = new google.auth.JWT(
googleServiceAccountKey.client_email,
null,
googleServiceAccountKey.private_key,
['https://www.googleapis.com/auth/analytics.readonly'], // You may need to specify scopes other than analytics
null,
)
googleJWTClient.authorize((error, access_token) => {
if (error) {
return console.error("Couldn't get access token", e)
}
// ... access_token ready to use to fetch data and return to client
// even serve access_token back to client for use in `gapi.analytics.auth.authorize`
})
If you went the "pass the access_token back to client" route:
gapi.analytics.auth.authorize({
'serverAuth': {
access_token // received from server, through Ajax request
}
})