Here we install the required Python libraries and create a test Sheet to make sure everything works. More information can be found in the Google documentation here:

Download Python (mainly for Windows Users)

Python 3 comes standard on Linux and macOS. But Windows users likely do not have it installed as a default. If you need Python and the pip installer, go to https://www.python.org/downloads/ and download the latest version of Python 3.x for your operating system.

Install Python Libraries

We need two libraries:

which we can install with pip (which is installed with Python 3). Go to a command prompt and type:

pip3 install google-api-python-client google-auth-oauthlib

Create A Test Sheet

To test everything, let's go ahead and create a Sheet.

Log in to your Google account and go to Docs and create a new Sheet and give it a name like Test Sheet:

Under File -> Share, add the "client_email" address from the .json file created in the previous step. You can open the .json file in a text editor to find this value.

You'll also need the spreadsheetID which you can get from the URL. It is the big long gibberish value between "/d/" and "/edit". (more info)

Run Example

Then, try running this example:

You need to edit this example with your specific info. See below.
from google.oauth2.service_account import Credentials
from googleapiclient.discovery import build

SERVICE_ACCOUNT_FILE = 'YOUR_CREDENTIALS_FILE.json'
SPREADSHEET_ID = 'YOUR_SPREADSHEET_ID'
SCOPES = ['https://spreadsheets.google.com/feeds',
          'https://www.googleapis.com/auth/drive']

credentials = Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)

service = build('sheets', 'v4', credentials=credentials)

sheet = service.spreadsheets()

range = 'A1'
values = [ ['test'], ]
body = {'values' : values}

sheet.values().append(spreadsheetId=SPREADSHEET_ID, 
                      valueInputOption='RAW',
                      range=range,
                      body=body).execute()

Replace YOUR_CREDENTIALS_FILE with the actual name of your .json file and YOUR_SPREADSHEET_ID with what you got from the URL. Save the above as something like gspread_test.py and then try running it:

python3 gspread_test.py

It should run without any errors. If you then go look at your spreadsheet, you should see test in cell A1, like this:

If any errors do occur, try and troubleshoot them. Hopefully they will contain helpful messages.

If the above test worked, move on to the next step.

This guide was first published on Jan 17, 2020. It was last updated on Jan 17, 2020.

This page (Python Setup) was last updated on Apr 17, 2021.

Text editor powered by tinymce.