client_builder

Gmail API Client Builders

This module provides builder classes for creating authenticated Gmail API clients with different credential storage strategies. Supports both local file storage and AWS Parameter Store for OAuth2 tokens and client secrets.

The module implements the builder pattern to abstract credential management while maintaining consistent authentication flow across different environments.

exception pythonic_gmail.client_builder.TokenNotFound[source]

Exception raised when OAuth2 token cannot be found or accessed.

This exception is raised when attempting to read stored credentials that don’t exist or are inaccessible in the configured storage location.

class pythonic_gmail.client_builder.ClientBuilder(scopes: list[str] = REQ)[source]

Abstract base class for Gmail API client authentication builders.

Provides the core OAuth2 authentication flow for Gmail API access while allowing different credential storage strategies through subclasses. Handles token refresh, re-authentication when needed, and service creation.

Parameters:

scopes – List of Gmail API scopes to request during authentication

Examples:

Local file storage:

builder = LocalPathClientBuilder(
    scopes=["https://www.googleapis.com/auth/gmail.readonly"],
    path_client_secrets=Path("~/.google/client_secrets.json"),
    path_token=Path("~/.google/token.json")
)
gmail_service = builder.auth()

AWS Parameter Store:

builder = AwsParameterStoreClientBuilder(
    scopes=["https://www.googleapis.com/auth/gmail.readonly"],
    ssm_client=boto3.client("ssm"),
    param_name_client_secrets="/app/gmail/client_secrets",
    param_name_token="/app/gmail/token"
)
gmail_service = builder.auth()

Note

Subclasses must implement credential storage methods for their specific storage backend (local files, cloud storage, etc.).

read_client_secrets_config() dict[source]

Read OAuth2 client secrets configuration from storage.

Returns:

Client secrets configuration dictionary containing client_id, client_secret, and other OAuth2 parameters

Raises:

NotImplementedError – Must be implemented by subclasses

read_token_config() dict[source]

Read stored OAuth2 token configuration from storage.

Returns:

Token configuration dictionary containing access_token, refresh_token, and token metadata

Raises:
write_token_config(data: dict)[source]

Store OAuth2 token configuration to persistent storage.

Called automatically after successful authentication or token refresh to persist credentials for future use.

Parameters:

data – Token configuration dictionary to store

Raises:

NotImplementedError – Must be implemented by subclasses

get_flow() InstalledAppFlow[source]

Create OAuth2 flow for interactive user authentication.

Builds an OAuth2 flow using client secrets and requested scopes. Used when initial authentication or re-authentication is required.

Returns:

Configured OAuth2 flow ready for user interaction

get_creds() Credentials[source]

Load existing OAuth2 credentials from stored token.

Reconstructs credentials object from previously stored token data. These credentials may need refresh if expired.

Returns:

OAuth2 credentials object loaded from storage

Raises:

TokenNotFound – When stored token cannot be found

auth() GmailResource[source]

Authenticate and create Gmail API service client.

Handles the complete OAuth2 authentication flow including: - Loading existing credentials if available - Refreshing expired tokens automatically - Prompting for re-authentication when necessary - Storing updated credentials for future use

Returns:

Authenticated Gmail API service client ready for use

Note

On first run or when refresh fails, opens a web browser for user authentication. Subsequent runs use stored credentials.

class pythonic_gmail.client_builder.LocalPathClientBuilder(scopes: list[str] = REQ, path_client_secrets: Path = REQ, path_token: Path = REQ)[source]

Gmail client builder using local file system for credential storage.

Stores OAuth2 client secrets and tokens as JSON files on the local filesystem. Ideal for development environments and single-user applications.

Parameters:
  • scopes – Gmail API scopes to request during authentication

  • path_client_secrets – Path to JSON file containing OAuth2 client secrets

  • path_token – Path to JSON file for storing OAuth2 tokens

Examples:

Development setup with home directory storage:

from pathlib import Path

