Execute Functions with the Apps Script API Stay organized with collections Save and categorize content based on your preferences.
Page Summary
The
scripts.runmethod of the Google Apps Script API allows calling applications to remotely execute specified Apps Script functions and receive responses.To use the
scripts.runmethod, the script project must be deployed as an API executable, the calling application must provide a properly scoped OAuth token, and both must share a common standard Google Cloud project with the Apps Script API enabled.The
scripts.runmethod requires the script project ID, the name of the function to execute, and any required parameters.The API can only pass and return basic data types (strings, arrays, objects, numbers, booleans), not complex Apps Script objects.
There are several limitations to the API, including the requirement for a common standard Cloud project, restriction to basic data types, inability to call scripts without scopes, and the lack of trigger creation functionality.
The Google Apps Script API provides ascripts.run methodthat remotely executes a specified Apps Script function. You can use this methodin acalling application to run a function in one of your script projectsremotely and receive a response.
Requirements
You must satisfy the following requirements before a calling application can usethescripts.runmethod.You must:
Deploy the script project as an API executable. You candeploy, undeploy, and redeploy projects as needed.
Provide a properly scoped OAuth token for the execution.This OAuth token must cover all thescopesused by the script, not just the ones used by the called function. See thefull list ofauthorization scopesin the method reference.
Ensure that the script and the calling application'sOAuth2client share a common Google Cloud project.The Cloud project must be astandard Cloud project;default projects created for Apps Script projects are insufficient. You can use a new standard Cloud project or an existing one.
Enable the Google Apps Script APIin the Cloud project.
script.run requestsif their script project changes ownership to eithershared driveor to an outside domain account. Fix this by redeploying the script in thenew domain or shared drive, or by moving the script back to its original domain.Warning: Script projects that use sensitive scopes are subject toreview by Google. Users attempting to authorize apps that call such scriptswith the Apps Script API might see a warning screen saying the app is unverifiedby Google. See theOAuth client verification guidefor more details.Thescripts.run method
Thescripts.runmethod requires key identifying information in order to run:
- TheID of the script project.
- Thename of the functionto execute.
- Thelist of parametersthe function requires (if any).
You can optionally configure your script to execute indevelopment mode.This mode executes with the most recentlysaved version of the script projectrather than the most recently deployed version. Do this by setting thedevMode boolean in therequest bodytotrue. Only the owner of the script can execute it in development mode.
Handling parameter data types
Using the Apps Script APIscripts.run methodusually involves sending data to Apps Script as function parameters andgetting data back as function return values. The API can only take and returnvalues with basic types: strings, arrays, objects, numbers, and booleans. Theseare similar to the basic types in JavaScript. More complexApps Script objects likeDocumentorSheet cannot be passed intoor from the script project by the API.
When your calling application is written in a strongly-type language such asJava, it passes in parameters as a list or array of generic objectscorresponding to these basic types. In many cases, you can apply simpletype conversions automatically. For example, a function that takes a numberparameter can be given a JavaDouble orInteger orLong object as aparameter without extra handling.
When the API returns the function response, you often need to cast thereturned value to the correct type before it can be used. Here are someJava-based examples:
- Numbers returned by the API to a Java application arrive as
java.math.BigDecimalobjects, and may need to be converted toDoublesorinttypes as needed. If the Apps Script function returns an array of strings, a Java applicationcasts the response into a
List<String>object:List<String> mylist = (List<String>)(op.getResponse().get("result"));If you are looking to return an array of
Bytes, you may find it convenientto encode the array as a base64 String within the Apps Script function andreturn that String instead:return Utilities.base64Encode(myByteArray); // returns a String.
Theexample code samples below illustrate ways ofinterpreting the API response.
General procedure
The following describes the general procedure for using the Apps Script APIto execute Apps Script functions:
Step 1: Set up the common Cloud project
Both your script and the calling application need to share the sameCloud project. This Cloud project can be an existing project ora new project created for this purpose. Once you have a Cloud project, youmustswitch your script project to use it.
Step 2: Deploy the script as an API executable
- Open the Apps Script project with the functions you want to use.
- At the top right, clickDeploy>New Deployment.
- In the dialog that opens, click Enable deployment types
>API Executable.
- In the "Who has access" drop-down menu, select the users who are allowed to call the script's functions using the Apps Script API.
- ClickDeploy.
Step 3: Configure the calling application
The calling application must enable the Apps Script API and establish OAuthcrendentials before it can be used. You must have access to the Cloud projectto do this.
- Configure the Cloud project that your calling application and script are using. You can do this with the following steps:
- Open the script project and at the left, clickOverview
.
- UnderProject Oauth scopes, record all the scopes that the script requires.
In the calling application code, generate a script OAuth access token for the API call. This is not a token the API itself uses, but rather one the script requires when executing. It should be built using the Cloud project client ID and the script scopes you recorded.
TheGoogle client libraries can greatly assist in building this token and handling OAuth for the application, usually allowing you to instead build a higher-level "credentials" object using the script scopes. See theApps Script API quickstarts for examples of building a credentials object from a list of scopes.
Step 4: Make thescript.run request
Once the calling application is configured, you can makescripts.run calls. Each APIcall consists of the following steps:
- Build anAPI requestusing the script ID, function name, and any requiredparameters.
- Make the
scripts.runcall and include the script OAuth token you built in theheader (if using a basicPOSTrequest) or else use a credentials objectyou built with the script scopes. - Allow the script to finish executing. Scripts are allowed to take up tosix minutes of execution time, so your application should allow for this.
- Upon finishing, the script function may return a value, which the APIdelivers back to the application if the value is a supported type.
You can findexamples ofscript.run API callsbelow.
script.run API request is executing a script function, it can result in aAuthorization is required to perform that action error. To avoid this, refresh your access token prior to making the API call if itsexpires_in time is less than the maximum script runtime for your account (6 minutes in most cases).To refresh your access token, you can add the following snippet before your
script.run API request:if (credential.getExpiresInSeconds() <= 360) { credential.refreshToken();}API request examples
The following examples show how to make an Apps Script API execution request invarious languages, calling an Apps Script function to print out a list offolders in the user's root directory. The script ID of the Apps Script projectcontaining the executed function must be specified where indicated withENTER_YOUR_SCRIPT_ID_HERE. The examples rely on theGoogle API Client libraries for their respectivelanguages.
Target Script
The function in this script uses the Drive API.
You mustenable the Drive API in theproject hosting the script.
Additionally, calling applications must send OAuth credentials which includethe following Drive scope:
https://www.googleapis.com/auth/drive
The example applications here use the Google client libraries to buildcredential objects for OAuth using this scope.
/***Returnthesetoffoldernamescontainedintheuser's root folder as an*object(withfolderIDsaskeys).*@return{Object}AsetoffoldernameskeyedbyfolderID.*/functiongetFoldersUnderRoot(){constroot=DriveApp.getRootFolder();constfolders=root.getFolders();constfolderSet={};while(folders.hasNext()){constfolder=folders.next();folderSet[folder.getId()]=folder.getName();}returnfolderSet;}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. */privatestaticHttpRequestInitializersetHttpTimeout(finalHttpRequestInitializerrequestInitializer){returnnewHttpRequestInitializer(){@Overridepublicvoidinitialize(HttpRequesthttpRequest)throwsIOException{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 */publicstaticScriptgetScriptService()throwsIOException{Credentialcredential=authorize();returnnewScript.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 */publicstaticStringgetScriptError(Operationop){if(op.getError()==null){returnnull;}// 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.StringBuildersb=newStringBuilder("\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");returnsb.toString();}publicstaticvoidmain(String[]args)throwsIOException{// ID of the script to call. Acquire this from the Apps Script editor,// under Publish > Deploy as API executable.StringscriptId="ENTER_YOUR_SCRIPT_ID_HERE";Scriptservice=getScriptService();// Create an execution request object.ExecutionRequestrequest=newExecutionRequest().setFunction("getFoldersUnderRoot");try{// Make the API request.Operationop=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(Stringid:folderSet.keySet()){System.out.printf("\t%s (%s)\n",folderSet.get(id),id);}}}}catch(GoogleJsonResponseExceptione){// 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. */functioncallScriptFunction(){constscriptId='<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){constresult=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));}elseif(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.consterror=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(leti=0;i <error.scriptStackTraceElements.length;i++){consttrace=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).constfolderSet=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
import{GoogleAuth}from'google-auth-library';import{google}from'googleapis';/** * Calls an Apps Script function to list the folders in the user's root Drive folder. */asyncfunctioncallAppsScript(){// The ID of the Apps Script project to call.constscriptId='1xGOh6wCm7hlIVSVPKm0y_dL-YqetspS5DEVmMzaxd_6AAvI-_u8DSgBT';// Authenticate with Google and get an authorized client.// TODO (developer): Use an appropriate auth mechanism for your app.constauth=newGoogleAuth({scopes:'https://www.googleapis.com/auth/drive',});// Create a new Apps Script API client.constscript=google.script({version:'v1',auth});constresp=awaitscript.scripts.run({auth,requestBody:{// The name of the function to call in the Apps Script project.function:'getFoldersUnderRoot',},scriptId,});if(resp.data.error?.details?.[0]){// The API executed, but the script returned an error.// Extract the error details.consterror=resp.data.error.details[0];console.log(`Script error message:${error.errorMessage}`);console.log('Script error stacktrace:');if(error.scriptStackTraceElements){// Log the stack trace.for(leti=0;i <error.scriptStackTraceElements.length;i++){consttrace=error.scriptStackTraceElements[i];console.log('\t%s: %s',trace.function,trace.lineNumber);}}}else{// The script executed successfully.// The structure of the response depends on the Apps Script function's return value.constfolderSet=resp.data.response??{};if(Object.keys(folderSet).length===0){console.log('No folders returned!');}else{console.log('Folders under your root folder:');Object.keys(folderSet).forEach((id)=>{console.log('\t%s (%s)',folderSet[id],id);});}}}Python
importgoogle.authfromgoogleapiclient.discoveryimportbuildfromgoogleapiclient.errorsimportHttpErrordefmain():"""Runs the sample."""# pylint: disable=maybe-no-memberscript_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"inresponse:# 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"inerror:# There may not be a stacktrace if the script didn't start# executing.print("Script error stacktrace:")fortraceinerror["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",{})ifnotfolder_set:print("No folders returned!")else:print("Folders under your root folder:")forfolder_id,folderinfolder_set.items():print(f"\t{0} ({1}).{format(folder,folder_id)}")exceptHttpErroraserror:# The API encountered a problem before the script started executing.print(f"An error occurred:{error}")print(error.content)if__name__=="__main__":main()Limitations
The Apps Script API has several limitations:
A common Cloud project. The script being called and thecalling application must share a Cloud project. The Cloud project must be astandard Cloud project;default projects created for Apps Script projects are insufficient. Thestandard Cloud project can be a new project or an existing one.
Basic parameter and return types. The API cannot pass or returnApps Script-specific objects (such asDocuments,Blobs,Calendars,Drive Files, etc.) to theapplication. Only basic types such as strings, arrays, objects, numbers, andbooleans can be passed and returned.
OAuth scopes. The API can only execute scripts that have at leastone required scope. This means you cannot use the API to call a scriptthat does not require authorization of one or more services.
No triggers.The API cannot create Apps Scripttriggers.
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-12-11 UTC.