Skip to content
Sumin Byeon edited this page Dec 17, 2016 · 4 revisions

Getting Started with Python gspread Library

gspread is a Google Spreadsheet library for Python. This library is used in some part of our code in order to access data stored in Google Spreadsheet.

The whole process of getting started with the library was not too much of hassle, except that if we could figure out one thing in advance we could have save about 45 minutes. The part we struggled was the permission settings of a Google Spreadsheet document which we will explain shortly.

Google Service Account

Refer this document for details: http://gspread.readthedocs.io/en/latest/oauth2.html

In short, we have set up a service account with an email address of ${account_name}@{project_name}.iam.gserviceaccount.com. And stored the account key (credentials) as a .json file somewhere secure.

image

Authentication

import gspread
from oauth2client.service_account import ServiceAccountCredentials

scopes = ['https://spreadsheets.google.com/feeds']
credentials = ServiceAccountCredentials.from_json_keyfile_name('${json_file_path}', scopes)
gc = gspread.authorize(credentials)

However, at this point the gc does not have any document.

>>> gc.openall()
[]

Google Spreadsheet Document Permission

That's because the service account does not have any Google Spreadsheet document. In our cases, we have a spreadsheet document in a personal Google account (e.g., ******@gmail.com) and we would like to access it from our service account (via Google API). The solution was to grant an appropriate permission to the service account email.

image

After this step, we were able to access the document as follows:

>>> gc.openall()
[<Spreadsheet 'SB펀드' id:2fXeus_GRPmab7upvoOm_frQ3dHG6oOtEXQqi5_8v3EQ>]

Clone this wiki locally