How to Connect an AI Agent to Google Sheets (Python + Sheets API)
Updated 2026-11-03
This guide connects a Python agent to Google Sheets with the official Google Sheets API v4. The agent gets read and append tools on a spreadsheet you choose, using the same OAuth desktop flow as Connect an AI agent to Gmail. Start read-only, then add append when you trust the prompts. Last tested 2026-11-03.
Docs used:
- Google Sheets API overview
- Python quickstart
- Method: spreadsheets.values.get
- Method: spreadsheets.values.append
Prerequisites
- A Google account and a Google Cloud project
- Python 3.10+
- The tool loop from Build your first AI agent in Python
- A spreadsheet ID (from the sheet URL:
https://docs.google.com/spreadsheets/d/SPREADSHEET_ID/edit)
Steps
1. Enable the Google Sheets API and create OAuth credentials
- In Google Cloud Console, enable Google Sheets API under APIs & Services → Library.
- Configure the OAuth consent screen (External + test users, or Internal for Workspace).
- Create OAuth client ID → Desktop app and download
credentials.json.
2. Install client libraries
pip install google-api-python-client google-auth-httplib2 google-auth-oauthlib openai
3. Authorize and build the Sheets service
# sheets_tools.py
import os
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
# Read-only first; add spreadsheets for append in step 5
SCOPES = ["https://www.googleapis.com/auth/spreadsheets.readonly"]
SPREADSHEET_ID = os.environ["SHEETS_SPREADSHEET_ID"] # from the sheet URL
def sheets_service():
creds = None
if os.path.exists("token_sheets.json"):
creds = Credentials.from_authorized_user_file("token_sheets.json", SCOPES)
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file("credentials.json", SCOPES)
creds = flow.run_local_server(port=0)
with open("token_sheets.json", "w") as f:
f.write(creds.to_json())
return build("sheets", "v4", credentials=creds)
svc = sheets_service()
Use a separate token file from Gmail so scope changes do not break the other integration.
4. Expose agent tools
def read_sheet_range(range_a1: str) -> str:
"""range_a1 example: 'Leads!A1:D20'"""
result = (
svc.spreadsheets()
.values()
.get(spreadsheetId=SPREADSHEET_ID, range=range_a1)
.execute()
)
rows = result.get("values", [])
return "\n".join(",".join(row) for row in rows) or "(empty range)"
def append_sheet_row(range_a1: str, values: list[str]) -> str:
"""Append one row; requires spreadsheets scope (step 5)."""
body = {"values": [values]}
res = (
svc.spreadsheets()
.values()
.append(
spreadsheetId=SPREADSHEET_ID,
range=range_a1,
valueInputOption="USER_ENTERED",
insertDataOption="INSERT_ROWS",
body=body,
)
.execute()
)
return f"appended {res.get('updates', {}).get('updatedRows', 0)} row(s)"
Register read_sheet_range (and optionally append_sheet_row) in TOOLS / FUNCS like the first-agent guide. Pass the spreadsheet ID via env, not through the model.
5. Enable append (optional)
- Add
https://www.googleapis.com/auth/spreadsheetstoSCOPES. - Delete
token_sheets.jsonand re-run OAuth. - Only expose
append_sheet_rowwhen you want the model to write; keep read-only for dashboards and reporting agents.
6. Test
export SHEETS_SPREADSHEET_ID="your_id_here"
export OPENAI_API_KEY="sk-..."
python agent.py "Read Leads!A1:C10 and summarize how many rows have Status=Open"
No-code alternative
In n8n, attach the Google Sheets node as a tool on the AI Agent node with a Google OAuth2 credential, similar to Connect an AI agent to HubSpot with n8n. Use $fromAI() on the range or row fields. Add n8n AI agent memory for follow-up questions on the same sheet.
Common errors
HttpError 403 ... has not enabled the Google Sheets API. Enable the API in the same Cloud project as your OAuth client.
Request had insufficient authentication scopes. You changed SCOPES but kept token_sheets.json. Delete the token file and consent again.
Unable to parse range. The model invented a sheet name. Validate range_a1 against tabs that exist, or pass fixed ranges in the system prompt.
Append returns 403 with read-only scope. You did not add the spreadsheets scope and re-authorize.
FAQ
Which API version does this use?
Google Sheets API v4 via googleapiclient.discovery.build("sheets", "v4", ...).
Can the agent edit arbitrary cells?
This guide uses get and append only. Random cell updates need values.update; add them only with validation, or keep append-only for auditability.
How do I connect Sheets without Python?
Use n8n’s Google Sheets tool node on an AI Agent workflow, or query a warehouse with Connect an AI agent to a database if the sheet is already synced to SQL.
Related guides
- Connect an AI agent to Gmail (same OAuth desktop pattern)
- Build your first AI agent in Python
- Connect an AI agent to HubSpot with n8n (CRM rows beside Sheets in n8n)
- Connect an AI agent to a database (SQL instead of spreadsheets)
- Fix: AI agent stuck in a loop (cap tool steps on wide ranges)
- What is an AI agent?