betodealmeida / gsheets-db-api

A Python DB-API and SQLAlchemy dialect to Google Spreasheets

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Implement auth

betodealmeida opened this issue · comments

Can we query private spreadsheets?

(1) Create service account (see instructions).

screen shot 2018-09-26 at 3 30 14 pm

(2) Download key as JSON.

(3) Manage API client access at https://admin.google.com/${DOMAIN}/AdminHome?chromeless=1#OGX:ManageOauthClients

  • Add the "Unique ID" from step 1 as the "Client Name"
  • Add https://www.googleapis.com/auth/spreadsheets.readonly as the scope.

(4) Make sure to impersonate a user, otherwise it will fail:

from __future__ import print_function
from google.oauth2 import service_account
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools

# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']

def main():
    """Shows basic usage of the Sheets API.
    Prints values from a sample spreadsheet.
    """
    SERVICE_ACCOUNT_FILE = '/Users/bdealmeida/Downloads/gsheetsdb-2bb6767cc084.json'
    creds = service_account.Credentials.from_service_account_file(
        SERVICE_ACCOUNT_FILE, scopes=SCOPES)
    delegated_creds = creds.with_subject('roberto@dealmeida.net')
    service = build('sheets', 'v4', credentials=delegated_creds)

    # Call the Sheets API
    SPREADSHEET_ID = '1hsxoXlOTQzMgNdS4Hp6tg-nVRq8v4Mc7syYZsOHltTk'
    RANGE_NAME = 'A2:B3'
    result = service.spreadsheets().values().get(spreadsheetId=SPREADSHEET_ID,
                                                range=RANGE_NAME).execute()
    values = result.get('values', [])

    if not values:
        print('No data found.')
    else:
        print('Name, Major:')
        for row in values:
            # Print columns A and E, which correspond to indices 0 and 4.
            print(row)

if __name__ == '__main__':
    main()

Scope should be https://spreadsheets.google.com/feeds instead.