JavaScript quickstart Stay organized with collections Save and categorize content based on your preferences.
Create a JavaScript web application that makes requests to the Google Apps Script API.
Quickstarts explain how to set up and run an app that calls aGoogle Workspace API. This quickstart uses asimplified authentication approach that is appropriate for a testingenvironment. For a production environment, we recommend learning aboutauthentication and authorizationbeforechoosing the access credentialsthat are appropriate for your app.
This quickstart uses Google Workspace's recommended API client librariesto handle some details of the authentication and authorization flow.
Objectives
- Set up your environment.
- Set up the sample.
- Run the sample.
Prerequisites
- Node.js & npm installed.
- A Google Cloudproject.
- A Google account with Google Drive enabled.
Set up your environment
To complete this quickstart, set up your environment.
Enable the API
Before using Google APIs, you need to turn them on in a Google Cloud project.You can turn on one or more APIs in a single Google Cloud project.In the Google Cloud console, enable the Google Apps Script API.
Configure the OAuth consent screen
If you're using a new Google Cloud project to complete this quickstart, configurethe OAuth consent screen. If you've alreadycompleted this step for your Cloud project, skip to the next section.
- In the Google Cloud console, go to Menu>Google Auth platform>Branding.
- If you have already configured the Google Auth platform, you can configure the following OAuth Consent Screen settings inBranding,Audience, andData Access. If you see a message that saysGoogle Auth platform not configured yet, clickGet Started:
- UnderApp Information, inApp name, enter a name for the app.
- InUser support email, choose a support email address where users can contact you if they have questions about their consent.
- ClickNext.
- UnderAudience, selectInternal.
- ClickNext.
- UnderContact Information, enter anEmail address where you can be notified about any changes to your project.
- ClickNext.
- UnderFinish, review theGoogle API Services User Data Policy and if you agree, selectI agree to the Google API Services: User Data Policy.
- ClickContinue.
- ClickCreate.
- For now, you can skip adding scopes. In the future, when you create an app for use outside of your Google Workspace organization, you must change theUser type toExternal. Then add the authorization scopes that your app requires. To learn more, see the fullConfigure OAuth consent guide.
Authorize credentials for a web application
To authenticate end users and access user data in your app, you need tocreate one or more OAuth 2.0 Client IDs. A client ID is used to identify asingle app to Google's OAuth servers. If your app runs on multiple platforms,you must create a separate client ID for each platform.- In the Google Cloud console, go to Menu>Google Auth platform>Clients.
- ClickCreate Client.
- ClickApplication type>Web application.
- In theName field, type a name for the credential. This name is only shown in the Google Cloud console.
- Add authorized URIs related to your app:
- Client-side apps (JavaScript)–UnderAuthorized JavaScript origins, clickAdd URI. Then, enter a URI to use for browser requests. This identifies the domains from which your application can send API requests to the OAuth 2.0 server.
- Server-side apps (Java, Python, and more)–UnderAuthorized redirect URIs, clickAdd URI. Then, enter an endpoint URI to which the OAuth 2.0 server can send responses.
- ClickCreate.
The newly created credential appears underOAuth 2.0 Client IDs.
Note the Client ID. Client secrets aren't used for Web applications.
Make a note of these credentials because you need them later in this quickstart.
Create an API key
- In the Google Cloud console, go to Menu>APIs & Services>Credentials.
- ClickCreate credentials>API key.
- Your new API key is displayed.
- Click Copy to copy your API key for use in your app's code. The API key can also be found in the "API keys" section of your project's credentials.
- ClickRestrict key to update advanced settings and limit use of your API key. For more details, seeApplying API key restrictions.
Set up the sample
- In your working directory, create a file named
index.html
. In the
index.html
file, paste the following sample code:apps-script/quickstart/index.html<!DOCTYPE html><html> <head> <title>Google Apps Script API Quickstart</title> <meta charset="utf-8" /> </head> <body> <p>Google Apps Script API Quickstart</p> <!--Add buttons to initiate auth sequence and sign out--> <button>Authorize</button> <button>Sign Out</button> <pre></pre> <script type="text/javascript"> /* exported gapiLoaded */ /* exported gisLoaded */ /* exported handleAuthClick */ /* exported handleSignoutClick */ // TODO(developer): Set to client ID and API key from the Developer Console const CLIENT_ID = '<YOUR_CLIENT_ID>'; const API_KEY = '<YOUR_API_KEY>'; // Discovery doc URL for APIs used by the quickstart const DISCOVERY_DOC = 'https://script.googleapis.com/$discovery/rest?version=v1'; // Authorization scopes required by the API; multiple scopes can be // included, separated by spaces. const SCOPES = 'https://www.googleapis.com/auth/script.projects'; let tokenClient; let gapiInited = false; let gisInited = false; document.getElementById('authorize_button').style.visibility = 'hidden'; document.getElementById('signout_button').style.visibility = 'hidden'; /** * Callback after api.js is loaded. */ function gapiLoaded() { gapi.load('client', initializeGapiClient); } /** * Callback after the API client is loaded. Loads the * discovery doc to initialize the API. */ async function initializeGapiClient() { await gapi.client.init({ apiKey: API_KEY, discoveryDocs: [DISCOVERY_DOC], }); gapiInited = true; maybeEnableButtons(); } /** * Callback after Google Identity Services are loaded. */ function gisLoaded() { tokenClient = google.accounts.oauth2.initTokenClient({ client_id: CLIENT_ID, scope: SCOPES, callback: '', // defined later }); gisInited = true; maybeEnableButtons(); } /** * Enables user interaction after all libraries are loaded. */ function maybeEnableButtons() { if (gapiInited && gisInited) { document.getElementById('authorize_button').style.visibility = 'visible'; } } /** * Sign in the user upon button click. */ function handleAuthClick() { tokenClient.callback = async (resp) => { if (resp.error !== undefined) { throw (resp); } document.getElementById('signout_button').style.visibility = 'visible'; document.getElementById('authorize_button').innerText = 'Refresh'; await createScript(); }; if (gapi.client.getToken() === null) { // Prompt the user to select a Google Account and ask for consent to share their data // when establishing a new session. tokenClient.requestAccessToken({prompt: 'consent'}); } else { // Skip display of account chooser and consent dialog for an existing session. tokenClient.requestAccessToken({prompt: ''}); } } /** * Sign out the user upon button click. */ function handleSignoutClick() { const token = gapi.client.getToken(); if (token !== null) { google.accounts.oauth2.revoke(token.access_token); gapi.client.setToken(''); document.getElementById('content').innerText = ''; document.getElementById('authorize_button').innerText = 'Authorize'; document.getElementById('signout_button').style.visibility = 'hidden'; } } /** * Creates a new 'Hello world' script. */ async function createScript() { let response; try { const createRequest = { resource: { title: 'My Script', }, }; response = await gapi.client.script.projects.create(createRequest); const updateContentRequest = { scriptId: response.result.scriptId, resource: { files: [{ name: 'hello', type: 'SERVER_JS', source: 'function helloWorld() {\n console.log("Hello, world!");\n}', }, { name: 'appsscript', type: 'JSON', source: '{"timeZone":"America/New_York","' + 'exceptionLogging":"CLOUD"}', }], }, }; response = await gapi.client.script.projects.updateContent(updateContentRequest); const output = `Script URL: https://script.google.com/d/${response.result.scriptId}/edit`; document.getElementById('content').innerText = output; } catch (err) { document.getElementById('content').innerText = err.message; return; } } </script> <script async defer src="https://apis.google.com/js/api.js" onload="gapiLoaded()"></script> <script async defer src="https://accounts.google.com/gsi/client" onload="gisLoaded()"></script> </body></html>
Replace the following:
YOUR_CLIENT_ID
: the client ID that you createdwhen youauthorized credentials for a web application.YOUR_API_KEY
: the API key that you created asaPrerequisite.
Run the sample
In your working directory, install thehttp-server package:
npm install http-server
In your working directory, start a web server:
npx http-server -p 8000
- In your browser, navigate to
http://localhost:8000
. - You see a prompt to authorize access:
- If you're not already signed in to your Google Account, sign in when prompted. If you're signed in to multiple accounts, select one account to use for authorization.
- ClickAccept.
Your JavaScript application runs and calls the Google Apps Script API.
Next steps
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-07-02 UTC.