This guide walks you through how to connect your Python tool to Google Sheets using a Service Account and securely pull data from specific worksheets.
- Google Account
- Access to Google Cloud Console
- Python installed with
pip
- Visit: Google Cloud Console
- Create or select an existing project.
- Go to APIs & Services → Library
- Enable the following APIs:
- Google Sheets API
- Google Drive API
- Go to APIs & Services → Credentials
- Click Create Credentials → Service Account
- Name it something like
scout-sheets-reader - Grant no additional roles (read-only is enough)
- Click Done
- In the service account list, click on the one you just created
- Go to Keys → Add Key → Create new key
- Choose JSON
- Download the file and place it in your project folder (e.g.,
secrets/gcloud_service_account.json)
- Open the Google Sheet you want to use.
- Click Share
- Paste the service account email (e.g.
scout-sheets-reader@scout-xxxxxx.iam.gserviceaccount.com) - Give it Viewer access.
- Save.
pip install gspread google-authHere's a minimal working example to read a worksheet:
import gspread
from google.oauth2.service_account import Credentials
SERVICE_ACCOUNT_FILE = "secrets/gcloud_service_account.json"
SCOPES = [
"https://www.googleapis.com/auth/spreadsheets.readonly",
"https://www.googleapis.com/auth/drive.readonly",
]
def get_gsheet_client():
credentials = Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE,
scopes=SCOPES
)
return gspread.authorize(credentials)
def get_sheet_data(sheet_url: str, sheet_name: str):
client = get_gsheet_client()
sheet = client.open_by_url(sheet_url)
worksheet = sheet.worksheet(sheet_name)
return worksheet.get_all_records()sheet_url = "https://docs.google.com/spreadsheets/d/your_spreadsheet_id_here/edit"
data = get_sheet_data(sheet_url, "Processed Companies")
for row in data:
print(row["company"], row["tags"])- Never commit your service account JSON key to version control.
- Add this to
.gitignore:
secrets/gcloud_service_account.json