Apps Script API로 함수 실행

Google Apps Script API는 지정된 Apps Script 함수를 원격으로 실행하는 scripts.run 메서드를 제공합니다. 호출 애플리케이션에서 이 메서드를 사용하여 스크립트 프로젝트 중 하나에서 함수를 원격으로 실행하고 응답을 받을 수 있습니다.

요구사항

호출하는 애플리케이션이 scripts.run 메서드를 사용하려면 먼저 다음 요구사항을 충족해야 합니다. 반드시 다음 요건을 충족해야 합니다.

  • 스크립트 프로젝트를 API 실행 파일로 배포합니다. 필요에 따라 프로젝트를 배포, 배포 취소, 다시 배포할 수 있습니다.

  • 실행에 적합한 범위가 지정된 OAuth 토큰을 제공합니다. 이 OAuth 토큰은 호출된 함수에서 사용되는 범위뿐만 아니라 스크립트에서 사용하는 모든 범위를 포함해야 합니다. 메서드 참조에서 승인 범위의 전체 목록을 참조하세요.

  • 스크립트와 호출 애플리케이션의 OAuth2 클라이언트가 공통 Google Cloud 프로젝트를 공유하는지 확인합니다. Cloud 프로젝트는 표준 클라우드 프로젝트여야 합니다. Apps Script 프로젝트용으로 만든 기본 프로젝트로는 충분하지 않습니다. 새 표준 Cloud 프로젝트 또는 기존 프로젝트를 사용할 수 있습니다.

  • Cloud 프로젝트에서 Google Apps Script API를 사용 설정합니다.

scripts.run 메서드

scripts.run 메서드를 실행하려면 키 식별 정보가 필요합니다.

필요한 경우 개발 모드에서 실행되도록 스크립트를 구성할 수 있습니다. 이 모드는 최근에 배포된 버전이 아닌 가장 최근에 저장된 스크립트 프로젝트 버전으로 실행됩니다. 요청 본문devMode 부울을 true로 설정하면 됩니다. 개발 모드에서는 스크립트의 소유자만 스크립트를 실행할 수 있습니다.

매개변수 데이터 유형 처리

Apps Script API scripts.run 메서드를 사용하려면 일반적으로 데이터를 Apps Script에 함수 매개변수로 전송하고 데이터를 함수 반환 값으로 다시 가져와야 합니다. API는 기본 유형(문자열, 배열, 객체, 숫자, 불리언)이 있는 값만 가져와서 반환할 수 있습니다. 이는 JavaScript의 기본 유형과 유사합니다. 문서 또는 시트와 같은 좀 더 복잡한 Apps Script 객체는 API를 사용하여 스크립트 프로젝트로 또는 스크립트 프로젝트에서 전달할 수 없습니다.

호출 애플리케이션이 Java와 같이 강타입(strongly type) 언어로 작성되었다면 이러한 기본 유형에 해당하는 일반 객체의 목록 또는 배열로 매개변수를 전달합니다. 대부분의 경우 간단한 유형 변환을 자동으로 적용할 수 있습니다. 예를 들어 숫자 매개변수를 사용하는 함수에는 추가 처리 없이 Java Double, Integer 또는 Long 객체를 매개변수로 지정할 수 있습니다.

API가 함수 응답을 반환할 때 반환된 값을 올바른 유형으로 변환해야 사용할 수 있는 경우가 많습니다. 다음은 자바 기반 예입니다.

  • API에서 Java 애플리케이션에 반환하는 숫자는 java.math.BigDecimal 객체로 도착하며 필요에 따라 Doubles 또는 int 유형으로 변환해야 할 수 있습니다.
  • Apps Script 함수가 문자열 배열을 반환하면 자바 애플리케이션은 응답을 List<String> 객체로 전송합니다.

    List<String> mylist = (List<String>)(op.getResponse().get("result"));
    
  • Bytes 배열을 반환하려는 경우 Apps Script 함수 내에서 배열을 base64 문자열로 인코딩하고 대신 해당 문자열을 반환하는 것이 편리할 수 있습니다.

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

아래의 코드 샘플 예는 API 응답을 해석하는 방법을 보여줍니다.

일반 절차

다음은 Apps Script API를 사용하여 Apps Script 함수를 실행하는 일반적인 절차를 설명합니다.

1단계: 공통 Cloud 프로젝트 설정

스크립트와 호출 애플리케이션은 모두 동일한 Cloud 프로젝트를 공유해야 합니다. 이 Cloud 프로젝트는 기존 프로젝트이거나 이 목적으로 만든 새 프로젝트일 수 있습니다. Cloud 프로젝트가 있으면 스크립트 프로젝트를 사용하도록 전환해야 합니다.

2단계: 스크립트를 API 실행 파일로 배포

  1. 사용하려는 함수가 있는 Apps Script 프로젝트를 엽니다.
  2. 오른쪽 상단에서 배포 > 새 배포를 클릭합니다.
  3. 대화상자가 열리면 배포 유형 사용 설정 > API 실행 파일을 클릭합니다.
  4. '액세스 권한이 있는 사용자' 드롭다운 메뉴에서 Apps Script API를 사용하여 스크립트의 함수를 호출할 수 있는 사용자를 선택합니다.
  5. 배포를 클릭합니다.

