user1935724
user1935724

Reputation: 554

Delete a file using Google Drive API

The problem is similar to this post(Documents deleted using Google Docs API still visible in Google Drive can't really get it working with the solutions suggested. When we delete a file using delete() function, whether or not the file got deleted is not the question here, the problem is the file will always be visible in the web browser and can not even be removed manually. I was wondering is there a way to delete the file but also make it disappear in the web UI?

Thanks a lot.

Upvotes: 4

Views: 13430

Answers (4)

function deleteGoogleDriveFile() {
  const fileId = "yourFileId"; // *1;
  const access_token = "yourAccessToken"; // *2;
  const url = `https://www.googleapis.com/drive/v3/files/${fileId}`;
  return await fetch(url, {
    method: 'DELETE',
    headers: {
      'Authorization': `Bearer ${access_token}`
    }
  }).then(res => res.json());
}

*1 - You can find yourFileId by going to your Drive Folder -> right click on your file -> share -> copy link. In the link url will find yourFileId by extracting:

https://drive.google.com/file/d/<yourFileId>/view?usp=drive_link

*2 - You can get yourAccessToken from Google OAuth 2.0 Playground

Step1: Select & authorize APIs -> Drive API v3 -> select https://www.googleapis.com/auth/drive -> click on Authorize APIs. The Google Account Selection and Consent Popup will show up, Select your account and select Allow to process to step 2.

Step2: Exchange authorization code for tokens: select Exchange authorization code for tokens, yourAccessToken will show on the Request / Response panel.

Upvotes: 0

Lewis
Lewis

Reputation: 9

FilesResource.DeleteRequest request = service.Files.Delete(fileID);
request.Execute();

heres the 2020 fix, v3 api.

P.S: If someone could tell me how to do syntax highlighting that'd be great.

Upvotes: 0

MSD
MSD

Reputation: 322

I have used the following:

public static string DeleteFile(string id)
{
  FilesResource.DeleteRequest request = DriveService.Files.Delete(id);
  return request.Fetch();
}

I have emptied out my google drive several times using this function without issue. Let me know if this works for you.

Upvotes: 0

Mike Spear
Mike Spear

Reputation: 882

In the v3 API, you should be able to delete a file by using its id. Don't forget to call execute() on the Delete object returned by service.files().delete().

import com.google.api.services.drive.model.*;
import com.google.api.services.drive.Drive;

Drive service = ...;

com.google.api.services.drive.model.File file = ...;

service.files().delete(file.getId()).execute();

Upvotes: 5

Related Questions