The gspread Package
Last updated
Was this helpful?
Last updated
Was this helpful?
The gspread
package provides an interface to Google Sheet documents via the Google Sheets and Google Drive APIs.
Google APIs:
The gspread
Package:
This document was originally adapted from an excellent .
First install the package (and a dependent auth-related package) using Pip, if necessary:
NOTE: the example code below has been tested against
gspread==3.6.0
andoauth2client==4.1.3
Finally, before committing, add the credentials filepath to your repository's ".gitignore" file to ensure it does not get tracked in version control or uploaded to GitHub:
If you create your own, make sure it contains a sheet called "Products-2021" with column headers id
, name
, department
, price
, and availability_date
. If you choose a different sheet name, customize it via an environment variable called SHEET_NAME
. Finally, modify the document's sharing settings to grant "edit" privileges to the "client email" address specified in the credentials file.
Visit the . Create a new project, or select an existing one. Click on your project, then from the project page, search for the "Google Sheets API" and enable it. Also search for the "Google Drive API" and enable it.
From either API page, or from the page, follow a process to create and download credentials to use the APIs: 1. Click "Create Credentials" for a "Service Account". Follow the prompt to create a new service account named something like "spreadsheet-service", and add a role of "Editor". 2. Click on the newly created service account from the "Service Accounts" section, and click "Add Key" to create a new "JSON" credentials file for that service account. Download the resulting .json file (this might happen automatically). 3. Move a copy of the credentials file into your project repository, typically into the root directory or perhaps a directory called "auth", and note its filepath. For the example below, we'll refer to a file called "google-credentials.json" in an "auth" directory (i.e. "auth/google-credentials.json").
Use this , or create your own. Note the document's unique identifier (e.g. 1_hisQ9kNjmc-cafIasMue6IQG-ql_6TcqFGpVNOkUSE
) from its URL, and store the identifier in an environment variable called GOOGLE_SHEET_ID
.