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
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With