I'm trying the below code to generate the google doc
SERVICE_FILENAME = 'C:/Users/XYZ/Test/service_account.json' # set path to service account filename
from googleapiclient.discovery import build
from google.oauth2 import service_account
from googleapiclient.http import MediaIoBaseDownload, MediaFileUpload
credentials = service_account.Credentials.from_service_account_file(SERVICE_FILENAME,
scopes=['https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/documents']
)
# drive = build('drive', 'v3', credentials=credentials)
drive = build('docs', 'v1', credentials=credentials)
# file_metadata = {'name': filepath,
# 'mimeType': 'application/vnd.google-apps.document'}
# media = MediaFileUpload(filepath,
# mimetype='application/vnd.openxmlformats-officedocument.wordprocessingml.document')
# file = drive.files().create(body=file_metadata,
# # media_body=media,
# fields='id').execute()
file_metadata = {
"title": "xyz",
"body": {}
}
file = drive.documents().create(body=file_metadata).execute()
print('File ID: %s' % file.get('id'))
But I'm not getting any file id and no file is getting created in the google doc. It says File ID: None
First, tried with drive API but that didn't work then I went for doc API which is also not working. Note: Both the APIs are enabled from GCP.
Approach I used after @Tanaike's comment:
from googleapiclient.discovery import build
from google.oauth2 import service_account
SERVICE_FILENAME = 'C:/Users/Test/service_account.json' # set path to service account filename
credentials = service_account.Credentials.from_service_account_file(SERVICE_FILENAME,
scopes=['https://www.googleapis.com/auth/drive']
)
drive = build('drive', 'v3', credentials=credentials)
page_token = None
response = drive.files().list(q="mimeType = 'application/vnd.google-apps.folder'",
spaces='drive',
fields='nextPageToken, files(id, name)',
pageToken=page_token).execute()
for file in response.get('files', []):
# Process change
print('Found file: %s (%s)' % (file.get('name'), file.get('id')))
if file.get('name') == "Document_API":
folder_id = file.get('id')
break
page_token = response.get('nextPageToken', None)
if page_token is None:
break
# create Google Docs file in folder
file_metadata = {
'name': 'data.docx',
'parents': [folder_id]
}
file = drive.files().create(body=file_metadata,
# media_body=media,
fields='id').execute()
print('File ID: %s' % file.get('id'))
In your situation, how about the following modification?
print('File ID: %s' % file.get('id'))
print('File ID: %s' % file.get('documentId'))
file.get('documentId')
.