Apps Script API로 함수 실행

Google Apps Script API는 scripts.run 메서드 특정 Apps Script 기능을 원격으로 실행하는 애플리케이션입니다. 이 메서드를 사용하면 스크립트 프로젝트 중 하나에서 함수를 실행하기 위해 호출 애플리케이션에서 요청을 보내고 응답을 받을 수 있습니다

요구사항

호출 애플리케이션이 scripts.run 메서드를 사용하여 축소하도록 요청합니다. 반드시 다음 요건을 충족해야 합니다.

  • 스크립트 프로젝트를 API 실행 파일로 배포합니다. 다음과 같은 작업을 할 수 있습니다. 필요에 따라 프로젝트를 배포, 배포 취소, 재배포할 수 있습니다.

  • 실행을 위해 적절한 범위가 지정된 OAuth 토큰을 제공합니다. 이 OAuth 토큰에는 모든 범위가 포함되어야 합니다. 스크립트에서 사용되는 모든 이벤트 때문입니다. 자세한 내용은 승인 범위 전체 목록 를 참조하세요.

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

  • Google Apps Script API 사용 설정 Cloud 프로젝트에서 가져옵니다

scripts.run 메서드

scripts.run 메서드를 실행하려면 다음과 같은 핵심 식별 정보가 필요합니다.

필요한 경우 개발 모드에서 실행되도록 스크립트를 구성할 수 있습니다. 이 모드는 가장 최근에 저장된 버전의 스크립트 프로젝트로 실행됩니다. 새 버전이 표시됩니다 이렇게 하려면 devMode요청 본문 true에게. 개발 모드에서 스크립트의 소유자만 스크립트를 실행할 수 있습니다.

매개변수 데이터 유형 처리

Apps Script API 사용 scripts.run 메서드 일반적으로 데이터를 Apps Script에 함수 매개변수로 전송하고 데이터를 함수 반환 값으로 다시 가져오기 API는 오직 값(문자열, 배열, 객체, 숫자 및 부울)을 포함할 수 있습니다. 이러한 자바스크립트의 기본 유형과 유사합니다. 더 복잡함 Apps Script 객체(예: Document) 또는 시트를 스크립트 프로젝트에서 가져올 수 있습니다.

호출 애플리케이션이 다음과 같은 강력한 유형의 언어로 작성된 경우 Java, 일반 객체의 목록 또는 배열로 매개변수를 전달합니다. 이러한 기본 유형에 해당합니다. 대부분의 경우 자동으로 입력합니다 예를 들어 숫자를 받는 함수가 매개변수는 Java Double, Integer 또는 Long 객체를 매개변수를 추가할 수 있습니다.

API가 함수 응답을 반환할 때 대개 사용할 수 있기 전에 올바른 유형으로 반환된 값을 반환합니다. 다음은 몇 가지 Java 기반 예:

  • API에서 Java 애플리케이션에 반환하는 숫자는 java.math.BigDecimal 객체이며 다음으로 변환해야 할 수도 있음 Doubles 또는 int 유형을 사용합니다.
  • Apps Script 함수가 문자열 배열을 반환하면 Java 애플리케이션이 응답을 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. 오른쪽 상단에서 배포 &gt; 새 배포를 클릭합니다.
  3. 대화상자가 열리면 배포 유형 사용 설정 을 클릭합니다. &gt; API 실행 파일을 선택합니다.
  4. '액세스 권한이 있는 사용자' 드롭다운 메뉴에서 내 계정에 대한 Apps Script API를 사용하여 스크립트의 함수를 호출할 수 있습니다.
  5. 배포를 클릭합니다.

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

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

  1. 호출하는 애플리케이션과 스크립트에서 사용 중인 Cloud 프로젝트를 구성합니다. 다음 단계를 따르세요. <ph type="x-smartling-placeholder">
      </ph>
    1. Cloud 프로젝트에서 Apps Script API를 사용 설정합니다.
    2. OAuth 동의 화면 구성
    3. OAuth 사용자 인증 정보 만들기
  2. 스크립트 프로젝트를 열고 왼쪽에서 개요 를 클릭합니다.
  3. 프로젝트 OAuth 범위에서 필요합니다.
  4. 호출하는 애플리케이션 코드에서 스크립트 OAuth 액세스 토큰을 생성합니다. (API 호출) API 자체가 사용하는 토큰이 아니라 스크립트가 필요합니다. 컨테이너는 Cloud 프로젝트 클라이언트 ID와 기록한 스크립트 범위

    Google 클라이언트 라이브러리는 이 토큰을 빌드하고 애플리케이션의 OAuth를 처리하는 데 도움을 주므로 대신 상위 수준의 '사용자 인증 정보'를 객체 스크립트 범위 사용 자세한 내용은 Apps Script API 빠른 시작에서 예시 확인 사용자 인증 정보 객체를 빌드하는 과정을 살펴보겠습니다

4단계: script.run 요청 실행

호출하는 애플리케이션이 구성되면 scripts.run 호출 각 API 호출은 다음 단계로 구성됩니다.

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

script.run API 호출의 예를 참고하세요. 참조하세요.

API 요청 예

다음 예는 다음에서 Apps Script API 실행 요청을 하는 방법을 보여줍니다. 애플리케이션 스크립트 기능을 호출하여 사용자 루트 디렉터리에 있습니다 Apps Script 프로젝트의 스크립트 ID 는 ENTER_YOUR_SCRIPT_ID_HERE 예시는 해당하는 Google API 클라이언트 라이브러리 있습니다.

대상 스크립트

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

Drive API를 사용 설정해야 프로젝트입니다.

또한 애플리케이션은 다음과 같은 OAuth 사용자 인증 정보를 전송해야 합니다. 다음 Drive 범위에 적용됩니다.

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

이 예제 애플리케이션은 Google 클라이언트 라이브러리를 사용하여 사용자 인증 정보 객체를 생성할 수 있습니다.

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

자바


/**
 * 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);
  }
}

자바스크립트

/**
 * 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 프로젝트는 표준 Cloud 프로젝트 Apps Script 프로젝트용으로 생성된 기본 프로젝트는 충분하지 않습니다. 이 표준 Cloud 프로젝트는 새 프로젝트일 수도 있고 기존 프로젝트일 수도 있습니다.

  2. 기본 매개변수 및 반환 유형 API는 다음 값을 전달하거나 반환할 수 없습니다. Apps Script 관련 객체 (예: 문서, blob, 캘린더, Drive 파일 등)을 애플리케이션입니다. 문자열, 배열, 객체, 숫자 및 부울을 전달하고 반환할 수 있습니다.

  3. OAuth 범위 API는 최소 필수 범위 1개입니다 즉, API를 사용하여 스크립트를 호출할 수 없습니다. 인증: 하나 이상의 서비스에 대한 승인이 필요하지 않습니다.

  4. 트리거가 없습니다. API에서 Apps Script를 만들 수 없습니다. 트리거를 만들 수 있습니다.