How to update Google Drive file label through Python API

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?

had this exact same headache few months ago! the issue is youre mixing up the apis - drive v3 doesnt handle labels directly. you need to use the drivelabels api v2 beta instead. also check if your label field is actually a choice field or text field, cause the update syntax is different for each type. make sure your credentials have the right scopes too

You’re encountering this issue because the Drive API v3 doesn’t actually support the labels field in the way you’re trying to use it. The Drive Labels API is separate from the main Drive API and requires different endpoints. I ran into the same problem last year when implementing label management. You need to use the Drive Labels API specifically, not the regular Drive API. Replace your update call with the Drive Labels API endpoint: python labels_service = build('drivelabels', 'v2', credentials=credentials) # Use modifyLabels method instead request_body = { 'labelModifications': [{ 'fieldModifications': [{ 'fieldId': 'your_field_id', 'setTextValues': ['new_value'] }]}]} result = labels_service.files().modifyLabels( fileId=document_id, body=request_body ).execute() The field selection error happens because regular Drive API doesn’t recognize the labels field. Make sure you’re using the correct label field IDs rather than display names, as the API is quite strict about this.