Wykonywanie funkcji za pomocą interfejsu Apps Script API

Interfejs Google Apps Script API udostępnia metodę scripts.run, która zdalnie wykonuje określoną funkcję Apps Script. Możesz użyć tej metody w aplikacji do wywoływania, by zdalnie uruchomić funkcję w jednym ze swoich skryptów i otrzymać odpowiedź.

Wymagania

Aby aplikacja do wykonywania połączeń mogła korzystać z metody scripts.run, musisz spełnić te wymagania. Musisz:

  • Wdróż projekt skryptu jako wykonywalny interfejs API. W razie potrzeby możesz wdrażać, wycofywać i ponownie wdrażać projekty.

  • Podaj token OAuth o prawidłowym zakresie do wykonania. Ten token OAuth musi obejmować wszystkie zakresy używane przez skrypt, a nie tylko te używane przez wywołanie funkcji. Zobacz pełną listę zakresów autoryzacji w dokumentacji metody.

  • Upewnij się, że skrypt i klient OAuth2 aplikacji wywołującej mają wspólny projekt Google Cloud. Projekt Cloud musi być standardowym projektem Cloud. Domyślne projekty utworzone dla projektów Apps Script są niewystarczające. Możesz użyć nowego lub standardowego projektu Cloud.

  • Włącz interfejs Google Apps Script API w projekcie Cloud.

Metoda scripts.run

Metoda scripts.run wymaga kluczowych informacji umożliwiających identyfikację:

Opcjonalnie możesz skonfigurować skrypt w trybie programistycznym. Ten tryb jest uruchamiany z najnowszą zapisaną wersją skryptu skryptu zamiast ostatnio wdrożonej wersji. Aby to zrobić, ustaw wartość logiczną devMode w treści żądania na true. Tylko właściciel skryptu może uruchomić go w trybie programisty.

Obsługa typów danych parametrów

Korzystanie z metody Apps Script API scripts.run zwykle wymaga przesyłania danych do Apps Script jako parametrów funkcji oraz odzyskiwania danych z powrotem jako wartości zwracających funkcje. Interfejs API może pobierać i zwracać wartości tylko z użyciem podstawowych typów: ciągów znaków, tablicy, obiektów, liczb i wartości logicznych. Są one podobne do podstawowych typów JavaScript. Interfejs API nie może przekazywać bardziej złożonych obiektów Apps Script takich jak Document czy Sheet.

Gdy aplikacja do wykonywania połączeń jest napisana w języku o ścisłym typie, takim jak Java, przekazuje jako parametry listę lub tablicę obiektów podstawowych odpowiadających tym typom. W wielu przypadkach można automatycznie zastosować konwersje proste. Na przykład funkcja, która przyjmuje parametr liczbowy, może mieć parametr Java Double, Integer lub Long jako parametr bez dodatkowej obsługi.

Gdy interfejs API zwraca odpowiedź funkcji, często trzeba przesłać zwrócone wartości na odpowiedni typ, zanim będzie można ich użyć. Oto kilka przykładów opartych na języku Java:

  • Liczby zwrócone przez interfejs API do aplikacji w języku Java przychodzą jako obiekty java.math.BigDecimal i w razie potrzeby mogą zostać skonwertowane na typy Doubles lub int.
  • Jeśli funkcja Apps Script zwraca tablicę ciągów, aplikacja w Javie przesyła odpowiedź do obiektu List<String>:

    List<String> mylist = (List<String>)(op.getResponse().get("result"));
    
  • Jeśli chcesz zwracać tablicę Bytes, możesz zakodować ją w formacie base64 za pomocą funkcji Apps Script i zwrócić ten ciąg:

    return Utilities.base64Encode(myByteArray); // returns a String.
    

Przykładowe fragmenty kodu poniżej pokazują, jak interpretować odpowiedź interfejsu API.

Procedura ogólna

Poniżej opisano ogólną procedurę dotyczącą korzystania z funkcji Apps Script przez interfejs API Apps Script:

Krok 1. Skonfiguruj wspólny projekt Cloud

