1

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'))
ninjacode
  • 318
  • 2
  • 18

2 Answers2

1

In your situation, how about the following modification?

From:

print('File ID: %s' % file.get('id'))

To:

print('File ID: %s' % file.get('documentId'))
  • You can retrieve the document ID of the created Google Document by file.get('documentId').

References:

Tanaike
  • 181,128
  • 11
  • 97
  • 165
  • `file.get('documentId')` returns a document id but I can't see the document in my drive or google docs. What is the reason behind that? If the Id is getting generated then the document should exists right? – ninjacode Dec 15 '21 at 08:50
  • 1
    @Ask_Ashu Thank you for replying. I apologize for the inconvenience. About your additional question, I think that the reason for your issue is due to that the Google Document is created by the service account. The service account is different from your Google account. The Document created by the service account is put to the Drive of the service account. – Tanaike Dec 15 '21 at 11:56
  • 1
    @Ask_Ashu If you want to see the created Document on your Google Drive, for example, at first, share a folder in your Google Drive with the email of the service account and put the created Document in the shared folder? By this, you can see it on your Drive. Or, how about sharing the created Document with your Google account? You can see the sample script at https://stackoverflow.com/q/58080962 and https://stackoverflow.com/q/64626446 – Tanaike Dec 15 '21 at 11:56
  • Thanks for the detailed explanation. Now, I'm able to see the document after giving service account email's access to the doc folder. The code I tried is updated in the question. – ninjacode Dec 16 '21 at 10:35
  • @Ask_Ashu Thank you for replying. I'm glad your issue was resolved. Thank you, too. – Tanaike Dec 16 '21 at 12:44
1

As an addition of what @Tanaike says, service accounts do not belong to your Google WorkSpace domain. The files created by a service account are not created in your Google Workspace Domain. If you want more information on how Service Accounts work versus regular accounts, you can check the Documentation.

As a workaround, you could share the file with a user, group, domain, etc. Adapted from Share file example :

create_share_sa.py
def uploadFiles():
    drive = build_service('drive', 'v3')
    new_file = drive.files().create(body={"name": "Testing"}).execute()
    # User share
    new_perm_user = {
        "type": "user",
        "role": "owner",
        "emailAddress": "your_a@domain.com",
    }
    # Domain Share
    # new_perm = {
    #     "type": "domain",
    #     "role": "reader",
    #     "domain": "domain",
    #     "allowFileDiscovery": True
    # }
    perm_id = drive.permissions().create(fileId=new_file['id'],
                                         body=new_perm_user).execute()
Documentation
Emel
  • 2,283
  • 1
  • 7
  • 18
  • I shared my folder with the google service account email and now the file is getting created but yes I want to give read/write permission to my file so this might help. Thanks. – ninjacode Dec 16 '21 at 10:43
  • Glad to hear it! – Emel Dec 16 '21 at 12:57