I’m having trouble updating labels on Google Drive files through the Python API. My code runs without errors but the label values don’t actually change. I’ve also tried to retrieve existing labels from files but I keep getting an “Invalid field selection labels” error.
# 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
SCOPES = ['https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/drive.labels']
# Authentication handler
def get_credentials():
token = None
if os.path.exists('token.json'):
token = Credentials.from_authorized_user_file('token.json', SCOPES)
if not token or not token.valid:
if token and token.expired and token.refresh_token:
token.refresh(Request())
else:
auth_flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
token = auth_flow.run_local_server(port=0)
with open('token.json', 'w') as file:
file.write(token.to_json())
return token
# Function to modify file label
def modify_file_label(document_id, category_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()
# Get current labels
current_labels = file_info.get('labels', [])
# Modify the specific label
for category in current_labels:
if category['id'] == category_id:
category['value'] = new_value_id
# Apply changes
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 parameters
document_id = '1pXX6SPbHuEJeO8wI8LIACbfEEItIzRIz'
category_id = 'A9438FD180'
new_value_id = '66645FBAAC'
modify_file_label(document_id, category_id, new_value_id)
I’ve verified that the file ID is correct and the file has labels applied. I’ve also re-authenticated multiple times but still can’t get it working. When I try to fetch existing labels, I get the “Invalid field selection labels” error. What am I doing wrong here?
You’re using the old Drive API v3 methods for labels - they’re deprecated. I hit this same issue last month with legacy code. The labels field doesn’t exist in the files resource anymore, that’s why you’re getting “Invalid field selection.”
You need a separate service instance for the Drive Labels API: build('drivelabels', 'v2beta', credentials=credentials). Then use drivelabels.files().listLabels(parent='files/{file_id}') to get current labels and drivelabels.files().modifyLabels() with the right request body for updates.
The request format’s completely different - structure your updates as label modifications with fieldMask parameters. Also, some operations take time to propagate across Google’s systems.
You seem to be encountering compatibility issues between the old labeling system and the newer Google Drive Labels API. The “Invalid field selection labels” error arises because the Drive API v3 does not support the labels field in the way you are attempting. I faced a similar problem recently. You should utilize the Drive Labels API separately by constructing a service using build('drivelabels', 'v2', credentials=credentials). You will need to call methods like labels().get() and files().modifyLabels(). The way to manipulate the labels is entirely different; rather than modifying the labels object directly, you must send label updates in the form of requests that include specific field masks. It’s beneficial to consult the Drive Labels API documentation for guidance on the correct request format. Your authentication scopes are appropriate, so that aspect should not hinder functionality.
you’re mixing up the old Drive API with the new Labels API. that fields='id,labels' won’t work - labels aren’t part of the files resource anymore. you’ll need to use the drivelabels service instead. call files().listLabels() to get existing labels, then files().modifyLabels() to update them. also, make sure you’re using the right label format in your request body.
Would you please gives us an example? I´ve really tried several things but none of them has worked
Hi, i´m sorry but this does not work in my case, can you guide me please? I let my code block here (I have credentials with all Scopes needed)
labels_service = build(‘drivelabels’, ‘v2beta’, credentials=creds)
labels_service.files().listLabels(parent=‘files/1jrgwRUbi5a5RLKt49y1DMIH9IGL0FZayP_TsNdUGDpQ’)
And I get the following error:
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Cell In[6], line 1 ----> 1 labels_service.files().listLabels(parent=‘files/1jrgwRUbi5a5RLKt49y1DMIH9IGL0FZayP_TsNdUGDpQ’) AttributeError: ‘Resource’ object has no attribute ‘files’
Hi! I´ve tried this option as well but I haven´t succeeded, this is my code
body_mod = {
‘labelModifications’: [
{
‘labelId’: ‘pVOqIbjTNpx3kad4CtOyHOU0KpxrmJhyif6RNNEbbFcb’,
‘fieldModifications’: [
{
‘fieldId’: ‘C4E3883519’,
‘setSingleSelectChoice’: ‘7FB5B1A9B9’
}
]
}
]
}
etiqueta_modificada = labels_service.files().modifyLabels(
name=f"files/1YQBAkXYjm158eUKMlCUqiEpYIEnVhfDHLjTjOFWALYA",
body=body_mod
).execute()
But I get this error:
AttributeError Traceback (most recent call last)
Cell In[21], line 1
----> 1 etiqueta_modificada = labels_service.files().modifyLabels(
2 name=f"files/1YQBAkXYjm158eUKMlCUqiEpYIEnVhfDHLjTjOFWALYA",
3 body=body_mod
4 ).execute()
AttributeError: ‘Resource’ object has no attribute ‘files’
It seems that I can´t see this methods within this services (drive and labels) versions, could you please help me to know if I am doing something wrong? Thanks in advance