Python Quickstart

Complete the steps described in the rest of this page to create a simple Python command-line application that makes requests to the Google Apps Script API.

Prerequisites

To run this quickstart, you need the following prerequisites:

  • Python 2.6 or greater.
  • The pip package management tool
  • A Google Cloud Platform project with the API enabled. To create a project and enable an API, refer to Create a project and enable the API

    Note: For this quickstart, you are enabling the "Google Apps Script API".
    
    • Authorization credentials for a desktop application. To create credentials for a desktop application, refer to Create credentials.
    • A Google account with Google Drive enabled

    Step 1: Install the Google client library

    To install the Google client library for Python, run the following command:

      pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
    

    For alternate installation options, refer to the Python library's Installation section.

    Step 2: Configure the sample

    To configure the sample:

    1. In your working directory, create a file named quickstart.py.
    2. Include the following code in quickstart.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 the
      project, and log the script's URL to the user.
      """
      from __future__ import print_function
      import os.path
      from googleapiclient import errors
      from googleapiclient.discovery import build
      from google_auth_oauthlib.flow import InstalledAppFlow
      from google.auth.transport.requests import Request
      from google.oauth2.credentials import Credentials
      
      # 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()
      
      def main():
          """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.
          if os.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.
          if not creds or not creds.valid:
              if creds and creds.expired and creds.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 run
              with open('token.json', 'w') as token:
                  token.write(creds.to_json())
      
          service = build('script', 'v1', credentials=creds)
      
          # Call the Apps Script API
          try:
              # Create a new project
              request = {'title': 'My Script'}
              response = service.projects().create(body=request).execute()
      
              # Upload two files to the project
              request = {
                  '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')
          except errors.HttpError as error:
              # The API encountered a problem.
              print(error.content)
      
      
      if __name__ == '__main__':
          main()

    Step 3: Run the sample

    To run the sample:

    1. From the command-line, execute the following command:

      python quickstart.py
      
    2. (optional). If this is your first time running the sample, the sample opens a new window prompting you to authorize access to your data:

      1. If you are not already signed in to your Google account, you are prompted to sign in. If you are signed in to multiple Google accounts, you are asked to select one account to use for the authorization.
      1. Click Accept. The app is authorized to access your data.
    3. The sample executes.

    If you have problems, refer to the Troubleshoot the sample section.

    Troubleshoot the sample

    This section describes some common issues that you may encounter while attempting to run this quickstart and suggests possible solutions.

    AttributeError: 'Module_six_moves_urllib_parse' object has no attribute 'urlparse'

    This error can occur in Mac OSX where the default installation of the six module (a dependency of the Python library) is loaded before the one that pip installed. To fix the issue, add pip's install location to the PYTHONPATH system environment variable:

    1. Determine pip's install location with the following command:

      pip show six | grep "Location:" | cut -d " " -f2
      
    2. Add the following line to your ~/.bashrc file, replacing <pip_install_path> with the value determined above:

      export PYTHONPATH=$PYTHONPATH:<pip_install_path>
      
    3. Reload your ~/.bashrc file in any open terminal windows using the following command:

      source ~/.bashrc
      

    TypeError: sequence item 0: expected str instance, bytes found

    This error is due to a bug in httplib2. To resolve this problem, upgrade to the latest version of httplib2 using this command:

    pip install --upgrade httplib2</code>
    </pre>
    

    Cannot uninstall 'six'

    When running the pip install command you may receive the following error:

    "Cannot uninstall 'six'. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall."

    This error occurs on Mac OSX when pip attempts to upgrade the pre-installed six package. To work around this issue, add the flag --ignore-installed six to the pip install command listed in step 2.

    This app isn't verified

    If the OAuth consent screen displays the warning "This app isn't verified," your app is requesting scopes that provide access to sensitive user data. If your application uses sensitive scopes, your your app must go through the verification process to remove that warning and other limitations. During the development phase you can continue past this warning by clicking Advanced > Go to {Project Name} (unsafe).

    Further reading

    For further information on the APIs used in this quickstart, refer to the following: