Skip to content

Core

GoogleAuth

GoogleAuth(token_store: TokenStore | None = None, credentials_file: str | None = None, scopes: list[str] | None = None, user_id: str | None = None, client_config: dict[str, Any] | None = None)

Google OAuth2 authentication handler.

Manages credential acquisition, refresh, and storage. Supports both OAuth (interactive) and Service Account (server-to-server).

Example

OAuth (interactive)

auth = GoogleAuth() auth.authenticate() # Opens browser

Service Account

auth = GoogleAuth.from_service_account("service-account.json")

Use credentials

service = build("gmail", "v1", credentials=auth.credentials)

Initialize OAuth authenticator.

Parameters:

Name Type Description Default
token_store TokenStore | None

Storage backend for tokens (default: the one GSUITE_TOKEN_STORAGE selects, SQLite unless set)

None
credentials_file str | None

Path to OAuth credentials JSON

None
scopes list[str] | None

OAuth scopes to request (default: Scopes.default(), i.e. Gmail, Calendar, Drive and Sheets)

None
user_id str | None

Name of the stored login to use (the account). One token store holds several: GoogleAuth(user_id="work"). Default: GSUITE_ACCOUNT, or "default"

None
client_config dict[str, Any] | None

The OAuth client as Google's JSON would hold it ({"installed": {...}} or {"web": {...}}), instead of a file; see from_client_config

None

credentials property

credentials: Credentials | None

Get current credentials, loading from store if needed.

from_client_config classmethod

from_client_config(client_id: str, client_secret: str, scopes: list[str] | None = None, token_store: TokenStore | None = None, user_id: str | None = None) -> GoogleAuth

Authenticator for an OAuth client given by ID and secret (no JSON file).

For servers configured from env or a settings page. The same GSUITE_CLIENT_ID / GSUITE_CLIENT_SECRET are read by the plain constructor too. Pair it with start_authorization when there is no browser on the machine.

from_service_account classmethod

from_service_account(service_account_file: str, scopes: list[str] | None = None, subject: str | None = None) -> GoogleAuth

Create authenticator from service account.

Parameters:

Name Type Description Default
service_account_file str

Path to service account JSON

required
scopes list[str] | None

OAuth scopes

None
subject str | None

Email to impersonate (for domain-wide delegation)

None

Returns:

Type Description
GoogleAuth

GoogleAuth instance with service account credentials

accounts

accounts() -> list[str]

Names of the logins in the token store (what user_id accepts), sorted.

Raises:

Type Description
NotImplementedError

The token store can't enumerate its tokens

stored_scopes

stored_scopes() -> list[str]

Scopes of this account's stored login; empty if there is none.

Log in again with these plus new ones to add access without losing any: a login replaces the stored scopes.

is_authenticated

is_authenticated() -> bool

Check if we have valid credentials.

needs_refresh

needs_refresh() -> bool

Check if credentials need refresh.

refresh

refresh() -> bool

Refresh expired credentials.

Returns:

Type Description
bool

True if refresh succeeded

Raises:

Type Description
TokenRefreshError

If refresh fails

authenticate

authenticate(force: bool = False) -> Credentials

Get valid credentials, running OAuth flow if needed.

Parameters:

Name Type Description Default
force bool

Force new authentication even if credentials exist

False

Returns:

Type Description
Credentials

Valid Google credentials

Raises:

Type Description
CredentialsNotFoundError

If the browser flow is needed and the credentials file doesn't exist

client_config

client_config() -> dict[str, Any]

The OAuth client: the one given, or GSUITE_CLIENT_ID/SECRET, or the credentials file.

Raises:

Type Description
CredentialsNotFoundError

None of them is available

start_authorization

start_authorization(redirect_uri: str = DEFAULT_REDIRECT_URI) -> AuthorizationRequest

First half of a login on a machine without a browser (PKCE).

Show request.url to the user; after consenting, Google redirects to redirect_uri with a code. Pass what they bring back (the code or the whole URL) to finish_authorization with this request.

Parameters:

Name Type Description Default
redirect_uri str

Where Google sends the user back. The default works with Desktop clients: the browser lands on an error page whose URL holds the code. A web client needs its registered URI.

DEFAULT_REDIRECT_URI

finish_authorization

finish_authorization(request: AuthorizationRequest, code_or_url: str) -> Credentials

