Failed in getting the downloadUrl property of files in Google Drive with python API

1.7k views Asked by At

I want to obtain the direct download link of a certain file on Google Drive and I used Google API Client for python and here's a part of my codes, which basically is the copy of the quickstart example:

SCOPES = "https://www.googleapis.com/auth/drive"
FILE_ID = "xxxxxx"


def get_credentials():
    ...
    return credentials

if __name__ == '__main__':
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build("drive", "v3", http=http)

    web_link = service.files().get(fileId=FILE_ID, fields="webContentLink").execute() # success
    download_link = service.files().get(fileId=FILE_ID, fields="downloadUrl").execute() # throw an error

Then I got the 400 error:

googleapiclient.errors.HttpError: <HttpError 400 when requesting https://www.googleapis.com/drive/v3/files/xxxxxx?alt=json&fields=downloadUrl returned "Invalid field selection downloadUrl">

I searched and read all related questions about this problem. As one said in this question:

The difference between this downloadURL and the webContentLink is that the webContentLink uses authorization from the user's browser cookie, the downloadURL requires an authorized API request (using OAuth 2.0).

So I thought maybe I didn't authorize the request successfully. However the first three statements in main part, did it for me according to the guide:

Use the authorize() function of the Credentials class to apply necessary credential headers to all requests made by an httplib2.Http instance ... Once an httplib2.Http object has been authorized, it is typically passed to the build function

So what's wrong with my program? And if I want to write my own request with urllib or requests to reproduce the error, how?

1

There are 1 answers

2
danielx On BEST ANSWER

downloadURL is a field that is available for File resources in the Google Drive API version 2 but not version 3 which you seem to be using.

In Google Drive API v3 the field has been replaced by doing a files.get with ?alt=media request to directly download a file without having to find out the specific URL for it. You can read more about the differences and changes between API v2 and v3 here.

Here is an example of how you can download files using the python Google API client library with Google Drive API v3:

file_id = '0BwwA4oUTeiV1UVNwOHItT0xfa2M'
request = drive_service.files().get_media(fileId=file_id)
fh = io.BytesIO()
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
    status, done = downloader.next_chunk()
    print "Download %d%%." % int(status.progress() * 100)

Check out the official documentation regarding downloading files using the API v3 here for more examples.