Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read a Google Sheet with Python using API Key instead of OAuth Client ID [Python]

While there are several useful articles on how to use OAuth Client IDs to generate credentials needed for reading and writing to Google Sheets, I have been unable to make sense of how one would use the alternative API Key (token) in such a context.

I've blindly attempted to simply pass the token string into gspread.authorize(TOKEN) but, not surprisingly, received an error: AttributeError: 'str' object has no attribute 'access_token'

Thanks in advance for any advice

like image 578
MoTrip Avatar asked Jul 04 '17 07:07

MoTrip


People also ask

How do I authenticate a Google Sheet in Python?

Go to your environment's terminal app and run pip install google-auth-httplib2 and pip install google-api-python-client. These are both necessary to authenticate our Google's secret credentials and to connect with the spreadsheet so make sure you have them installed.

How do I get access token in Google Sheets API?

Obtaining Access Token and Refresh TokenNavigate to OAuth 2.0 Playground and click the OAuth 2.0 Configuration button in the top right corner of your screen. Select Use your own OAuth credentials, and provide the obtained Client ID and Client Secret values. Click on Close.


1 Answers

First of all, the Google Sheet api can use Api key.
The main difference between Api key and OAuth 2.0 is that the Api key can only access public data.

For REST http request, You can append the query parameter key=yourAPIKey to all request URLs.

For python, see the google-api-python-client library's reference.
The build() function has a parameter named developerKey.
I wrote a simple example which is modified from the offical quickstart.

#!/usr/bin/env python

from __future__ import print_function
import httplib2
import os

from apiclient import discovery


def main(key=None):
    discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
                    'version=v4')
    service = discovery.build(
        'sheets',
        'v4',
        http=httplib2.Http(),
        discoveryServiceUrl=discoveryUrl,
        developerKey=key)

    spreadsheetId = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms'
    rangeName = 'Class Data!A2:E'
    result = service.spreadsheets().values().get(
        spreadsheetId=spreadsheetId, range=rangeName).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('%s, %s' % (row[0], row[4]))


if __name__ == '__main__':
    from sys import argv

    if len(argv) == 2:
        main(key=argv[1])
    else:
        main()

Some useful offical links.
https://developers.google.com/sheets/api/guides/authorizing
https://developers.google.com/api-client-library/python/auth/api-keys

However,most popular third library based on offical library does not expose the developerKey parameter.

like image 77
drinkmystery Avatar answered Oct 20 '22 04:10

drinkmystery