How to properly connect to Google Spreadsheets API? - python

I want to connect to the Google Spreadsheets API with Python.
So I do:
import gspread
from oauth2client.service_account import ServiceAccountCredentials
scope=['https://www.googleapis.com/auth/spreadsheets',
'https://wwww.googleapis.com/auth/drive']
credentials = ServiceAccountCredentials.from_json_keyfile_name('cred.json', scope)
gc = gspread.authorize(credentials)
wks = gc.open('datatest').Sheet1
print(wks.get_all_records)
But I get this error
HttpAccessTokenRefreshError: invalid_scope: https://www.googleapis.com/auth/spreadsheets is not a valid audience string.
How can I use Google-auth instead of gspread with this data?

you input 4w !!!!
X 'https://wwww.googleapis.com/auth/drive'
O 'https://www.googleapis.com/auth/drive'
import gspread
from oauth2client.service_account import ServiceAccountCredentials
scope = ['https://www.googleapis.com/auth/drive']
credentials = ServiceAccountCredentials.from_json_keyfile_name('CredentialsFile.json', scope)
ss_app = gspread.authorize(credentials=credentials) # make sure your Google Sheets API is enabled
sht = ss_app.open('sheet_name_xxxx') # In your spreadsheet, click the Share button and paste the client email as same as CredentialsFile.json.client_email, and make sure your Google Drive API is enabled
wks = sht.worksheet('worksheet_name_xxxx')
print(wks.acell('A1').value)
hope that it helps.

Related

How to authenticate Google account via Python

This following snippet authenticates user account on Colab:
from google.colab import auth
auth.authenticate_user()
However, I am writing a script to run this on a desktop so I can't use this feature. How can I authenticate a Google account in Python?
This is my full code:
import gspread, json
import pandas as pd
from google.auth import default
from google.colab import auth
auth.authenticate_user()
creds, _ = default()
gc = gspread.authorize(creds)
SCOPE = ["https://docs.google.com/forms/d/aBCdefGHJ/edit"]
SECRETS_FILE = "client_secret.json"
SPREADSHEET = "GForm doc"
json_key = json.load(open(SECRETS_FILE))
gc = gspread.authorize(creds)
workbook = gc.open(SPREADSHEET)
sheet = workbook.sheet1
data = pd.DataFrame(sheet.get_all_records())
print(data['Email Address'])
print(list(data['Links']))
As you can see, I am using the Colab library so it makes this code useless as a standalone Python script. I want to authenticate without logging in with my email and password since I don't want to expose those. Is there a way to authenticate Google credentials?

Invalid response 405 when using airflow GoogleBaseHook in python