Second half: exchange the code for tokens and store them.

Parameters:

Name Type Description Default
request AuthorizationRequest

What start_authorization returned (possibly rebuilt with AuthorizationRequest.from_dict)

required
code_or_url str

The code, or the whole redirect URL as pasted; a URL must carry the request's state

required

Raises:

Type Description
AuthenticationError

Google declined, the URL is from another attempt, or the code was rejected

revoke

revoke(*, remote: bool = True) -> bool

Sign out: revoke the grant at Google and delete the stored token.

With remote=True (the default) the refresh token (or the access token, if there is none) is revoked at Google: the app disappears from the user's account permissions and every token from that grant stops working. Google answering that the token is already invalid counts as done. If Google can't be reached or answers with another error, a warning is logged and the local token is deleted anyway, so signing out never stops halfway. remote=False only forgets the token locally.

Returns:

Type Description
bool

True if there was a grant to revoke or a stored token to delete.

export_token

export_token() -> dict[str, Any] | None

Export token data for external storage.

Returns:

Type Description
dict[str, Any] | None

Token data dict or None if not authenticated

get_user_email

get_user_email() -> str | None

Get authenticated user's email.

Returns:

Type Description
str | None

Email address or None

Scopes

Google API OAuth scopes.

Use these constants to request specific permissions.

gmail classmethod

gmail() -> list[str]

Standard Gmail scopes for read, send, modify.

calendar classmethod

calendar() -> list[str]

Standard Calendar scopes.

drive classmethod

drive() -> list[str]

Standard Drive scopes.

sheets classmethod

sheets() -> list[str]

Standard Sheets scopes.

tasks classmethod

tasks() -> list[str]

Standard Tasks scopes.

contacts classmethod

contacts() -> list[str]

Standard Contacts (People API) scopes.

searchconsole classmethod

searchconsole() -> list[str]

Search Console, read-only.

analytics classmethod

analytics() -> list[str]

Google Analytics 4 (Admin and Data APIs), read-only.

tagmanager classmethod

tagmanager() -> list[str]

Tag Manager, read-only.

marketing classmethod

marketing() -> list[str]

Search Console + Analytics + Tag Manager, all read-only.

Opt-in: not part of default() or all(), so existing logins are not asked to re-consent. Add it with gsuite auth login --force --scopes default,marketing.

all classmethod

all() -> list[str]

All standard scopes for full access.

default classmethod

default() -> list[str]

Default scopes: Gmail, Calendar, Drive and Sheets.

Drive used to be missing, so a default login got 403s from the Drive client and from the Sheets calls that go through Drive (open by title, list, share, export). Tokens created before need gsuite auth login --force.

Tasks and Contacts are left out on purpose: contacts is a sensitive scope, and asking for both on every login would over-ask. Request them with Scopes.all() or gsuite auth login --scopes all.

Settings

Bases: BaseSettings

Application settings loaded from environment variables.

Prefix: GSUITE_ Example: GSUITE_API_KEY=secret

cors_origin_list property

cors_origin_list: list[str]

CORS origins parsed from the comma-separated setting.

api_account_list property

api_account_list: list[str]

Accounts selectable through the REST API, parsed from the comma-separated setting.

validate_for_secretmanager

validate_for_secretmanager() -> None

Validate settings when using Secret Manager.

GoogleService

GoogleService(api: str, version: str, *, attr: str | None = None)

Descriptor for a discovery-based API service, built on first access.

The owner needs an auth attribute (a GoogleAuth). The service is built with :func:authorized_http, so requests time out, and cached on the instance. Assigning replaces it, which is how tests or callers inject a fake or a preconfigured service::

class Drive:
    service = GoogleService("drive", "v3")

drive = Drive(auth)
drive.service = fake_service

Parameters:

Name Type Description Default
api str

Discovery API name, e.g. "gmail".

required
version str

API version, e.g. "v1".

required
attr str | None

Instance attribute that caches the service; defaults to the descriptor's name with a leading underscore (service -> _service).

None

Channel dataclass

Channel(id: str, resource_id: str, expiration: datetime | None = None, token: str | None = None, resource_uri: str | None = None, raw: dict[str, Any] = dict())

A notification channel, as Google created it.

Keep id and resource_id: both are needed to stop the channel.

exceptions

Google Suite exceptions.

