Google Sheets OAuth2 API: the complete setup guide
Google Sheets OAuth2 API: the complete setup guide
Every programmatic interaction with Google Sheets hits the same wall: authentication. You can read a public spreadsheet with an API key, but the moment you need to write or access private data, you need OAuth2. The Google Sheets OAuth2 API flow grants scoped, token-based access that lets your code act on behalf of a user — securely and without storing passwords.
Why OAuth2 instead of an API key?
Think of OAuth2 as a hotel key card system. An API key is the lobby door. OAuth2 is the room key — it grants access to a specific room (spreadsheet), for a specific guest (your app), with an expiration time. Google enforces this because Sheets often contain sensitive data. Three grant types: Authorization code flow (human grants consent via browser), Service account flow (server-to-server automation), and API key (read-only public sheets only).
Creating OAuth2 credentials
- Create a project in Google Cloud Console.
- Enable the Google Sheets API under APIs & Services.
- Configure the OAuth consent screen.
- Create credentials — OAuth client ID for user-facing apps, Service account for server automation.
- Download the JSON key file. Store it securely; never commit to version control.
For service accounts: share your target spreadsheet with the service account email (name@project.iam.gserviceaccount.com).
Scopes to request
spreadsheets.readonly— read-only accessspreadsheets— full read/writedrive.file— access only files created by your app
Handling token refresh
Access tokens expire after one hour. Store the refresh token securely, then use it to get new access tokens. Service accounts simplify this — the google-auth Python library handles refresh automatically. CodeWords stores credentials in encrypted environment variables and handles refresh internally.
Reading and writing data
Core Python patterns for the Sheets API v4 — use spreadsheets().values().get() for reads and spreadsheets().values().update() for writes. Use batchUpdate to send multiple writes in a single API call within Google's rate limits (60 requests per minute per user). Set up your Google Sheets integration on CodeWords →




