Thực thi các hàm bằng API Apps Script

API Google Apps Script cung cấp một phương thức scripts.run để thực thi từ xa một hàm Apps Script cụ thể. Bạn có thể sử dụng phương thức này trong ứng dụng gọi để chạy một hàm trong một trong các dự án tập lệnh của bạn từ xa và nhận được phản hồi.

Yêu cầu

Bạn phải đáp ứng các yêu cầu sau đây thì ứng dụng gọi mới có thể sử dụng phương thức scripts.run. Bạn phải:

  • Triển khai dự án tập lệnh dưới dạng một API có thể thực thi. Bạn có thể triển khai, huỷ triển khai và triển khai lại các dự án nếu cần.

  • Cung cấp mã thông báo OAuth có phạm vi phù hợp để thực thi. Mã thông báo OAuth này phải bao gồm tất cả phạm vi mà tập lệnh sử dụng, chứ không chỉ những phạm vi mà hàm được gọi sử dụng. Xem danh sách đầy đủ về các phạm vi uỷ quyền trong tài liệu tham khảo về phương thức.

  • Đảm bảo rằng tập lệnh và ứng dụng gọi OAuth2 của ứng dụng chia sẻ một dự án chung trên Google Cloud. Dự án Cloud phải là một dự án Cloud tiêu chuẩn; các dự án mặc định được tạo cho dự án Apps Script là không đủ. Bạn có thể sử dụng một dự án Cloud chuẩn mới hoặc một dự án hiện có.

  • Bật Google Apps Script API trong dự án trên Cloud.

Phương thức scripts.run

Phương thức scripts.run yêu cầu thông tin nhận dạng chính để chạy:

Bạn có thể tuỳ ý định cấu hình tập lệnh để thực thi ở chế độ phát triển. Chế độ này thực thi bằng phiên bản đã lưu gần đây nhất của dự án tập lệnh thay vì phiên bản được triển khai gần đây nhất. Hãy thực hiện việc này bằng cách đặt giá trị boolean devMode trong nội dung yêu cầu thành true. Chỉ chủ sở hữu tập lệnh mới có thể thực thi tập lệnh ở chế độ phát triển.

Xử lý các loại dữ liệu tham số

Việc sử dụng phương thức Apps Script API scripts.run thường liên quan đến việc gửi dữ liệu đến Apps Script dưới dạng tham số hàm và nhận dữ liệu dưới dạng giá trị trả về của hàm. API chỉ có thể nhận và trả về các giá trị có kiểu cơ bản: chuỗi, mảng, đối tượng, số và boolean. Các loại này tương tự như các loại cơ bản trong JavaScript. API không thể truyền các đối tượng Apps Script phức tạp hơn như Document hoặc Sheet vào hoặc từ dự án tập lệnh.

Khi ứng dụng gọi của bạn được viết bằng một ngôn ngữ có kiểu dữ liệu mạnh như Java, ứng dụng đó sẽ truyền các tham số dưới dạng một danh sách hoặc mảng các đối tượng chung tương ứng với các kiểu cơ bản này. Trong nhiều trường hợp, bạn có thể tự động áp dụng các lượt chuyển đổi loại đơn giản. Ví dụ: một hàm lấy tham số số có thể được cung cấp đối tượng Double, Integer hoặc Long Java làm tham số mà không cần xử lý thêm.

Khi API trả về phản hồi của hàm, bạn thường cần truyền giá trị được trả về sang đúng loại trước khi có thể sử dụng. Dưới đây là một số ví dụ dựa trên Java:

  • Các số do API trả về cho một ứng dụng Java sẽ có dạng đối tượng java.math.BigDecimal và có thể cần được chuyển đổi thành các loại Doubles hoặc int nếu cần.
  • Nếu hàm Apps Script trả về một mảng chuỗi, thì ứng dụng Java sẽ truyền phản hồi vào một đối tượng List<String>:

    List<String> mylist = (List<String>)(op.getResponse().get("result")); 
  • Nếu muốn trả về một mảng Bytes, bạn có thể thấy thuận tiện khi mã hoá mảng dưới dạng một chuỗi base64 trong hàm Apps Script và trả về chuỗi đó:

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

Các ví dụ về mã dưới đây minh hoạ các cách diễn giải phản hồi API.

Quy trình chung

Sau đây là quy trình chung để sử dụng Apps Script API nhằm thực thi các hàm Apps Script:

Bước 1: Thiết lập dự án Cloud chung

Cả tập lệnh và ứng dụng gọi đều cần dùng chung một dự án trên Cloud. Dự án Cloud này có thể là một dự án hiện có hoặc một dự án mới được tạo cho mục đích này. Khi đã có một dự án trên Cloud, bạn phải chuyển dự án tập lệnh để sử dụng dự án đó.

Bước 2: Triển khai tập lệnh dưới dạng một tệp thực thi API

  1. Mở dự án Apps Script có các hàm mà bạn muốn sử dụng.
  2. Ở trên cùng bên phải, hãy nhấp vào Triển khai > Triển khai mới.
  3. Trong hộp thoại mở ra, hãy nhấp vào Bật các loại hình triển khai > API Executable (Tệp thực thi API).
  4. Trong trình đơn thả xuống "Ai có quyền truy cập", hãy chọn những người dùng được phép gọi các hàm của tập lệnh bằng Apps Script API.
  5. Nhấp vào Triển khai.

