Google Spreadsheets Python API - Simple interface for working with Google Sheets
gspread provides multiple authentication methods for accessing Google Sheets API, supporting different use cases from server-side applications to interactive scripts.
Authenticate using a service account JSON file or dictionary. Recommended for server-side applications and automated scripts.
def service_account(filename: Union[Path, str] = DEFAULT_SERVICE_ACCOUNT_FILENAME,
scopes: Iterable[str] = DEFAULT_SCOPES,
http_client: HTTPClientType = HTTPClient) -> Client:
"""
Authenticate using service account credentials.
Parameters:
- filename (Union[Path, str]): Path to service account JSON file. Defaults to DEFAULT_SERVICE_ACCOUNT_FILENAME.
- scopes (Iterable[str]): OAuth2 scopes. Defaults to DEFAULT_SCOPES.
- http_client (HTTPClientType): HTTP client type. Default: HTTPClient.
Returns:
Client: Authenticated client instance.
"""
def service_account_from_dict(info: Mapping[str, Any], scopes: Iterable[str] = DEFAULT_SCOPES,
http_client: HTTPClientType = HTTPClient) -> Client:
"""
Authenticate using service account credentials from dictionary.
Parameters:
- info (Mapping[str, Any]): Service account information dictionary.
- scopes (Iterable[str]): OAuth2 scopes. Defaults to DEFAULT_SCOPES.
- http_client (HTTPClientType): HTTP client type. Default: HTTPClient.
Returns:
Client: Authenticated client instance.
"""Usage examples:
# From file
gc = gspread.service_account()
# From specific file
gc = gspread.service_account(filename='path/to/service_account.json')
# From dictionary
service_account_info = {
"type": "service_account",
"project_id": "your-project-id",
"private_key_id": "key-id",
"private_key": "-----BEGIN PRIVATE KEY-----\n...",
"client_email": "your-service-account@your-project.iam.gserviceaccount.com",
"client_id": "client-id",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token"
}
gc = gspread.service_account_from_dict(service_account_info)
# With custom scopes
gc = gspread.service_account(scopes=['https://www.googleapis.com/auth/spreadsheets'])Interactive OAuth2 flow for applications that need user consent. Suitable for desktop applications and interactive scripts.
def oauth(scopes: Iterable[str] = DEFAULT_SCOPES, flow: FlowCallable = local_server_flow,
credentials_filename: Union[str, Path] = DEFAULT_CREDENTIALS_FILENAME,
authorized_user_filename: Union[str, Path] = DEFAULT_AUTHORIZED_USER_FILENAME,
http_client: HTTPClientType = HTTPClient) -> Client:
"""
Authenticate using OAuth2 flow.
Parameters:
- scopes (Iterable[str]): OAuth2 scopes. Defaults to DEFAULT_SCOPES.
- flow (FlowCallable): OAuth2 flow callable. Defaults to local_server_flow.
- credentials_filename (Union[str, Path]): Path to OAuth2 credentials JSON file. Default: DEFAULT_CREDENTIALS_FILENAME.
- authorized_user_filename (Union[str, Path]): Path to store authorized user info. Default: DEFAULT_AUTHORIZED_USER_FILENAME.
- http_client (HTTPClientType): HTTP client type. Default: HTTPClient.
Returns:
Client: Authenticated client instance.
"""
def oauth_from_dict(credentials: Optional[Mapping[str, Any]] = None,
authorized_user_info: Optional[Mapping[str, Any]] = None,
scopes: Iterable[str] = DEFAULT_SCOPES,
flow: FlowCallable = local_server_flow,
http_client: HTTPClientType = HTTPClient) -> Tuple[Client, Dict[str, Any]]:
"""
Authenticate using OAuth2 flow from dictionary.
Parameters:
- credentials (Optional[Mapping[str, Any]]): OAuth2 credentials information dictionary.
- authorized_user_info (Optional[Mapping[str, Any]]): Existing authorized user information.
- scopes (Iterable[str]): OAuth2 scopes. Defaults to DEFAULT_SCOPES.
- flow (FlowCallable): OAuth2 flow callable. Defaults to local_server_flow.
- http_client (HTTPClientType): HTTP client type. Default: HTTPClient.
Returns:
Tuple[Client, Dict[str, Any]]: Authenticated client instance and authorized user info.
"""Usage examples:
# Basic OAuth2 flow
gc = gspread.oauth()
# From specific file
gc = gspread.oauth(filename='oauth_credentials.json')
# From dictionary
oauth_info = {
"client_id": "your-client-id.apps.googleusercontent.com",
"client_secret": "your-client-secret",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token"
}
gc = gspread.oauth_from_dict(oauth_info)
# With custom port and host
gc = gspread.oauth(port=8080, host='127.0.0.1')Authenticate using pre-existing credentials objects from google-auth library.
def authorize(credentials: Credentials, http_client: HTTPClientType = HTTPClient,
session: Optional[Session] = None) -> Client:
"""
Authorize using existing credentials object.
Parameters:
- credentials (Credentials): Google auth credentials object (e.g., from google.auth).
- http_client (HTTPClientType): HTTP client type. Default: HTTPClient.
- session (Optional[Session]): Custom requests Session object.
Returns:
Client: Authenticated client instance.
"""Usage example:
from google.auth import default
# Use default credentials (e.g., from environment or gcloud)
credentials, project = default()
gc = gspread.authorize(credentials)Authenticate using Google API key. Limited functionality - only allows reading publicly shared spreadsheets.
def api_key(api_key: str) -> Client:
"""
Authenticate using API key.
Parameters:
- api_key (str): Google API key.
Returns:
Client: Client instance with API key authentication.
Note: API key authentication has limited access - can only read publicly accessible spreadsheets.
"""Usage example:
gc = gspread.api_key('your-api-key-here')
# Only works with publicly shared spreadsheets
sheet = gc.open_by_url('https://docs.google.com/spreadsheets/d/spreadsheet-id/edit#gid=0')DEFAULT_SCOPES = [
'https://www.googleapis.com/auth/spreadsheets',
'https://www.googleapis.com/auth/drive'
]
READONLY_SCOPES = [
'https://www.googleapis.com/auth/spreadsheets.readonly',
'https://www.googleapis.com/auth/drive.readonly'
]The DEFAULT_SCOPES provide full read/write access to spreadsheets and drive files. Use READONLY_SCOPES when you only need read access to spreadsheets and drive metadata.
Additional utility functions for managing OAuth credentials.
def get_config_dir(config_dir_name: str = "gspread", os_is_windows: bool = os.name == "nt") -> Path:
"""
Construct a config dir path.
Parameters:
- config_dir_name (str): Configuration directory name. Default: "gspread".
- os_is_windows (bool): Whether OS is Windows. Default: os.name == "nt".
Returns:
Path: Configuration directory path.
"""
def load_credentials(filename: Path = DEFAULT_AUTHORIZED_USER_FILENAME) -> Optional[OAuthCredentials]:
"""
Load OAuth credentials from file.
Parameters:
- filename (Path): Path to authorized user file. Default: DEFAULT_AUTHORIZED_USER_FILENAME.
Returns:
Optional[OAuthCredentials]: Loaded credentials or None if file doesn't exist.
"""
def store_credentials(creds: OAuthCredentials, filename: Path = DEFAULT_AUTHORIZED_USER_FILENAME,
strip: str = "token") -> None:
"""
Store OAuth credentials to file.
Parameters:
- creds (OAuthCredentials): OAuth credentials to store.
- filename (Path): Path to store credentials. Default: DEFAULT_AUTHORIZED_USER_FILENAME.
- strip (str): Fields to strip from stored credentials. Default: "token".
Returns:
None
"""
def local_server_flow(client_config: Mapping[str, Any], scopes: Iterable[str], port: int = 0) -> OAuthCredentials:
"""
OAuth flow using local server strategy.
Parameters:
- client_config (Mapping[str, Any]): OAuth client configuration.
- scopes (Iterable[str]): OAuth scopes.
- port (int): Local server port. 0 for random port.
Returns:
OAuthCredentials: Authorized OAuth credentials.
"""class FlowCallable(Protocol):
"""Protocol for OAuth flow callables."""
def __call__(self, client_config: Mapping[str, Any], scopes: Iterable[str], port: int = 0) -> OAuthCredentials: ...
# Type aliases
HTTPClientType = Type[HTTPClient]
# Default paths
DEFAULT_CONFIG_DIR = get_config_dir()
DEFAULT_CREDENTIALS_FILENAME = DEFAULT_CONFIG_DIR / "credentials.json"
DEFAULT_AUTHORIZED_USER_FILENAME = DEFAULT_CONFIG_DIR / "authorized_user.json"
DEFAULT_SERVICE_ACCOUNT_FILENAME = DEFAULT_CONFIG_DIR / "service_account.json"Install with Tessl CLI
npx tessl i tessl/pypi-gspread