Apps Script API ile İşlevler Yürütme

Google Apps Komut Dosyası API'si, belirtilen bir Apps Komut Dosyası işlevini uzaktan yürüten bir scripts.run yöntemi sağlar. Bu yöntemi, komut dosyası projelerinizden birinde bir işlevi uzaktan çalıştırmak ve yanıt almak için arama uygulamasında kullanabilirsiniz.

Şartlar

Bir arama uygulamasının scripts.run yöntemini kullanabilmesi için aşağıdaki koşulları karşılaması gerekir. Yapmanız gerekenler:

  • Komut dosyası projesini çalıştırılabilir API olarak dağıtın. Gerektiğinde projeleri dağıtabilir, dağıtımı kaldırabilir ve yeniden dağıtabilirsiniz.

  • Yürütme için uygun kapsamda bir OAuth jetonu sağlayın. Bu OAuth jetonu, yalnızca çağrılan işlev tarafından kullanılanlar değil, komut dosyası tarafından kullanılan tüm kapsamları kapsamalıdır. Yöntem referansındaki yetkilendirme kapsamlarının tam listesine göz atın.

  • Komut dosyasının ve çağıran uygulamanın OAuth2 istemcisinin ortak bir Google Cloud projesini paylaştığından emin olun. Cloud projesi standart bir Cloud projesi olmalıdır. Apps Komut Dosyası projeleri için oluşturulan varsayılan projeler yeterli değildir. Yeni bir standart Cloud projesi veya mevcut bir proje kullanabilirsiniz.

  • Cloud projesinde Google Apps Script API'yi etkinleştirin.

scripts.run yöntemi

scripts.run yönteminin çalışması için temel tanımlayıcı bilgiler gerekir:

İsteğe bağlı olarak komut dosyanızı geliştirme modunda çalışacak şekilde yapılandırabilirsiniz. Bu mod, en son dağıtılan sürüm yerine komut dosyası projesinin en son kaydedilen sürümüyle yürütülür. Bunu yapmak için istek gövdesinde devMode boolean değerini true olarak ayarlayın. Komut dosyasını yalnızca sahibi geliştirme modunda çalıştırabilir.

Parametre veri türlerini işleme

Apps Komut Dosyası API'sini scripts.run yöntemini kullanarak genellikle işlev parametreleri olarak Apps Komut Dosyası'na veri gönderme ve işlev dönüş değerleri olarak veri alma işlemi yapılır. API yalnızca temel türlerdeki değerleri (dizeler, diziler, nesneler, sayılar ve boole değerleri) alıp döndürebilir. Bunlar, JavaScript'teki temel türlere benzer. Document veya Sheet gibi daha karmaşık Apps Komut Dosyası nesneleri, API tarafından komut dosyası projesine veya komut dosyası projesinden geçirilemez.

Arama uygulamanız Java gibi kesin türü belirlenmiş bir dilde yazıldığında, parametreleri bu temel türlere karşılık gelen genel nesnelerin listesi veya dizisi olarak iletir. Çoğu durumda, basit tür dönüşümlerini otomatik olarak uygulayabilirsiniz. Örneğin, sayı parametresi alan bir işleve ek işlem yapmadan parametre olarak Java Double, Integer veya Long nesnesi verilebilir.

API, işlev yanıtını döndürdüğünde döndürülen değerin kullanılabilmesi için genellikle doğru türe dönüştürülmesi gerekir. Aşağıda bazı Java tabanlı örnekler verilmiştir:

  • API tarafından bir Java uygulamasına döndürülen sayılar java.math.BigDecimal nesneleri olarak gelir ve gerektiğinde Doubles veya int türlerine dönüştürülmesi gerekebilir.
  • Apps Komut Dosyası işlevi bir dize dizisi döndürürse Java uygulaması, yanıtı bir List<String> nesnesine dönüştürür:

    List<String> mylist = (List<String>)(op.getResponse().get("result"));
    
  • Bytes dizisi döndürmek istiyorsanız diziyi Apps Komut Dosyası işlevi içinde base64 dizesi olarak kodlamanın ve bunun yerine bu dizeyi döndürmenin daha kolay olduğunu görebilirsiniz:

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

Aşağıdaki örnek kod örnekleri, API yanıtını yorumlama yöntemlerini gösterir.

Genel prosedür

Aşağıda, Apps Script işlevlerini yürütmek için Apps Script API'yi kullanmayla ilgili genel prosedür açıklanmaktadır:

1. adım: Ortak Cloud projesini oluşturun

Hem komut dosyanız hem de çağıran uygulama aynı Cloud projesini paylaşmalıdır. Bu Cloud projesi mevcut bir proje veya bu amaçla oluşturulmuş yeni bir proje olabilir. Cloud projeniz olduğunda komut dosyası projenizi bu projeyi kullanacak şekilde değiştirmeniz gerekir.

2. adım: Komut dosyasını API yürütülebilir dosyası olarak dağıtın

  1. Kullanmak istediğiniz işlevlerin bulunduğu Apps Komut Dosyası projesini açın.
  2. Sağ üstte Dağıt > Yeni Dağıtım'ı tıklayın.
  3. Açılan iletişim kutusunda Dağıtım türlerini etkinleştir > API Executable'ı tıklayın.
  4. "Erişimi olanlar" açılır menüsünde, Apps Komut Dosyası API'sini kullanarak komut dosyasının işlevlerini çağırmasına izin verilen kullanıcıları seçin.
  5. Dağıt'ı tıklayın.

