I've been trying to modify the label value of a file using the following code.
However, it's not working. Do you have any ideas?
# Import Libraries
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
# Define the required scopes
SCOPES = ['https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/drive.labels']
# Authenticate and load credentials
def authenticate():
creds = None
# The file token.json stores the user's access and refresh tokens.
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# If there are no valid credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES) # Use the correct file name here
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.json', 'w') as token:
token.write(creds.to_json())
return creds
# Main function to update the label on a file
def update_label(file_id, label_id, public_choice_id):
creds = authenticate()
service = build('drive', 'v3', credentials=creds)
try:
# Get the file's metadata including labels
file_metadata = service.files().get(fileId=file_id, fields='id,labels').execute()
# Get the existing labels
labels = file_metadata.get('labels', [])
# Update the label for 'Data Classification' to 'Public'
for label in labels:
if label['id'] == label_id:
label['value'] = public_choice_id # Set the label value to "Public"
# Update the file with the new labels
updated_file_metadata = service.files().update(
fileId=file_id,
body={'labels': labels}
).execute()
print(f"Label for file {file_id} updated successfully!")
except HttpError as error:
print(f"An error occurred: {error}")
# Example usage
file_id = '1pXX6SPbHuEJeO8wI8LIACbfEEItIzRIz' # The ID of the file you want to modify
label_id = 'A9438FD180' # Data Classification label ID
public_choice_id = '66645FBAAC' # Public choice ID for the label
update_label(file_id, label_id, public_choice_id)
What I’ve tried: I’ve confirmed that the file has labels applied and the file_id is correct. I’ve made sure that the required scopes are set, including https://www.googleapis.com/auth/drive and https://www.googleapis.com/auth/drive.labels. I’ve also tried refreshing the token.json and re-authorizing the credentials, but the issue persists.
I also failed retrieving the current label and value label from the file
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
# SCOPES needed to access labels
SCOPES = ['https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/drive.labels']
# Authenticate and create the API client
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Build the Drive API client
service = build('drive', 'v3', credentials=creds)
# Build the Labels API client
labels_service = build('drive', 'v3', credentials=creds)
# Fetch the labels for the file
file_labels = labels_service.files().get(fileId=file_id, fields='id,labels').execute()
# Check the labels associated with the file
print("File Labels:", file_labels)
But I get this message:
HttpError: <HttpError 400 when requesting https://www.googleapis.com/drive/v3/files/1pXX6SPbHuEJeO8wI8LIACbfEEItIzRIz?fields=id%2Clabels&alt=json returned "Invalid field selection labels". Details: "[{'message': 'Invalid field selection labels', 'domain': 'global', 'reason': 'invalidParameter', 'location': 'fields', 'locationType': 'parameter'}]"
Why am I receiving this error when trying to get the file metadata with labels? How can I fix this issue to successfully modify the label value for a file? Thanks in advance for your help!