builder = LocalPathClientBuilder(
    scopes=["https://www.googleapis.com/auth/gmail.readonly"],
    path_client_secrets=Path.home() / ".google" / "client_secrets.json",
    path_token=Path.home() / ".google" / "token.json"
)
gmail_service = builder.auth()

Shared project configuration:

builder = LocalPathClientBuilder(
    scopes=["https://www.googleapis.com/auth/gmail.modify"],
    path_client_secrets=Path("config/gmail_secrets.json"),
    path_token=Path("config/gmail_token.json")
)

Note

Ensure proper file permissions on credential files to protect sensitive authentication data from unauthorized access.

read_client_secrets_config() dict[source]

Read OAuth2 client secrets from local JSON file.

Returns:

Client secrets configuration dictionary

Raises:
read_token_config() dict[source]

Read OAuth2 token from local JSON file.

Returns:

Token configuration dictionary

Raises:
write_token_config(data: dict)[source]

Write OAuth2 token to local JSON file.

Creates parent directories if they don’t exist and writes token data with human-readable formatting.

Parameters:

data – Token configuration dictionary to store

write_client_secrets_config(data: dict)[source]

Write OAuth2 client secrets to local JSON file.

Utility method for programmatically storing client secrets. Creates parent directories if they don’t exist.

Parameters:

data – Client secrets configuration dictionary to store

class pythonic_gmail.client_builder.AwsParameterStoreClientBuilder(scopes: list[str] = REQ, ssm_client: SSMClient = REQ, param_name_client_secrets: str = REQ, param_name_token: str = REQ)[source]

Gmail client builder using AWS Systems Manager Parameter Store.

Stores OAuth2 credentials as encrypted parameters in AWS SSM Parameter Store. Ideal for production environments, CI/CD pipelines, and multi-instance deployments where centralized credential management is required.

Parameters:
  • scopes – Gmail API scopes to request during authentication

  • ssm_client – Configured AWS SSM client for parameter operations

  • param_name_client_secrets – SSM parameter name for client secrets

  • param_name_token – SSM parameter name for OAuth2 tokens

Examples:

Production environment with AWS profile:

import boto3

builder = AwsParameterStoreClientBuilder(
    scopes=["https://www.googleapis.com/auth/gmail.readonly"],
    ssm_client=boto3.Session(profile_name="prod").client("ssm"),
    param_name_client_secrets="/app/gmail/client_secrets",
    param_name_token="/app/gmail/token"
)
gmail_service = builder.auth()

Cross-account deployment:

# Using assumed role credentials
ssm_client = boto3.client(
    "ssm",
    aws_access_key_id=assumed_credentials["AccessKeyId"],
    aws_secret_access_key=assumed_credentials["SecretAccessKey"],
    aws_session_token=assumed_credentials["SessionToken"]
)

builder = AwsParameterStoreClientBuilder(
    scopes=["https://www.googleapis.com/auth/gmail.modify"],
    ssm_client=ssm_client,
    param_name_client_secrets="/shared/gmail/secrets",
    param_name_token="/shared/gmail/token"
)

Note

Parameters are stored as SecureString type for encryption at rest. Ensure proper IAM permissions for ssm:GetParameter and ssm:PutParameter.

read_client_secrets_config() dict[source]

Read OAuth2 client secrets from AWS Parameter Store.

Returns:

Client secrets configuration dictionary

Raises:

TokenNotFound – If client secrets parameter doesn’t exist

read_token_config() dict[source]

Read OAuth2 token from AWS Parameter Store.

Returns:

Token configuration dictionary

Raises:

TokenNotFound – If token parameter doesn’t exist

write_token_config(data: dict)[source]

Write OAuth2 token to AWS Parameter Store.

Parameters:

data – Token configuration dictionary to store

write_client_secrets_config(data: dict)[source]

Write OAuth2 client secrets to AWS Parameter Store.

Utility method for programmatically storing client secrets.

Parameters:

data – Client secrets configuration dictionary to store