GSuiteError

GSuiteError(message: str, cause: Exception | None = None)

Bases: Exception

Base exception for all Google Suite errors.

AuthenticationError

AuthenticationError(message: str, cause: Exception | None = None)

Bases: GSuiteError

Authentication-related errors.

CredentialsNotFoundError

CredentialsNotFoundError(path: str)

Bases: AuthenticationError

OAuth credentials file not found.

TokenExpiredError

TokenExpiredError()

Bases: AuthenticationError

Token is expired and cannot be refreshed.

TokenRefreshError

TokenRefreshError(cause: Exception | None = None)

Bases: AuthenticationError

Failed to refresh token.

NotAuthenticatedError

NotAuthenticatedError()

Bases: AuthenticationError

Operation requires authentication but not authenticated.

APIError

APIError(message: str, service: str, status_code: int | None = None, cause: Exception | None = None)

Bases: GSuiteError

Google API call errors.

RateLimitError

RateLimitError(service: str, retry_after: int | None = None)

Bases: APIError

Rate limit exceeded.

QuotaExceededError

QuotaExceededError(service: str)

Bases: APIError

API quota exceeded.

NotFoundError

NotFoundError(service: str, resource_type: str, resource_id: str)

Bases: APIError

Resource not found.

PermissionDeniedError

PermissionDeniedError(service: str, operation: str)

Bases: APIError

Permission denied for operation.

InsufficientScopeError

InsufficientScopeError(service: str)

Bases: PermissionDeniedError

The login lacks an OAuth scope the call needs.

Unlike other permission errors, logging in again with the right scopes fixes it (gsuite auth login --force --scopes ...).

SyncTokenExpiredError

SyncTokenExpiredError(service: str)

Bases: APIError

An incremental sync token (or Gmail history ID) is too old to resume from.

Google keeps them for a limited time (about a week for Contacts and Gmail). List everything again without a token and keep the new one.

ValidationError

ValidationError(field: str, message: str)

Bases: GSuiteError

Input validation error.

ConfigurationError

ConfigurationError(message: str, cause: Exception | None = None)

Bases: GSuiteError

Configuration error.

AsyncGoogleClient

AsyncGoogleClient(auth: Any, *, timeout: float | None = None, transport: Any = None)

Authorized async HTTP for Google APIs, with retries and mapped errors.

Parameters:

Name Type Description Default
auth Any

A GoogleAuth (OAuth or service account) or google-auth credentials.

required
timeout float | None

Seconds per request (default: GSUITE_REQUEST_TIMEOUT).

None
transport Any

An httpx transport (tests pass httpx.MockTransport).

None

aclose async

aclose() -> None

Close the underlying connection pool.

request async

request(method: str, url: str, *, service: str, resource_type: str = 'resource', resource_id: str = 'unknown', params: dict[str, Any] | None = None, json: Any = None, content: bytes | None = None, headers: dict[str, str] | None = None, accept: Collection[int] = (), retry: bool = True) -> Any

Send a request; returns the httpx.Response of a successful call.

Parameters:

Name Type Description Default
method str

HTTP method.

required
url str

Full URL of the endpoint.

required
service str

Service name for errors and logs ("gmail", "drive", ...).

required
resource_type str

What the URL addresses, for errors ("file", ...).

'resource'
resource_id str

Its ID, for errors.

'unknown'
params dict[str, Any] | None

Query parameters.

None
json Any

JSON body.

None
content bytes | None

Raw body (instead of json).

None
headers dict[str, str] | None

Extra headers; the authorization header is added.

None
accept Collection[int]

Non-2xx statuses to return instead of raising (e.g. 308 from a resumable upload).

()
retry bool

False sends it once, for callers that recover on their own (a resumable upload asks the server where to resume).

True

Raises:

Type Description
GSuiteError

A subclass of it for HTTP errors.

TransportError

A network error, once retries are exhausted.

json async

json(method: str, url: str, **kwargs: Any) -> Any

request() and decode the JSON body ({} when empty).

paginate async

paginate(url: str, items_key: str, *, service: str, params: dict[str, Any] | None = None, max_items: int | None = None, page_size_param: str = 'maxResults', max_page_size: int = 100) -> AsyncIterator[dict[str, Any]]

Async paginate(): yield items of a GET list endpoint, following nextPageToken.