Cknu
Cknu

Reputation: 186

Obtain file content using Drive API

I'm trying to donwload a file i've uploaded to a Team Drive using the v3 method from drive().files().get() as described in documentation.
I can get the metadata, like file ID and permissions, but don't know how to access the actual binary content, e.g. to write it to a file. The file in question is a plain text file.

This is part of the code i'm using.

    request = service.files().get(fileId=file_id, supportsTeamDrives=True)
    pprint.pprint(request.to_json())
    response = request.execute()
    pprint.pprint(response)

And the response (from the pprints)
Request

{
  "uri": "https://www.googleapis.com/drive/v3/files/1CxxxxxxxxxxxxHp?supportsTeamDrives=true&alt=json", 
  "method": "GET",
  "body": null,
  "headers": {
    "accept": "application/json",
    "accept-encoding": "gzip, deflate",
    "user-agent": "google-api-python-client/1.7.8 (gzip)"
  },
  "methodId": "drive.files.get",
  "resumable": null,
  "response_callbacks": [],
  "_in_error_state": false, 
  "body_size": 0,
  "resumable_uri": null, 
  "resumable_progress": 0
}

File Metadata

{'id': '1CxxxxxxxxxxxxHp',
 'kind': 'drive#file',
 'mimeType': 'text/plain',
 'name': 'test.txt',
 'teamDriveId': 'XXXXXXXXXXXXXXX'}

I can access file metadata, but don't know how to get the file's contents, to write to a file.

I'm using the full access scope, "https://www.googleapis.com/auth/drive".

Documentation says "Gets a file's metadata or content by ID.", but it doesn't explain how.

Upvotes: 7

Views: 6065

Answers (1)

Cknu
Cknu

Reputation: 186

Ok. After trying different options, i came to a solution mixing info from different posts.

1 - The get_media() method works in v3 but is not documented anywhere (even on v2 docs). 2 - io.BytesIO dindn't work, changed to FileIO.

The result code was something like this:

request = drive_service.files().get_media(fileId=file_id)
fh = io.FileIO(filename, "wb")
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
    status, done = downloader.next_chunk()

Google Api documentation is really messy and inconsistent in so many ways.

Upvotes: 8

Related Questions