Search code examples
javagoogle-apps-scriptgoogle-api-client

How to run a Google App Script using Google API Service Library (Java)


By following the Java Quickstart example, I am able to create a new Google App Script project and retrieve the scriptId. Also, by referring to the Restful API document, the script should be able to be executed using Method: scripts.run. However, I don't know how to retrieve the return value using com.google.api.services.script.Script in Java.

I've tried:

Script scriptService = getScriptService();
Script.Scripts scripts = scriptService.scripts();
Script.Scripts.Run run = scripts.run(scriptId, request);

and decompiled run function:

public Script.Scripts.Run run(String var1, ExecutionRequest var2) throws IOException {
    Script.Scripts.Run var3 = new Script.Scripts.Run(var1, var2);
    Script.this.initialize(var3);
    return var3;
}

The function doesn't return an ExecutionResponse object which I am looking for.


Solution

  • Per the REST API documentation, calling script.run does not immediately return an ExecutionResponse object, but an Operation object that may contain an ExecutionResponse:

    {
      "done": boolean,
    
      // Union field result can be only one of the following:
      "error": {
        object(Status)
      },
      "response": object(ExecutionResponse)
      ,
      // End of list of possible types for union field result.
    }
    

    If we look at the Java API Client library, we see that method Script.Script.run takes arguments of the script ID, and an ExecutionRequest, and then returns a Script.Script.Run request that must be .execute()d:

    Create a request for the method "scripts.run". This request holds the parameters needed by the script server. After setting any optional parameters, call the AbstractGoogleClientRequest.execute() method to invoke the remote operation.

    The request referred to by the quoted documentation is Script.Script.Run, and has methods like .setAccessToken() for additional configuration, and several execution methods like .execute() and .executeMedia() to actually submit the execution request and return the Operation.