3단계: 호출 애플리케이션 구성하기

호출 애플리케이션은 사용하기 전에 Apps Script API를 사용 설정하고 OAuth 사용자 인증 정보를 설정해야 합니다. 이렇게 하려면 Cloud 프로젝트에 액세스할 수 있어야 합니다.

  1. 호출 애플리케이션 및 스크립트에서 사용 중인 Cloud 프로젝트를 구성합니다. 방법은 다음과 같습니다.
    1. Cloud 프로젝트에서 Apps Script API를 사용 설정합니다.
    2. OAuth 동의 화면 구성
    3. OAuth 사용자 인증 정보 만들기
  2. 스크립트 프로젝트를 열고 왼쪽에서 개요 를 클릭합니다.
  3. 프로젝트 OAuth 범위에서 스크립트에 필요한 모든 범위를 기록합니다.
  4. 호출하는 애플리케이션 코드에서 API 호출용 스크립트 OAuth 액세스 토큰을 생성합니다. 이는 API 자체에서 사용하는 토큰이 아니라 스크립트를 실행할 때 필요한 토큰이 아닙니다. Cloud 프로젝트 클라이언트 ID와 기록한 스크립트 범위를 사용하여 빌드해야 합니다.

    Google 클라이언트 라이브러리는 이 토큰을 빌드하고 애플리케이션의 OAuth를 처리하는 데 큰 도움이 될 수 있으며, 일반적으로 스크립트 범위를 사용하여 상위 수준의 '사용자 인증 정보' 객체를 빌드할 수 있습니다. 범위 목록에서 사용자 인증 정보 객체를 빌드하는 예시는 Apps Script API 빠른 시작을 참조하세요.

4단계: script.run 요청하기

호출 애플리케이션이 구성되면 scripts.run를 호출할 수 있습니다. 각 API 호출은 다음 단계로 구성됩니다.

  1. 스크립트 ID, 함수 이름, 필수 매개변수를 사용하여 API 요청을 빌드합니다.
  2. scripts.run를 호출하고 헤더에 빌드한 스크립트 OAuth 토큰을 포함하거나 (기본 POST 요청을 사용하는 경우) 스크립트 범위로 빌드한 사용자 인증 정보 객체를 사용합니다.
  3. 스크립트 실행이 완료될 때까지 기다립니다. 스크립트는 최대 6분의 실행 시간이 걸릴 수 있으므로 애플리케이션에서 이 시간을 허용해야 합니다.
  4. 완료되면 스크립트 함수가 값을 반환할 수 있으며, 값이 지원되는 유형인 경우 API가 애플리케이션에 다시 전달합니다.

아래에서 script.run API 호출의 예를 확인하세요.

API 요청 예

다음 예는 Apps Script 함수를 호출하여 사용자의 루트 디렉터리에 있는 폴더 목록을 출력하여 Apps Script API 실행을 다양한 언어로 요청하는 방법을 보여줍니다. 실행된 함수가 포함된 Apps Script 프로젝트의 스크립트 ID는 ENTER_YOUR_SCRIPT_ID_HERE로 표시된 곳에 지정해야 합니다. 예에서는 해당 언어의 Google API 클라이언트 라이브러리를 사용합니다.

대상 스크립트

이 스크립트의 함수는 Drive API를 사용합니다.

스크립트를 호스팅하는 프로젝트에서 Drive API를 사용 설정해야 합니다.

또한 호출 애플리케이션은 다음 Drive 범위가 포함된 OAuth 사용자 인증 정보를 전송해야 합니다.

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

여기에 나와 있는 예시 애플리케이션은 Google 클라이언트 라이브러리를 사용하여 이 범위를 사용하는 OAuth용 사용자 인증 정보 객체를 빌드합니다.

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

제한사항

Apps Script API에는 몇 가지 제한사항이 있습니다.

  1. 공통 Cloud 프로젝트. 호출되는 스크립트와 호출 애플리케이션은 Cloud 프로젝트를 공유해야 합니다. Cloud 프로젝트는 표준 클라우드 프로젝트여야 합니다. Apps Script 프로젝트용으로 만든 기본 프로젝트로는 충분하지 않습니다. 표준 Cloud 프로젝트는 새 프로젝트이거나 기존 프로젝트일 수 있습니다.

  2. 기본 매개변수 및 반환 유형. API는 Apps Script 관련 객체 (예: 문서, Blob, 캘린더, 드라이브 파일 등)를 애플리케이션에 전달하거나 반환할 수 없습니다. 문자열, 배열, 객체, 숫자, 불리언과 같은 기본 유형만 전달 및 반환될 수 있습니다.

  3. OAuth 범위. API는 필수 범위가 하나 이상 있는 스크립트만 실행할 수 있습니다. 즉, API를 사용하여 하나 이상의 서비스에 대한 승인이 필요하지 않은 스크립트를 호출할 수 없습니다.

  4. 트리거 없음.API는 Apps Script 트리거를 만들 수 없습니다.