Bước 3: Định cấu hình ứng dụng gọi

Ứng dụng gọi phải bật Apps Script API và thiết lập thông tin đăng nhập OAuth thì mới có thể sử dụng. Bạn phải có quyền truy cập vào Dự án trên đám mây để thực hiện việc này.

  1. Định cấu hình dự án trên Cloud mà ứng dụng và tập lệnh gọi của bạn đang sử dụng. Bạn có thể thực hiện việc này theo các bước sau:
    1. Bật Apps Script API trong dự án trên Cloud.
    2. Định cấu hình màn hình đồng ý OAuth.
    3. Tạo thông tin xác thực OAuth.
  2. Mở dự án tập lệnh, rồi ở bên trái, hãy nhấp vào Tổng quan .
  3. Trong phần Project Oauth scopes (Phạm vi OAuth của dự án), hãy ghi lại tất cả các phạm vi mà tập lệnh yêu cầu.
  4. Trong mã ứng dụng gọi, hãy tạo mã truy cập OAuth của tập lệnh cho lệnh gọi API. Đây không phải là mã thông báo mà chính API sử dụng, mà là mã thông báo mà tập lệnh yêu cầu khi thực thi. Bạn nên tạo khoá này bằng mã ứng dụng khách dự án trên Cloud và các phạm vi tập lệnh mà bạn đã ghi lại.

    Thư viện ứng dụng Google có thể hỗ trợ rất nhiều trong việc tạo mã thông báo này và xử lý OAuth cho ứng dụng, thường cho phép bạn thay vào đó tạo một đối tượng "thông tin đăng nhập" cấp cao hơn bằng cách sử dụng các phạm vi tập lệnh. Hãy xem Các hướng dẫn nhanh về Apps Script API để biết ví dụ về cách tạo một đối tượng thông tin đăng nhập từ danh sách các phạm vi.

Bước 4: Thực hiện yêu cầu script.run

Sau khi định cấu hình ứng dụng gọi điện, bạn có thể thực hiện các cuộc gọi scripts.run. Mỗi lệnh gọi API bao gồm các bước sau:

  1. Tạo một yêu cầu API bằng cách sử dụng mã tập lệnh, tên hàm và mọi tham số bắt buộc.
  2. Thực hiện lệnh gọi scripts.run và đưa mã thông báo OAuth của tập lệnh mà bạn đã tạo vào tiêu đề (nếu dùng yêu cầu POST cơ bản) hoặc dùng đối tượng thông tin xác thực mà bạn đã tạo bằng các phạm vi của tập lệnh.
  3. Cho phép tập lệnh hoàn tất quá trình thực thi. Tập lệnh được phép mất tối đa 6 phút để thực thi, vì vậy ứng dụng của bạn phải cho phép điều này.
  4. Sau khi hoàn tất, hàm tập lệnh có thể trả về một giá trị mà API sẽ gửi lại cho ứng dụng nếu giá trị đó thuộc một loại được hỗ trợ.

Bạn có thể xem ví dụ về lệnh gọi API script.run bên dưới.

Ví dụ về yêu cầu API

Các ví dụ sau đây minh hoạ cách thực hiện yêu cầu thực thi Apps Script API bằng nhiều ngôn ngữ, gọi một hàm Apps Script để in danh sách các thư mục trong thư mục gốc của người dùng. Bạn phải chỉ định mã tập lệnh của dự án Apps Script chứa hàm được thực thi ở nơi được chỉ ra bằng ENTER_YOUR_SCRIPT_ID_HERE. Các ví dụ này dựa vào Thư viện ứng dụng API của Google cho các ngôn ngữ tương ứng.

Tập lệnh đích

Hàm trong tập lệnh này sử dụng Drive API.

Bạn phải bật Drive API trong dự án lưu trữ tập lệnh.

Ngoài ra, các ứng dụng gọi phải gửi thông tin đăng nhập OAuth bao gồm phạm vi Drive sau:

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

Các ứng dụng mẫu ở đây sử dụng thư viện ứng dụng Google để tạo các đối tượng thông tin đăng nhập cho OAuth bằng phạm vi này.

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

Các điểm hạn chế

API Apps Script có một số hạn chế:

  1. Một dự án chung trên Đám mây. Tập lệnh đang được gọi và ứng dụng gọi phải dùng chung một dự án trên đám mây. Dự án Cloud phải là một dự án Cloud tiêu chuẩn; các dự án mặc định được tạo cho dự án Apps Script là không đủ. Dự án Cloud tiêu chuẩn có thể là dự án mới hoặc dự án hiện có.

  2. Tham số cơ bản và các loại dữ liệu trả về. API không thể truyền hoặc trả về các đối tượng dành riêng cho Apps Script (chẳng hạn như Tài liệu, Blob, Lịch, Tệp trên Drive, v.v.) cho ứng dụng. Chỉ các kiểu cơ bản như chuỗi, mảng, đối tượng, số và boolean mới có thể được truyền và trả về.

  3. Phạm vi OAuth. API chỉ có thể thực thi những tập lệnh có ít nhất một phạm vi bắt buộc. Điều này có nghĩa là bạn không thể dùng API để gọi một tập lệnh không yêu cầu uỷ quyền của một hoặc nhiều dịch vụ.

  4. Không có trình kích hoạt.API không thể tạo trình kích hoạt Apps Script.