Cloud Learner
Cloud Learner

Reputation: 141

How to access Google Doc Api with service account?

I want my web server to request google doc via service account. The reason I choose the service account is I don't want any login information from my user.

Tried below code but this throws The caller does not have permission errors.

SCOPES = ['https://www.googleapis.com/auth/documents']
    SERVICE_ACCOUNT_FILE = 'xxx.json'

    credentials = service_account.Credentials.from_service_account_file(
        SERVICE_ACCOUNT_FILE, scopes=SCOPES
    )
    service = googleapiclient.discovery.build('docs', 'v1', credentials=credentials)
    response = service.documents().get(documentId='xxx').execute()

Upvotes: 2

Views: 1877

Answers (3)

Rafa Guillermo
Rafa Guillermo

Reputation: 15357

Answer:

You need to make sure the Service Account has access rights to the files it is attempting to read/write.

More Information:

The The caller does not have permission error message indicates that the file with ID documentID has sharing permissions such that the service account you are using does not have the permission to do what you are asking it to do - be that reading or writing.

If impersonation of the user really is infeasible for you, the file needs to be accessible via one of the following share options:

If the service account is on a different domain to the user that owns the file:

  • On - Public on the web
  • On - Anyone with the link

If the service account is on the same domain as the user:

  • On - Anyone at your organisation can find and access
  • On - Anyone at your organisation with the link

Alternatively, you can share directly with the service account by selecting Off - Specific people and typing the service account's email address in the People field in the share dialog from the file itself. The service account's email address can be found in the GCP Project with which it is associated - at console.developers.google.com

References:

Upvotes: 0

Tom Larkworthy
Tom Larkworthy

Reputation: 2354

Instructions on creating a service account and reading a Google doc https://www.futurice.com/blog/read-goog-doc-using-service-account

The document needs to either be shared with the service account's email address OR be publicly shared.

Upvotes: 1

Pievis
Pievis

Reputation: 1994

If you don't want to impersonate the user, you have to share the document with the service account from drive in order to give it permission's to read/write

Upvotes: 0

Related Questions