Search code examples
google-apps-scriptgoogle-apigoogle-docsgoogle-api-ruby-client

Correct scope for Google App Script Execution API?


I'm hoping to automate some HR work by running a Google App Script via the Execution API. Without getting too much into the details, I'd like to pass employee evaluation data as a parameter into the App Script. The script will then use this data to compile an "Employee Review" GDoc.

So far, I have ran a simple test App Script using the Execution API. For example, I can successfully run a simple function which logs a string or interacts with spreadsheets. So far so good.

But I run into problems when trying to write to a GDoc (which is unfortunately integral to my task). Here's my paired down script:

// TODO: Eventually, we'll pass these variables as arguments
var docId = "MY-DOC-ID";

// Find the team member review doc
var doc = DocumentApp.openById(docId);

// Replace placeholder text
var docBody = doc.getActiveSection();
docBody.replaceText('{{DATE}}', "Date set by App Script!!!");
doc.saveAndClose();

This script works when I press the "Run" button in the App Scripts web UI. But when I try to run via the Execution API, I get:

{
  "error": "unauthorized_client",
  "error_description": "Unauthorized client or scope in request."
}

So apparently I haven't provided the correct scope? Following the docs, I can find the necessary scope(s) in Project Properties > Scopes which says:

enter image description here

But when I try adding that scope, it wont work. As I said other scopes (e.g. https://www.googleapis.com/auth/spreadsheets) work just fine. Perhaps the auth/documents scope is no longer supported or there's a bug in their API?

Questions

  1. What is the correct scope? I can see a big list here but I don't see https://www.googleapis.com/auth/documents, so?
  2. Any other suggestions? For example, is it possible to write to a Google Doc using the Google Client API directly (i.e. without using App Scripts)?

Solution

  • Doh. I figured out the solution to my problem. While it was a dumb mistake, it's nevertheless worth posting as it may save others confusion in the future.

    First, a little context about my setup. I'm authenticating to the Google Client API using a Service Account. Furthermore, as is common when using a service account setup, I am impersonating a user within our organization (specifically my own account).

    My missing step (obvious in hindsight)...

    1. Log into the App Script web UI as the person you are impersonating.
    2. Manually run the script by pressing the play button
    3. If the impersonated user has not already granted permissions to access the required scopes, you will be prompted to do so.
    4. After granting access (specifically for the https://www.googleapis.com/auth/documents scope), my authorization error disappeared.

    So the lesson: Make sure the account you are impersonating has granted access for all the scopes which your script requires.