Search code examples
pythongoogle-apigoogle-drive-apigoogle-api-python-client

python google api v3 Error on update file


I try to use google drive api v3 in python to update file on google drive using code from official google instruction.

But i receive an Error:

The resource body includes fields which are not directly writable.

How it can be solved?

Here my code i try to use:

  try:
      # First retrieve the file from the API.

       file = service.files().get(fileId='id_file_in_google_drive').execute()
       # File's new metadata.
       file['title'] = 'new_title'
       file['description'] = 'new_description'
       file['mimeType'] = 'application/pdf'

       # File's new content.
       media_body = MediaFileUpload(
               '/home/my_file.pdf',
                mimetype='application/pdf',
                resumable=True)

       # Send the request to the API.
       updated_file = service.files().update(
                fileId='id_file_in_google_drive',
                body=file,
                media_body=media_body).execute()
            return updated_file
        
  except errors:
       print('An error occurred: %s')
       return None


Solution

  • The issue is that you are using the same object as you got back from the files.get method. The File.update method uses HTTP PATCH methodology, this means that all parameters that you send are going to be updated. This object returned by file.get contains all of the fields for the file object. When you send it to the file.update method you are trying to update a lot of fields which are not updatable.

       file = service.files().get(fileId='id_file_in_google_drive').execute()
       # File's new metadata.
       file['title'] = 'new_title'
       file['description'] = 'new_description'
       file['mimeType'] = 'application/pdf'
    

    What you should do is create a new object, then update the file using this new object only updating the fields you want to update. Remember in Google Drive v3 its name not title.

    file_metadata = {'name': 'new_title' , 'description': 'new description'}
    
    updated_file = service.files().update(
                fileId='id_file_in_google_drive',
                body=file_metadata ,
                media_body=media_body).execute()