Java quickstart Stay organized with collections Save and categorize content based on your preferences.
Page Summary
This quickstart guides you through creating a Java command-line application that interacts with the Google Apps Script API using simplified authentication suitable for testing.
To follow along, you need Java 11+, Gradle 7.0+, a Google Cloud project, and a Google account with Google Drive enabled.
The setup process involves enabling the Google Apps Script API in your Google Cloud project, configuring the OAuth consent screen, and authorizing credentials for a desktop application by downloading a
credentials.jsonfile.You will prepare your workspace by creating a project structure and build file, then set up the sample code in a Java file that includes logic to create a new script project and upload files.
Running the sample for the first time will prompt you to authorize access, and subsequent runs will not require reauthorization as the information is stored locally.
Create a Java command-line 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
- Java 11 or greater.
- Gradle 7.0 or greater.
- A Google Cloud project.
- 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 desktop 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>Desktop app.
- In theName field, type a name for the credential. This name is only shown in the Google Cloud console.
- ClickCreate.
The newly created credential appears under "OAuth 2.0 Client IDs."
- Save the downloaded JSON file as
credentials.json, and move the file to your working directory.
Prepare the workspace
In your working directory, create a new project structure:
gradle init --type basicmkdir -p src/main/java src/main/resourcesIn the
src/main/resources/directory, copy thecredentials.jsonfilethat you previously downloaded.Open the default
build.gradlefile and replace its contents with thefollowing code:appsScript/quickstart/build.gradleapplyplugin:'java'applyplugin:'application'mainClassName='AppsScriptQuickstart'sourceCompatibility=11targetCompatibility=11version='1.0'repositories{mavenCentral()}dependencies{implementation'com.google.api-client:google-api-client:2.0.0'implementation'com.google.oauth-client:google-oauth-client-jetty:1.34.1'implementation'com.google.apis:google-api-services-script:v1-rev20220323-2.0.0'}
Set up the sample
In the
src/main/java/directory, create a new Java file with a name thatmatches themainClassNamevalue in yourbuild.gradlefile.Include the following code in your new Java file:
appsScript/quickstart/src/main/java/AppsScriptQuickstart.javaimportcom.google.api.client.auth.oauth2.Credential;importcom.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;importcom.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;importcom.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;importcom.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;importcom.google.api.client.googleapis.javanet.GoogleNetHttpTransport;importcom.google.api.client.http.javanet.NetHttpTransport;importcom.google.api.client.json.JsonFactory;importcom.google.api.client.json.gson.GsonFactory;importcom.google.api.client.util.store.FileDataStoreFactory;importcom.google.api.services.script.Script;importcom.google.api.services.script.model.Content;importcom.google.api.services.script.model.CreateProjectRequest;importcom.google.api.services.script.model.File;importcom.google.api.services.script.model.Project;importjava.io.FileNotFoundException;importjava.io.IOException;importjava.io.InputStream;importjava.io.InputStreamReader;importjava.security.GeneralSecurityException;importjava.util.Arrays;importjava.util.Collections;importjava.util.List;publicclassAppsScriptQuickstart{privatestaticfinalStringAPPLICATION_NAME="Apps Script API Java Quickstart";privatestaticfinalJsonFactoryJSON_FACTORY=GsonFactory.getDefaultInstance();privatestaticfinalStringTOKENS_DIRECTORY_PATH="tokens";/** * Global instance of the scopes required by this quickstart. * If modifying these scopes, delete your previously saved credentials folder at /secret. */privatestaticfinalList<String>SCOPES=Collections.singletonList("https://www.googleapis.com/auth/script.projects");privatestaticfinalStringCREDENTIALS_FILE_PATH="/credentials.json";/** * Creates an authorized Credential object. * * @param HTTP_TRANSPORT The network HTTP Transport. * @return An authorized Credential object. * @throws IOException If the credentials.json file cannot be found. */privatestaticCredentialgetCredentials(finalNetHttpTransportHTTP_TRANSPORT)throwsIOException{// Load client secrets.InputStreamin=AppsScriptQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);if(in==null){thrownewFileNotFoundException("Resource not found: "+CREDENTIALS_FILE_PATH);}GoogleClientSecretsclientSecrets=GoogleClientSecrets.load(JSON_FACTORY,newInputStreamReader(in));// Build flow and trigger user authorization request.GoogleAuthorizationCodeFlowflow=newGoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT,JSON_FACTORY,clientSecrets,SCOPES).setDataStoreFactory(newFileDataStoreFactory(newjava.io.File(TOKENS_DIRECTORY_PATH))).setAccessType("offline").build();LocalServerReceiverreceiver=newLocalServerReceiver.Builder().setPort(8888).build();returnnewAuthorizationCodeInstalledApp(flow,receiver).authorize("user");}publicstaticvoidmain(String...args)throwsIOException,GeneralSecurityException{// Build a new authorized API client service.finalNetHttpTransportHTTP_TRANSPORT=GoogleNetHttpTransport.newTrustedTransport();Scriptservice=newScript.Builder(HTTP_TRANSPORT,JSON_FACTORY,getCredentials(HTTP_TRANSPORT)).setApplicationName(APPLICATION_NAME).build();Script.Projectsprojects=service.projects();// Creates a new script project.ProjectcreateOp=projects.create(newCreateProjectRequest().setTitle("My Script")).execute();// Uploads two files to the project.Filefile1=newFile().setName("hello").setType("SERVER_JS").setSource("function helloWorld() {\n console.log(\"Hello, world!\");\n}");Filefile2=newFile().setName("appsscript").setType("JSON").setSource("{\"timeZone\":\"America/New_York\",\"exceptionLogging\":\"CLOUD\"}");Contentcontent=newContent().setFiles(Arrays.asList(file1,file2));ContentupdatedContent=projects.updateContent(createOp.getScriptId(),content).execute();// Logs the project URL.System.out.printf("https://script.google.com/d/%s/edit\n",updatedContent.getScriptId());}}
Run the sample
Run the sample:
gradle run
- The first time you run the sample, it prompts you 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 Java application runs and calls the Google Apps Script API.
Authorization information is stored in the file system, so the next time you run the sample code, you aren't prompted for authorization.
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-12-11 UTC.