Python quickstart

Create a Python command-line application that makes requests to theGoogle 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.
  • Install the client library.
  • Set up the sample.
  • Run the sample.

Prerequisites

To run this quickstart, you need the following 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.

Install the Google client library

  • Install the Google client library for Python:

    pipinstall--upgradegoogle-api-python-clientgoogle-auth-httplib2google-auth-oauthlib

Configure the sample

  1. In your working directory, create a file namedquickstart.py.
  2. Include the following code inquickstart.py:

    apps_script/quickstart/quickstart.py
    """Shows basic usage of the Apps Script API.Call the Apps Script API to create a new script project, upload a file to theproject, and log the script's URL to the user."""importos.pathfromgoogle.auth.transport.requestsimportRequestfromgoogle.oauth2.credentialsimportCredentialsfromgoogle_auth_oauthlib.flowimportInstalledAppFlowfromgoogleapiclientimporterrorsfromgoogleapiclient.discoveryimportbuild# If modifying these scopes, delete the file token.json.SCOPES=["https://www.googleapis.com/auth/script.projects"]SAMPLE_CODE="""function helloWorld() {  console.log("Hello, world!");}""".strip()SAMPLE_MANIFEST="""{  "timeZone": "America/New_York",  "exceptionLogging": "CLOUD"}""".strip()defmain():"""Calls the Apps Script API."""creds=None# The file token.json stores the user's access and refresh tokens, and is# created automatically when the authorization flow completes for the first# time.ifos.path.exists("token.json"):creds=Credentials.from_authorized_user_file("token.json",SCOPES)# If there are no (valid) credentials available, let the user log in.ifnotcredsornotcreds.valid:ifcredsandcreds.expiredandcreds.refresh_token:creds.refresh(Request())else:flow=InstalledAppFlow.from_client_secrets_file("credentials.json",SCOPES)creds=flow.run_local_server(port=0)# Save the credentials for the next runwithopen("token.json","w")astoken:token.write(creds.to_json())try:service=build("script","v1",credentials=creds)# Call the Apps Script API# Create a new projectrequest={"title":"My Script"}response=service.projects().create(body=request).execute()# Upload two files to the projectrequest={"files":[{"name":"hello","type":"SERVER_JS","source":SAMPLE_CODE},{"name":"appsscript","type":"JSON","source":SAMPLE_MANIFEST,},]}response=(service.projects().updateContent(body=request,scriptId=response["scriptId"]).execute())print("https://script.google.com/d/"+response["scriptId"]+"/edit")excepterrors.HttpErroraserror:# The API encountered a problem.print(error.content)if__name__=="__main__":main()

Run the sample

  1. In your working directory, build and run the sample:

    python3quickstart.py
  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 Python 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-02 UTC.