24
votes

I am working on an app using Google Drive. I want the user to be able to share files by link, setting the permissions to anyone and withLink as described in the Google Developers documentation.

However, I cannot figure out what link to share. When I share a file in the Google Drive browser interface, I see the Link to share in the format:

https://docs.google.com/presentation/d/[...]/edit?usp=sharing

A link in this format is not part of the file resource object, nor it is returned from the http call setting the permissions. I hope someone can explain to me how to get this link through the REST api?

4

4 Answers

24
votes

You can use the alternateLink property in the File resource to get a link that can be shared for opening the file in the relevant Google editor or viewer:

https://developers.google.com/drive/v2/reference/files

Update

[With API V3](https://developers.google.com/drive/api/v3/reference/files it is suggested to use the webViewLink property.

12
votes

To actually enable link sharing using Google Drive API:

drive.permissions.create({
  fileId: '......',
  requestBody: {
    role: 'reader',
    type: 'anyone',
  }
});

Get the webLinkView value using:

const webViewLink = await drive.files.get({
    fileId: file.id,
    fields: 'webViewLink'
}).then(response => 
    response.data.webViewLink
);

3
votes

In my case using the PHP Api v3, for the link to be non-empty you must define that you request this field... and if you have the right permissions:

so something like this:

$file =self::$service->files->get("1ogXyGxcJdMXt7nJddTpVqwd6_G8Hd5sUfq4b4cxvotest",array("fields"=>"webViewLink"));
1
votes

Here's a practical example on how to get the WebViewLink file property (A.K.A. File edit link):

$file = $service->files->get($file_id, array('fields' => 'webViewLink'));
$web_link_view = $file->getWebViewLink();

OR

$sheetsList = $drive_service->files->listFiles([
  'fields' => 'files(id, name, webViewLink, webContentLink)',
]);

$web_link_view = $sheetsList->current()->getWebViewLink();

Pay attention that you should load the file specifying which fields you wanna bring with it (In this case, webViewLink). If you don't do that, only id and name will be available.

In case you need to adjust the file sharing settings, this is how you do it:

$permissions = new \Google_Service_Drive_Permission();
$permissions->setRole('writer');
$permissions->setType('anyone');

$drive_service->permissions->create($file_id, $permissions);

Possible values for setRole() and setType() can be found here: https://developers.google.com/drive/api/v3/reference/permissions/create