I’m having trouble updating label values on files in Google Drive using Python. My code runs without errors but the label changes don’t seem to take effect.
# Required imports
import os
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
# API permissions needed
SCOPES = ['https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/drive.labels']
# Handle authentication
def get_credentials():
credentials = None
if os.path.exists('token.json'):
credentials = Credentials.from_authorized_user_file('token.json', SCOPES)
if not credentials or not credentials.valid:
if credentials and credentials.expired and credentials.refresh_token:
credentials.refresh(Request())
else:
auth_flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
credentials = auth_flow.run_local_server(port=0)
with open('token.json', 'w') as token_file:
token_file.write(credentials.to_json())
return credentials
# Function to modify file label
def modify_file_label(document_id, category_label_id, new_value_id):
credentials = get_credentials()
drive_service = build('drive', 'v3', credentials=credentials)
try:
# Retrieve file info with labels
file_info = drive_service.files().get(fileId=document_id, fields='id,labels').execute()
# Extract current labels
current_labels = file_info.get('labels', [])
# Modify the target label
for label_item in current_labels:
if label_item['id'] == category_label_id:
label_item['value'] = new_value_id
# Apply changes to file
result = drive_service.files().update(
fileId=document_id,
body={'labels': current_labels}
).execute()
print(f"Successfully updated label for file {document_id}")
except HttpError as err:
print(f"Error occurred: {err}")
# Test the function
document_id = '1pXX6SPbHuEJeO8wI8LIACbfEEItIzRIz'
category_label_id = 'A9438FD180'
new_value_id = '66645FBAAC'
modify_file_label(document_id, category_label_id, new_value_id)
I also tried to fetch the existing labels first but got an error saying “Invalid field selection labels”. The API seems to reject the labels field when I try to retrieve file metadata. Has anyone successfully worked with Drive labels in Python? What am I missing here?