Zarówno skrypt, jak i aplikacja do wykonywania połączeń muszą mieć ten sam projekt Cloud. Może to być istniejący projekt lub nowy projekt utworzony w tym celu. Gdy masz już projekt Cloud, musisz włączyć go do użytku.

Krok 2. Wdróż skrypt jako plik wykonywalny interfejsu API

  1. Otwórz projekt Apps Script z funkcjami, których chcesz używać.
  2. W prawym górnym rogu kliknij Wdróż > Nowe wdrożenie.
  3. W wyświetlonym oknie kliknij Włącz typy wdrożeń > Interfejs API wykonywalny.
  4. W menu „Kto ma dostęp” wybierz użytkowników, którzy mogą wywoływać funkcje skryptu za pomocą interfejsu Apps Script API.
  5. Kliknij Wdróż.

Krok 3. Skonfiguruj aplikację do wykonywania połączeń

Aplikacja do wywoływania musi włączyć interfejs Apps Script API i ustanowić rekordy OAuth przed jego użyciem. Aby to zrobić, musisz mieć dostęp do projektu Cloud.

  1. Skonfiguruj projekt Cloud używany przez Twoją aplikację do wykonywania połączeń i skrypt. Aby to zrobić:
    1. Włącz Apps Script API w projekcie Cloud.
    2. Skonfiguruj ekran zgody OAuth
    3. Tworzenie danych logowania OAuth
  2. Otwórz projekt skryptu i po lewej stronie kliknij Przegląd .
  3. W sekcji Zakresy protokołu OAuth projektu zarejestruj wszystkie zakresy wymagane przez skrypt.
  4. W kodzie aplikacji wywołującej wygeneruj token dostępu OAuth do skryptu dla wywołania interfejsu API. To nie jest token, z którego korzysta sam interfejs API, ale raczej wymagany przez skrypt podczas wykonywania. Powinna zostać utworzona za pomocą identyfikatora klienta projektu Cloud i zarejestrowanych zakresów skryptu.

    Biblioteki klienta Google mogą znacznie pomóc w utworzeniu tego tokena i obsłudze protokołu OAuth w aplikacji. Zwykle umożliwiają one tworzenie obiektu „credentials” wyższego poziomu za pomocą zakresów skryptu. Przykłady tworzenia obiektu danych uwierzytelniających z listy zakresów znajdziesz w krótkich wprowadzeniach do Apps Script API.

Krok 4. Wyślij żądanie script.run

Po skonfigurowaniu aplikacji do wykonywania połączeń możesz wykonywać scripts.run. Każde wywołanie interfejsu API składa się z następujących kroków:

  1. Utwórz żądanie API, używając identyfikatora skryptu, nazwy funkcji i wszelkich wymaganych parametrów.
  2. Wywołaj scripts.run i umieść w nagłówku token OAuth skryptu utworzony w nagłówku (jeśli jest to podstawowe żądanie POST) albo obiekt uwierzytelniania utworzony przy użyciu zakresów skryptu.
  3. Zezwalaj na dokończenie wykonywania skryptu. Wykonanie skryptów może potrwać do 6 minut, więc Twoja aplikacja powinna na to zezwalać.
  4. Po zakończeniu funkcja skryptu może zwrócić wartość, która zostanie zwrócona do interfejsu API przez aplikację (jeśli jest to obsługiwany typ).

Przykładowe wywołania interfejsu script.run znajdziesz poniżej.

Przykłady żądań do interfejsu API

Poniższe przykłady pokazują, jak utworzyć żądanie wykonania interfejsu Apps Script API w różnych językach, wywołując funkcję Apps Script, aby wyświetlić listę folderów w katalogu głównym użytkownika. W miejscu ENTER_YOUR_SCRIPT_ID_HERE w projekcie Apps Script zawierającym wykonaną funkcję trzeba podać identyfikator skryptu. Przykłady korzystają z bibliotek klienta interfejsu API Google w poszczególnych językach.

Skrypt docelowy