3. adım: Arama uygulamasını yapılandırın

Çağıran uygulamanın kullanılabilmesi için Apps Komut Dosyası API'sini etkinleştirmesi ve OAuth kimlik bilgilerini oluşturması gerekir. Bunu yapmak için Cloud projesine erişiminiz olmalıdır.

  1. Çağıran uygulamanızın ve komut dosyanızın kullandığı Cloud projesini yapılandırın. Bu işlemi aşağıdaki adımlarla yapabilirsiniz:
    1. Cloud projesinde Apps Script API'yi etkinleştirin.
    2. OAuth izin ekranını yapılandırın.
    3. OAuth kimlik bilgileri oluşturun.
  2. Senaryo projesini açın ve sol tarafta Genel bakış tıklayın.
  3. Project Oauth scopes (Proje OAuth kapsamları) bölümünde, komut dosyasının gerektirdiği tüm kapsamları kaydedin.
  4. Çağıran uygulama kodunda, API çağrısı için bir komut dosyası OAuth erişim jetonu oluşturun. Bu, API'nin kendisinin kullandığı bir jeton değil, komut dosyasının yürütülürken ihtiyaç duyduğu bir jetondur. Cloud projesi istemci kimliği ve kaydettiğiniz komut dosyası kapsamları kullanılarak oluşturulmalıdır.

    Google istemci kitaplıkları, bu jetonu oluşturma ve uygulama için OAuth'u işleme konusunda büyük ölçüde yardımcı olabilir. Genellikle, komut dosyası kapsamlarını kullanarak bunun yerine daha üst düzey bir "kimlik bilgileri" nesnesi oluşturmanıza olanak tanır. Kapsam listesinden kimlik bilgisi nesnesi oluşturma örnekleri için Apps Script API hızlı başlangıç kılavuzlarına bakın.

4. adım: script.run isteğinde bulunun

Arama uygulaması yapılandırıldıktan sonra scripts.run aramaları yapabilirsiniz. Her API çağrısı aşağıdaki adımlardan oluşur:

  1. Komut dosyası kimliğini, işlev adını ve gerekli tüm parametreleri kullanarak API isteği oluşturun.
  2. scripts.run çağrısını yapın ve oluşturduğunuz komut dosyası OAuth jetonunu üstbilgiye ekleyin (temel bir POST isteği kullanıyorsanız) veya komut dosyası kapsamlarıyla oluşturduğunuz bir kimlik bilgileri nesnesi kullanın.
  3. Komut dosyasının yürütülmesini tamamlamasına izin verin. Komut dosyalarının yürütme süresi en fazla altı dakika olabilir. Bu nedenle, uygulamanız buna izin vermelidir.
  4. Tamamlandığında, komut dosyası işlevi bir değer döndürebilir. Bu değer, desteklenen bir türse API tarafından uygulamaya geri gönderilir.

script.run API çağrılarıyla ilgili örnekleri aşağıda bulabilirsiniz.

API isteği örnekleri

Aşağıdaki örneklerde, kullanıcının kök dizinindeki klasörlerin listesini yazdırmak için bir Apps Komut Dosyası işlevini çağıran çeşitli dillerde Apps Komut Dosyası API yürütme isteğinin nasıl yapılacağı gösterilmektedir. Yürütülen işlevi içeren Apps Komut Dosyası projesinin komut dosyası kimliği, ENTER_YOUR_SCRIPT_ID_HERE ile belirtilen yerde tanımlanmalıdır. Örneklerde, ilgili diller için Google API İstemci Kitaplıkları kullanılır.

Hedef Komut Dosyası

Bu komut dosyasındaki işlev, Drive API'yi kullanır.

Komut dosyasının barındırıldığı projede Drive API'yi etkinleştirmeniz gerekir.

Ayrıca, çağıran uygulamalar aşağıdaki Drive kapsamını içeren OAuth kimlik bilgilerini göndermelidir:

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

Buradaki örnek uygulamalar, bu kapsamı kullanarak OAuth için kimlik bilgisi nesneleri oluşturmak üzere Google istemci kitaplıklarını kullanır.

/**
 * 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

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}.{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()

Sınırlamalar

Apps Script API'nin çeşitli sınırlamaları vardır:

  1. Ortak bir Cloud projesi. Çağrılan komut dosyası ve çağıran uygulama aynı Cloud projesini paylaşmalıdır. Cloud projesi bir standart Cloud projesi olmalıdır. Apps Komut Dosyası projeleri için oluşturulan varsayılan projeler yeterli değildir. Standart Cloud projesi yeni veya mevcut bir proje olabilir.

  2. Temel parametre ve dönüş türleri. API, uygulamaya Apps Komut Dosyası'na özgü nesneleri (ör. Documents, Blobs, Calendars, Drive Files vb.) iletemez veya döndüremez. Yalnızca dizeler, diziler, nesneler, sayılar ve boole değerleri gibi temel türler iletilebilir ve döndürülebilir.

  3. OAuth kapsamları. API yalnızca en az bir gerekli kapsamı olan komut dosyalarını yürütebilir. Bu nedenle, bir veya daha fazla hizmetin yetkilendirilmesini gerektirmeyen bir komut dosyasını çağırmak için API'yi kullanamazsınız.

  4. Tetikleyici yok: API, Apps Script tetikleyicileri oluşturamaz.