Java quickstart

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

  • 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.

    Enable the 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.

  1. In the Google Cloud console, go to Menu>Google Auth platform>Branding.

    Go to Branding

  2. 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:
    1. UnderApp Information, inApp name, enter a name for the app.
    2. InUser support email, choose a support email address where users can contact you if they have questions about their consent.
    3. ClickNext.
    4. UnderAudience, selectInternal.
    5. ClickNext.
    6. UnderContact Information, enter anEmail address where you can be notified about any changes to your project.
    7. ClickNext.
    8. UnderFinish, review theGoogle API Services User Data Policy and if you agree, selectI agree to the Google API Services: User Data Policy.
    9. ClickContinue.
    10. ClickCreate.
  3. 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.
  1. In the Google Cloud console, go to Menu>Google Auth platform>Clients.

    Go to Clients

  2. ClickCreate Client.
  3. ClickApplication type>Desktop app.
  4. In theName field, type a name for the credential. This name is only shown in the Google Cloud console.
  5. ClickCreate.

    The newly created credential appears under "OAuth 2.0 Client IDs."

  6. Save the downloaded JSON file ascredentials.json, and move the file to your working directory.

Prepare the workspace

  1. In your working directory, create a new project structure:

    gradle init --type basicmkdir -p src/main/java src/main/resources
  2. In thesrc/main/resources/ directory, copy thecredentials.json filethat you previously downloaded.

  3. Open the defaultbuild.gradle file and replace its contents with thefollowing code:

    appsScript/quickstart/build.gradle
    applyplugin:'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

  1. In thesrc/main/java/ directory, create a new Java file with a name thatmatches themainClassName value in yourbuild.gradle file.

  2. Include the following code in your new Java file:

    appsScript/quickstart/src/main/java/AppsScriptQuickstart.java
    importcom.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

  1. Run the sample:

    gradle run
  1. The first time you run the sample, it prompts you to authorize access:
    1. 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.
    2. 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-07-07 UTC.