Funkcja w tym skrypcie używa interfejsu Drive API.

Musisz włączyć interfejs Drive API w projekcie hostującym skrypt.

Oprócz tego aplikacje wywołujące muszą wysyłać dane logowania OAuth, które obejmują ten zakres Dysku:

  • https://www.googleapis.com/auth/drive

Przykładowe aplikacje korzystają z bibliotek klienta Google do tworzenia obiektów danych logowania OAuth przez ten zakres.

/**
 * Return the set of folder names contained in the user's root folder as an
 * object (with folder IDs as keys).
 * @return {Object} A set of folder names keyed by folder ID.
 */
function getFoldersUnderRoot() {
  const root = DriveApp.getRootFolder();
  const folders = root.getFolders();
  const folderSet = {};
  while (folders.hasNext()) {
    const folder = folders.next();
    folderSet[folder.getId()] = folder.getName();
  }
  return folderSet;
}

Java


/**
 * Create a HttpRequestInitializer from the given one, except set
 * the HTTP read timeout to be longer than the default (to allow
 * called scripts time to execute).
 *
 * @param {HttpRequestInitializer} requestInitializer the initializer
 *                                 to copy and adjust; typically a Credential object.
 * @return an initializer with an extended read timeout.
 */
private static HttpRequestInitializer setHttpTimeout(
    final HttpRequestInitializer requestInitializer) {
  return new HttpRequestInitializer() {
    @Override
    public void initialize(HttpRequest httpRequest) throws IOException {
      requestInitializer.initialize(httpRequest);
      // This allows the API to call (and avoid timing out on)
      // functions that take up to 6 minutes to complete (the maximum
      // allowed script run time), plus a little overhead.
      httpRequest.setReadTimeout(380000);
    }
  };
}

/**
 * Build and return an authorized Script client service.
 *
 * @param {Credential} credential an authorized Credential object
 * @return an authorized Script client service
 */
public static Script getScriptService() throws IOException {
  Credential credential = authorize();
  return new Script.Builder(
      HTTP_TRANSPORT, JSON_FACTORY, setHttpTimeout(credential))
      .setApplicationName(APPLICATION_NAME)
      .build();
}

/**
 * Interpret an error response returned by the API and return a String
 * summary.
 *
 * @param {Operation} op the Operation returning an error response
 * @return summary of error response, or null if Operation returned no
 * error
 */
public static String getScriptError(Operation op) {
  if (op.getError() == null) {
    return null;
  }

  // Extract the first (and only) set of error details and cast as a Map.
  // The values of this map are the script's 'errorMessage' and
  // 'errorType', and an array of stack trace elements (which also need to
  // be cast as Maps).
  Map<String, Object> detail = op.getError().getDetails().get(0);
  List<Map<String, Object>> stacktrace =
      (List<Map<String, Object>>) detail.get("scriptStackTraceElements");

  java.lang.StringBuilder sb =
      new StringBuilder("\nScript error message: ");
  sb.append(detail.get("errorMessage"));
  sb.append("\nScript error type: ");
  sb.append(detail.get("errorType"));

  if (stacktrace != null) {
    // There may not be a stacktrace if the script didn't start
    // executing.
    sb.append("\nScript error stacktrace:");
    for (Map<String, Object> elem : stacktrace) {
      sb.append("\n  ");
      sb.append(elem.get("function"));
      sb.append(":");
      sb.append(elem.get("lineNumber"));
    }
  }
  sb.append("\n");
  return sb.toString();
}

