Search code examples
python-3.xgoogle-drive-apigoogle-api-python-client

How can I get the Drive API to print a description of the file?


This is the code from Google Drive v3 API example.

def main(): """Shows basic usage of the Google Drive API.""" credentials = get_credentials() http = credentials.authorize(httplib2.Http()) service = discovery.build('drive', 'v3', http=http)

results = service.files().list(q="mimeType='image/jpeg'",
    pageSize=2,fields="nextPageToken, files(id, mimeType, name, description)").execute()
items = results.get('files', [])
if not items:
    print('No files found.')
else:
    print('Files:')
    for item in items:
        print('{0} {1} {2} {3}'.format(item['id'], item['mimeType'], item['name'], item['description']))

I added description which looks like a valid attribute from the v3 documentation. I am getting this error.

print('{0} {1} {2} {3}'.format(item['id'], item['mimeType'], item['name'], item['description']))

KeyError: 'description'

I am using Python 3.0. The code from the original example can be found here - https://developers.google.com/drive/v3/web/quickstart/python#step_3_set_up_the_sample

The documentation for the files reference can be found here - https://developers.google.com/drive/v3/reference/files


Solution

  • While description is valid, not all files will have a description and if they don't the description attribute won't be returned. Try:

    for item in items:
      description = item.get('description', '')  
      print('{0} {1} {2} {3}'.format(item['id'], item['mimeType'], item['name'], description))
    

    this sets description to the attribute returned by the API if a description is set or '' (blank) if the attribute isn't set for the item.