I am currently looking for a way to read data from a Sheet in Python from a GCP Cloud Run instance. A service account (to which I shared the sheet) is loaded during the deployment of the instance and I was wondering if it was possible to use this service account directly without loading its key, as the instance is already using the account.
If you have any idea on how to do it I'll be happy. Thanks
A service account is an email, as any user account. If you need to access a user Google Sheet document to perform some processing on the data, you can simply share the sheet with the service account email. Put it in "Viewer" for read only or in "Editor" if you also want to update the sheet.
Then in your code, you need to create a credential, with the Cloud Run service account (not a key that you have on your side). The important part here, is to correctly scope the credential.
And then you can use the Sheet API to interact when the document.
from googleapiclient.discovery import build
import google.auth
SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly', 'https://www.googleapis.com/auth/cloud-platform']
default_credentials, project_id = google.auth.default(scopes=SCOPES)
# The ID and range of a sample spreadsheet.
SAMPLE_SPREADSHEET_ID = 'YOUR DOCUMENT ID'
SAMPLE_RANGE_NAME = 'A1:C1'
service = build('sheets', 'v4', credentials=default_credentials)
sheet = service.spreadsheets()
result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID,
range=SAMPLE_RANGE_NAME).execute()
values = result.get('values', [])
to_ret = "Result \n"
if not values:
to_ret += "\n" + 'No data found.'
print('No data found.')
else:
to_ret += "\n" + 'Results:'
print('Results:')
for row in values:
to_ret += "\n" + row[0]
print(row)