public static void main(String[] args) throws IOException {
  // ID of the script to call. Acquire this from the Apps Script editor,
  // under Publish > Deploy as API executable.
  String scriptId = "ENTER_YOUR_SCRIPT_ID_HERE";
  Script service = getScriptService();

  // Create an execution request object.
  ExecutionRequest request = new ExecutionRequest()
      .setFunction("getFoldersUnderRoot");

  try {
    // Make the API request.
    Operation op =
        service.scripts().run(scriptId, request).execute();

    // Print results of request.
    if (op.getError() != null) {
      // The API executed, but the script returned an error.
      System.out.println(getScriptError(op));
    } else {
      // The result provided by the API needs to be cast into
      // the correct type, based upon what types the Apps
      // Script function returns. Here, the function returns
      // an Apps Script Object with String keys and values,
      // so must be cast into a Java Map (folderSet).
      Map<String, String> folderSet =
          (Map<String, String>) (op.getResponse().get("result"));
      if (folderSet.size() == 0) {
        System.out.println("No folders returned!");
      } else {
        System.out.println("Folders under your root folder:");
        for (String id : folderSet.keySet()) {
          System.out.printf(
              "\t%s (%s)\n", folderSet.get(id), id);
        }
      }
    }
  } catch (GoogleJsonResponseException e) {
    // The API encountered a problem before the script was called.
    e.printStackTrace(System.out);
  }
}

JavaScript

/**
 * Load the API and make an API call.  Display the results on the screen.
 */
function callScriptFunction() {
  const scriptId = '<ENTER_YOUR_SCRIPT_ID_HERE>';

  // Call the Apps Script API run method
  //   'scriptId' is the URL parameter that states what script to run
  //   'resource' describes the run request body (with the function name
  //              to execute)
  try {
    gapi.client.script.scripts.run({
      'scriptId': scriptId,
      'resource': {
        'function': 'getFoldersUnderRoot',
      },
    }).then(function(resp) {
      const result = resp.result;
      if (result.error && result.error.status) {
        // The API encountered a problem before the script
        // started executing.
        appendPre('Error calling API:');
        appendPre(JSON.stringify(result, null, 2));
      } else if (result.error) {
        // The API executed, but the script returned an error.

        // Extract the first (and only) set of error details.
        // The values of this object are the script's 'errorMessage' and
        // 'errorType', and an array of stack trace elements.
        const error = result.error.details[0];
        appendPre('Script error message: ' + error.errorMessage);

        if (error.scriptStackTraceElements) {
          // There may not be a stacktrace if the script didn't start
          // executing.
          appendPre('Script error stacktrace:');
          for (let i = 0; i < error.scriptStackTraceElements.length; i++) {
            const trace = error.scriptStackTraceElements[i];
            appendPre('\t' + trace.function + ':' + trace.lineNumber);
          }
        }
      } else {
        // The structure of the result will depend upon what the Apps
        // Script function returns. Here, the function returns an Apps
        // Script Object with String keys and values, and so the result
        // is treated as a JavaScript object (folderSet).

        const folderSet = result.response.result;
        if (Object.keys(folderSet).length == 0) {
          appendPre('No folders returned!');
        } else {
          appendPre('Folders under your root folder:');
          Object.keys(folderSet).forEach(function(id) {
            appendPre('\t' + folderSet[id] + ' (' + id + ')');
          });
        }
      }
    });
  } catch (err) {
    document.getElementById('content').innerText = err.message;
    return;
  }
}

Node.js

/**
 * Call an Apps Script function to list the folders in the user's root Drive
 * folder.
 *
 */
