How to use JSON string as credentials instead of filepath for Python with Google API

Chris from

I'm looking for a way to build a Google Credentials object and access my Google Sheets spreadsheet without having to reference another file containing my client_secret.json data. This feels like it should be quite easy to do, I just want to be able to copy the JSON into my python script and access it that way, but I haven't been able to find a way to do it.

According to https://oauth2client.readthedocs.io/en/latest/source/oauth2client.file.html it seems like the only way to use the current method is with a filepath, but again if the file literally only contains JSON, it seems like there should be a way of just putting the JSON in my python script and using it from there.

Listed below is how I currently get the values from my json file.

SCOPES = 'https://www.googleapis.com/auth/spreadsheets.readonly'
store = file.Storage('credentials.json')
creds = store.get()
if not creds or creds.invalid:
    flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
    creds = tools.run_flow(flow, store)
service = build('sheets', 'v4', http=creds.authorize(Http()))

SPREADSHEET_ID = ID
RANGE_NAME = sheetName + '!A2:D'
result = service.spreadsheets().values().get(spreadsheetId=SPREADSHEET_ID,
                                             range=RANGE_NAME).execute()

python google-api google-oauth2 google-api-python-client oauth2client

Answers

answered 6 days ago Chris #1

Changed my code to this:

SCOPES = 'https://www.googleapis.com/auth/spreadsheets'
store = file.Storage('credentials.json')

flow = client.OAuth2WebServerFlow(client_id='619103408544-qbpfk38g9jk4tkc5gshvds9hs8g5ur9o.apps.googleusercontent.com',
                                    client_secret='faJQr2Wd3x25_yKYIWslxR4s',
                                    scope=SCOPES)
creds = tools.run_flow(flow, store)
service = build('sheets', 'v4', http=creds.authorize(Http()))

Used a different function to create the flow, turns out you don't need to actually use the store to make the credentials so I just deleted the store.get() line.