I am running airflow in docker. I create an airflow Google Cloud connection through web server GUI on my localhost:8080. In python code, I want to read data in Gsheet to with GoogleBaseHook as:
import json
from googleapiclient.discovery import build
from airflow.providers.google.common.hooks.base_google import GoogleBaseHook
from oauth2client.service_account import ServiceAccountCredentials
gcp_hook = GoogleBaseHook(gcp_conn_id="spx-service-account")
cred_dict = json.loads(gcp_hook._get_field('keyfile_dict'))
SCOPES = ['https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_dict(cred_dict, scopes=SCOPES)
service = build('sheets', 'v4', credentials=creds, cache_discovery=False)
sheet = service.spreadsheets()
result = sheet.values().get(spreadsheetId="1yN3atY6NG7PfY8yNcNAiVqURra8WtQJWCKXc-ccymk0", range="Sheet1!A1:B4").execute()['values']
But executing the code above shows Failed to retrieve access token. 405 Not Allowed
Error:
Does anyone know what causes this error and how I can solve it? Thank you.
Oops, it ends up to be something wrong with my keyfile JSON. I have no idea why those token_uri is encoded when I downloaded it from my Gmail (tech team sent it to us via email) and opened it with my windows laptop. If your credential is correct, the code below should work:
import json
from googleapiclient.discovery import build
from airflow.providers.google.common.hooks.base_google import GoogleBaseHook
from oauth2client.service_account import ServiceAccountCredentials
gcp_hook = GoogleBaseHook(gcp_conn_id="spx-service-account")
cred_dict = json.loads(gcp_hook._get_field('keyfile_dict'))
SCOPES = ['https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_dict(cred_dict, scopes=SCOPES)
service = build('sheets', 'v4', credentials=creds, cache_discovery=False)
sheet = service.spreadsheets()
result = sheet.values().get(spreadsheetId="1yN3atY6NG7PfY8yNcNAiVqURra8WtQJWCKXc-ccymk0", range="Sheet1!A1:B4").execute()['values']

Retrieving google sheet values with google sheet api on company restricted spreadsheet

I want to be able to read a spreadsheet, that has been shared with me, inside the company I work.
I have tried adapting the script from this link.
This is the code I use:
from apiclient import discovery
from oauth2client.service_account import ServiceAccountCredentials
import httplib2
scope = [
'https://www.googleapis.com/auth/spreadsheets',
'https://www.googleapis.com/auth/drive'
]
SERVICE_ACCOUNT_FILE = "gsheetread-293005-d7e75122e4c7.json"
credentials = ServiceAccountCredentials.from_json_keyfile_name(
SERVICE_ACCOUNT_FILE, scopes=scope)
# Use the create_delegated() method and authorize the delegated credentials
delegated_credentials = credentials.create_delegated('myemail#company.com')
delegated_http = delegated_credentials.authorize(httplib2.Http())
google_sheet = discovery.build('spreadsheet_id', 'v3', http=delegated_http)
I get an error:
oauth2client.client.HttpAccessTokenRefreshError: unauthorized_client: Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested.
The error you're getting means you didn't add some or all of the specified scopes (https://www.googleapis.com/auth/spreadsheets,
https://www.googleapis.com/auth/drive) when granting domain-wide authority to your service account. Please follow these steps:
In step 5, you have to add both https://www.googleapis.com/auth/spreadsheets,
https://www.googleapis.com/auth/drive (actually, you only need to add one, if you're just accessing a spreadsheet, but you should remove the other one from your code).
Additional notes:
The library you're using, oauth2client, is deprecated. Use google-auth instead, which doesn't rely on httplib2.
You're not using a valid service name (spreadsheet_id). If you want to use Sheets API, the service name should be sheets.
Sheets API V3 is deprecated and will be shut down in January 2021. Use V4 instead.
As I mentioned before, there's no need to use the drive scope if you're accessing a spreadsheet. spreadsheets is enough.
Code snippet (using non-deprecated library):
from googleapiclient.discovery import build
from google.oauth2 import service_account
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
SERVICE_ACCOUNT_FILE = "gsheetread-293005-d7e75122e4c7.json"
creds = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
delegated_credentials = creds.with_subject('myemail#company.com')
service = build('sheets', 'v4', credentials=delegated_credentials)
spreadsheet = service.spreadsheets().get(spreadsheetId="YOUR_SPREADSHEET_ID").execute()
print(spreadsheet)

Error 403 google spreadsheets gspread when open in console

I'm trying to repeat the guide (https://www.youtube.com/watch?v=vISRn5qFrkM) - generated client_secrets.json, put it in the DAGs folder (because then I will run the script from airflow)
But despite the client secret-still gives the error 403-not enough rights , how can I fix it?
import gspread
from oauth2client.service_account import ServiceAccountCredentials
import pprint
scope = ['https://spreadsheets.google.com/feeds']
creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json',scope)
client = gspread.authorize(creds)
sheet = client.open('Data base').sheet4
result = sheet.get_all_records()
print(result)
self solved - apparently when you use the file name it refers to the disk API to find this file
therefore, you must also log in to drive. to do this, you need to add it to the scope
import gspread
from oauth2client.service_account import ServiceAccountCredentials
import pprint
scope = ["https://spreadsheets.google.com/feeds","https://www.googleapis.com/auth/spreadsheets.readonly", "https://www.googleapis.com/auth/drive"]
creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json',scope)
client = gspread.authorize(creds)
sheet = client.open('Data base').worksheet("Sum Data")
result = sheet.get_all_records()
print(result)

Accessing google spreadsheet using shared link

I am building a python app where user can provide 'Anyone can edit' link to their spreadsheet and data can be read from there. I am using python's gspread module but it throws SpreadSheetNotFound error.
import gspread
from oauth2client.service_account import ServiceAccountCredentials
scope = ['https://spreadsheets.google.com/feeds']
credentials = ServiceAccountCredentials.from_json_keyfile_name('myauth.json', scope)
gc = gspread.authorize(credentials)
wks = gc.open_by_url(urls_given_by_user_having_edit_permission)
Above code is not working. Is there any way to achieve this?
wks.share('', perm_type='anyone', role='reader')
Read permission for all people with link. reference https://gspread.readthedocs.io/en/latest/api.html#gspread.models.Spreadsheet.share

Categories