async function callAppsScript() {
  const scriptId = '1xGOh6wCm7hlIVSVPKm0y_dL-YqetspS5DEVmMzaxd_6AAvI-_u8DSgBT';

  const {GoogleAuth} = require('google-auth-library');
  const {google} = require('googleapis');

  // Get credentials and build service
  // TODO (developer) - Use appropriate auth mechanism for your app
  const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/drive',
  });
  const script = google.script({version: 'v1', auth});

  try {
    // Make the API request. The request object is included here as 'resource'.
    const resp = await script.scripts.run({
      auth: auth,
      resource: {
        function: 'getFoldersUnderRoot',
      },
      scriptId: scriptId,
    });
    if (resp.error) {
      // The API executed, but the script returned an error.

      // Extract the first (and only) set of error details. The values of this
      // object are the script's 'errorMessage' and 'errorType', and an array
      // of stack trace elements.
      const error = resp.error.details[0];
      console.log('Script error message: ' + error.errorMessage);
      console.log('Script error stacktrace:');

      if (error.scriptStackTraceElements) {
        // There may not be a stacktrace if the script didn't start executing.
        for (let i = 0; i < error.scriptStackTraceElements.length; i++) {
          const trace = error.scriptStackTraceElements[i];
          console.log('\t%s: %s', trace.function, trace.lineNumber);
        }
      }
    } else {
      // The structure of the result will depend upon what the Apps Script
      // function returns. Here, the function returns an Apps Script Object
      // with String keys and values, and so the result is treated as a
      // Node.js object (folderSet).
      const folderSet = resp.response.result;
      if (Object.keys(folderSet).length == 0) {
        console.log('No folders returned!');
      } else {
        console.log('Folders under your root folder:');
        Object.keys(folderSet).forEach(function(id) {
          console.log('\t%s (%s)', folderSet[id], id);
        });
      }
    }
  } catch (err) {
    // TODO(developer) - Handle error
    throw err;
  }
}

Python

from __future__ import print_function

import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError


def main():
    """Runs the sample.
    """
    # pylint: disable=maybe-no-member
    script_id = '1VFBDoJFy6yb9z7-luOwRv3fCmeNOzILPnR4QVmR0bGJ7gQ3QMPpCW-yt'

    creds, _ = google.auth.default()
    service = build('script', 'v1', credentials=creds)

    # Create an execution request object.
    request = {"function": "getFoldersUnderRoot"}

    try:
        # Make the API request.
        response = service.scripts().run(scriptId=script_id,
                                         body=request).execute()
        if 'error' in response:
            # The API executed, but the script returned an error.
            # Extract the first (and only) set of error details. The values of
            # this object are the script's 'errorMessage' and 'errorType', and
            # a list of stack trace elements.
            error = response['error']['details'][0]
            print(f"Script error message: {0}.{format(error['errorMessage'])}")

            if 'scriptStackTraceElements' in error:
                # There may not be a stacktrace if the script didn't start
                # executing.
                print("Script error stacktrace:")
                for trace in error['scriptStackTraceElements']:
                    print(f"\t{0}: {1}."
                          f"{format(trace['function'], trace['lineNumber'])}")
        else:
            # The structure of the result depends upon what the Apps Script
            # function returns. Here, the function returns an Apps Script
            # Object with String keys and values, and so the result is
            # treated as a Python dictionary (folder_set).
            folder_set = response['response'].get('result', {})
            if not folder_set:
                print('No folders returned!')
            else:
                print('Folders under your root folder:')
                for (folder_id, folder) in folder_set.items():
                    print(f"\t{0} ({1}).{format(folder, folder_id)}")

    except HttpError as error:
        # The API encountered a problem before the script started executing.
        print(f"An error occurred: {error}")
        print(error.content)


if __name__ == '__main__':
    main()

Ograniczenia

Interfejs Apps Script API ma kilka ograniczeń:

  1. Wspólny projekt Cloud. Wywoływany skrypt i aplikacja wywołująca muszą mieć wspólny projekt Cloud. Projekt Cloud musi być standardowym projektem Google Cloud. Domyślne projekty utworzone dla projektów Apps Script są niewystarczające. Standardowy projekt Cloud może być nowym lub już istniejącym.

  2. Parametry podstawowe i typy zwrotów. Interfejs API nie może przekazywać ani zwracać do aplikacji obiektów specyficznych dla Apps Script (takich jak Dokumenty, Blobs, Kalendarze, pliki na Dysku itp.). Można przekazywać i zwracać tylko podstawowe typy, takie jak ciągi, tablice, obiekty, liczby i wartości logiczne.

  3. Zakresy OAuth. Interfejs API może wykonywać tylko skrypty, które mają co najmniej 1 wymagany zakres. Oznacza to, że nie możesz używać interfejsu API do wywoływania skryptu, który nie wymaga autoryzacji co najmniej 1 usługi.

  4. Brak aktywatorów.Interfejs API nie może tworzyć aktywatorów Apps Script.