user165222
user165222

Reputation: 173

Downloading A File with Google Drive API

I'm trying to download a file from Google Drive using the Python API. I'm looking through the documentation and I'm seeing a def that takes two args, the service instance and a Drive File instance. I'm not seeing anywhere how to create a Drive File instance to pass to the def. How is this supposed to be done? Maybe I'm just not understanding something simple here, that's a very good possibility as well...

Upvotes: 0

Views: 15915

Answers (3)

Christophe
Christophe

Reputation: 2012

I concur with Burcu's answer: the Google Drive "get" method will only return the metadata of a file. If you wish to retrieve the file's content you should then download it using its downloadUrl property, as indicated by Burcu. So: 1. get the metadata, 2. extract the downloadUrl property, and 3. download using an http request.

As to your question, the "Drive File instance to pass to the def" is actually built from the credentials, so for example:

 /**
 * Returns the credentials of the user in the session. If user is not in the
 * session, returns null.
 * @param req   Request object.
 * @param resp  Response object.
 * @return      Credential object of the user in session or null.
 */
protected Credential getCredential(HttpServletRequest req,
    HttpServletResponse resp) {
  String userId = (String) req.getSession().getAttribute(KEY_SESSION_USERID);
  if (userId != null) {
    return credentialManager.get(userId);
  }
  return null;
};

/**
 * Build and return a Drive service object based on given request parameters.
 * @param credential User credentials.
 * @return Drive service object that is ready to make requests, or null if
 *         there was a problem.
 */
protected Drive getDriveService(Credential credential) {
  return new Drive.Builder(TRANSPORT, JSON_FACTORY, credential).build();
}

For a complete explanation you can refer to: https://developers.google.com/drive/web/examples/java#putting_together_the_pieces_getting_a_complete_set_of_credentials_for_every_request

Upvotes: 2

Burcu Dogan
Burcu Dogan

Reputation: 9213

I don't know the documentation page you're mentioning but, in order to download a file, get its metadata and make an authenticated request to its downloadUrl.

f = service.files().get(fileId=file_id).execute()
resp, content = service._http.request(f.get('downloadUrl'))

Upvotes: 4

mflaming
mflaming

Reputation: 1157

You might consider trying the Temboo Python SDK, which contains simplified methods for working with Google Drive (in addition to 100+ other APIs). Take a look at https://www.temboo.com/library/Library/Google/Drive/Files/Get/

(Full disclosure: I work at Temboo.)

Upvotes: 2

Related Questions