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 Sheets API.


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
  • Authorization credentials for a desktop application. To learn how to create credentials for a desktop application, refer to Create credentials.
  • A Google account.

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
  2. Include the following code in

    from __future__ import print_function
    import os.path
    from google.auth.transport.requests import Request
    from google.oauth2.credentials import Credentials
    from google_auth_oauthlib.flow import InstalledAppFlow
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
    # If modifying these scopes, delete the file token.json.
    SCOPES = ['']
    # The ID and range of a sample spreadsheet.
    SAMPLE_SPREADSHEET_ID = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms'
    SAMPLE_RANGE_NAME = 'Class Data!A2:E'
    def main():
        """Shows basic usage of the Sheets API.
        Prints values from a sample spreadsheet.
        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:
                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:
            service = build('sheets', 'v4', credentials=creds)
            # Call the Sheets API
            sheet = service.spreadsheets()
            result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID,
            values = result.get('values', [])
            if not values:
                print('No data found.')
            print('Name, Major:')
            for row in values:
                # Print columns A and E, which correspond to indices 0 and 4.
                print('%s, %s' % (row[0], row[4]))
        except HttpError as err:
    if __name__ == '__main__':

Step 3: Run the sample

To run the sample:

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

  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

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 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 selecting Advanced > Go to {Project Name} (unsafe).

File not found error for credentials.json

When running the sample, you might receive a file not found or no such file error regarding credentials.json.

This error occurs when you have not authorized the desktop application credentials as detailed in the Prerequisites section above. To learn how to create credentials for a desktop application, go to Create credentials.

Once you create the credentials, make sure the downloaded JSON file is saved as credentials.json. Then move the file to your working directory with the rest of the sample quickstart code.

Further reading

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