Search code examples
pythongoogle-sheets-api

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


Solution

  • 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.