or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

auth.mdchannel.mddiscovery.mderrors.mdhttp.mdindex.mdmedia.mdmimeparse.mdmodel.mdschema.mdtesting.md
tile.json

tessl/pypi-google-api-python-client

Google API Client Library for Python that provides discovery-based access to hundreds of Google services with authentication, caching, and media upload/download support.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/google-api-python-client@2.181.x

To install, run

npx @tessl/cli install tessl/pypi-google-api-python-client@2.181.0

index.mddocs/

Google API Python Client

The Google API Python Client Library provides a comprehensive Python interface for accessing Google's discovery-based APIs. It handles authentication, API discovery, request construction, response processing, and media management for hundreds of Google services including Gmail, Drive, Calendar, YouTube, and many others.

Package Information

  • Package Name: google-api-python-client
  • Language: Python
  • Installation: pip install google-api-python-client
  • Dependencies: google-auth, google-auth-httplib2, google-api-core, httplib2, uritemplate

Core Imports

Primary import for API discovery and service building:

from googleapiclient import discovery

Common imports for error handling and HTTP functionality:

from googleapiclient import errors
from googleapiclient import http

Backward compatibility imports (legacy):

from apiclient import discovery  # Same as googleapiclient.discovery
from apiclient import errors     # Same as googleapiclient.errors

Basic Usage

import google.auth
from googleapiclient import discovery
from googleapiclient.errors import HttpError

# Authentication using Application Default Credentials
credentials, project = google.auth.default()

# Build service client for Gmail API
service = discovery.build('gmail', 'v1', credentials=credentials)

try:
    # List messages in user's inbox
    results = service.users().messages().list(userId='me', maxResults=10).execute()
    messages = results.get('messages', [])
    
    for message in messages:
        msg = service.users().messages().get(userId='me', id=message['id']).execute()
        print(f"Subject: {msg['payload']['headers'][0]['value']}")
        
except HttpError as error:
    print(f'An error occurred: {error}')

Architecture

The library follows a layered architecture:

  • Discovery Layer: Dynamically builds service clients from API discovery documents
  • Resource Layer: Provides typed access to API resources and methods
  • HTTP Layer: Handles request construction, authentication, retries, and response processing
  • Model Layer: Manages request/response serialization and media handling
  • Cache Layer: Optimizes performance through discovery document caching

This design enables the library to support hundreds of Google APIs without requiring individual client implementations.

Capabilities

API Discovery and Service Building

Core functionality for discovering Google APIs and building service clients with automatic method generation, authentication integration, and caching support.

def build(serviceName, version, http=None, discoveryServiceUrl=None, 
          developerKey=None, model=None, requestBuilder=None, 
          credentials=None, cache_discovery=True, cache=None, 
          client_options=None, adc_cert_path=None, adc_key_path=None, 
          num_retries=1, static_discovery=None, always_use_jwt_access=False):
    """
    Construct a Resource for interacting with an API.
    
    Args:
        serviceName (str): Name of the service (e.g., 'gmail', 'drive')
        version (str): Version of the service (e.g., 'v1')
        http (httplib2.Http, optional): HTTP client instance
        discoveryServiceUrl (str, optional): URL for discovery service
        developerKey (str, optional): API key for authentication
        model (BaseModel, optional): Data model for request/response handling
        requestBuilder (RequestBuilder, optional): Custom request builder
        credentials (Credentials, optional): OAuth2 credentials
        cache_discovery (bool): Whether to cache discovery documents
        cache (Cache, optional): Custom cache implementation
        client_options (ClientOptions, optional): Client configuration options
        adc_cert_path (str, optional): Path to ADC certificate
        adc_key_path (str, optional): Path to ADC private key
        num_retries (int): Number of retry attempts for discovery (default: 1)
        static_discovery (bool, optional): Use static discovery documents (None for auto)
        always_use_jwt_access (bool): Always use JWT access tokens for service accounts
        
    Returns:
        Resource: A Resource object with methods for each API endpoint
    """

def build_from_document(service, base=None, future=None, http=None, 
                       developerKey=None, model=None, requestBuilder=None, 
                       credentials=None, client_options=None, adc_cert_path=None, 
                       adc_key_path=None, always_use_jwt_access=False):
    """
    Create a Resource from a discovery document.
    
    Args:
        service (dict or str): The discovery document or JSON string
        base (str, optional): Base URI for the service (deprecated)
        future (str, optional): Future version identifier (deprecated)
        developerKey (str, optional): API key for authentication
        http (httplib2.Http, optional): HTTP client instance
        model (BaseModel, optional): Data model for request/response handling
        requestBuilder (RequestBuilder, optional): Custom request builder
        credentials (Credentials, optional): OAuth2 credentials
        client_options (ClientOptions, optional): Client configuration options
        adc_cert_path (str, optional): Path to ADC certificate
        adc_key_path (str, optional): Path to ADC private key
        always_use_jwt_access (bool): Always use JWT for service accounts
        
    Returns:
        Resource: A Resource object built from the discovery document
    """

API Discovery and Service Building

HTTP Request Handling

Comprehensive HTTP functionality including individual requests, batch processing, retry logic, authentication integration, and mock support for testing.

class HttpRequest:
    def __init__(self, http, postproc, uri, method='GET', body=None, 
                 headers=None, methodId=None, resumable=None): ...
    
    def execute(self, http=None, num_retries=0):
        """
        Execute the HTTP request.
        
        Args:
            http (httplib2.Http, optional): HTTP client to use
            num_retries (int): Number of retry attempts
            
        Returns:
            object: Deserialized response content
        """

class BatchHttpRequest:
    def __init__(self, callback=None, batch_uri=None): ...
    
    def add(self, request, callback=None, request_id=None):
        """
        Add a request to the batch.
        
        Args:
            request (HttpRequest): Request to add to batch
            callback (callable, optional): Callback for this request
            request_id (str, optional): Unique ID for this request
        """
    
    def execute(self, http=None, num_retries=0):
        """Execute all requests in the batch."""

HTTP Request Handling

Media Upload and Download

Robust media handling with support for file uploads, in-memory uploads, streaming, progress tracking, resumable transfers, and chunked processing for large files.

class MediaFileUpload:
    def __init__(self, filename, mimetype=None, chunksize=DEFAULT_CHUNK_SIZE, 
                 resumable=False):
        """
        Upload a file to Google APIs.
        
        Args:
            filename (str): Path to the file to upload
            mimetype (str, optional): MIME type of the file
            chunksize (int): Size of upload chunks in bytes
            resumable (bool): Whether upload should be resumable
        """

class MediaIoBaseDownload:
    def __init__(self, fd, request, chunksize=DEFAULT_CHUNK_SIZE):
        """
        Download media to a file-like object.
        
        Args:
            fd (IOBase): File-like object to write download data
            request (HttpRequest): Request for the media download
            chunksize (int): Size of download chunks in bytes
        """
    
    def next_chunk(self, num_retries=0):
        """
        Download the next chunk of media.
        
        Args:
            num_retries (int): Number of retry attempts
            
        Returns:
            tuple: (MediaDownloadProgress, bool) - progress and done status
        """

Media Upload and Download

Error Handling and Exceptions

Complete error handling system with structured exceptions, HTTP error details, batch error processing, and integration patterns for robust error management.

class HttpError(Exception):
    """HTTP request failed with error response."""
    
    def __init__(self, resp, content, uri=None): ...
    
    @property
    def error_details(self):
        """List of individual error details from the response."""
    
    def _get_reason(self):
        """Get the reason phrase from the HTTP response."""

class BatchError(HttpError):
    """Error occurred in batch request processing."""

class MediaUploadSizeError(HttpError):
    """Media upload size exceeds limits."""

Error Handling and Exceptions

Testing and Mocking

Comprehensive testing utilities including HTTP mocking, response simulation, sequence testing, and integration with standard testing frameworks.

class HttpMock:
    def __init__(self, filename=None, headers=None):
        """
        Mock HTTP responses for testing.
        
        Args:
            filename (str, optional): File containing mock response
            headers (dict, optional): HTTP headers for mock response
        """
    
    def request(self, uri, method='GET', body=None, headers=None, 
                redirections=1, connection_type=None):
        """Return mock HTTP response."""

class HttpMockSequence:
    def __init__(self, iterable):
        """
        Mock a sequence of HTTP responses.
        
        Args:
            iterable: Sequence of (response, content) tuples
        """

Testing and Mocking

Authentication Integration

Authentication helper functions that integrate with google-auth and oauth2client libraries, providing credential management, scope handling, and header application.

def default_credentials():
    """Get default credentials from the environment."""

def with_scopes(credentials, scopes):
    """
    Add scopes to credentials if supported.
    
    Args:
        credentials: OAuth2 credentials object
        scopes (list): List of OAuth2 scopes to add
        
    Returns:
        Credentials with scopes applied
    """

def apply_credentials(credentials, headers):
    """
    Apply credentials to request headers.
    
    Args:
        credentials: OAuth2 credentials object  
        headers (dict): HTTP headers to modify
    """

Authentication Integration

Common Usage Patterns

Service Authentication and Building

import google.auth
from googleapiclient import discovery

# Application Default Credentials
credentials, project = google.auth.default()
service = discovery.build('gmail', 'v1', credentials=credentials)

# Service Account Authentication
from google.oauth2 import service_account
credentials = service_account.Credentials.from_service_account_file(
    'path/to/service-account-key.json',
    scopes=['https://www.googleapis.com/auth/gmail.readonly']
)
service = discovery.build('gmail', 'v1', credentials=credentials)

Error Handling Best Practices

from googleapiclient.errors import HttpError
import time

def make_request_with_retry(service, max_retries=3):
    for attempt in range(max_retries):
        try:
            return service.users().messages().list(userId='me').execute()
        except HttpError as error:
            if error.resp.status in [500, 502, 503, 504] and attempt < max_retries - 1:
                time.sleep(2 ** attempt)  # Exponential backoff
                continue
            raise

Batch Request Processing

from googleapiclient import http

def batch_callback(request_id, response, exception):
    if exception is not None:
        print(f'Request {request_id} failed: {exception}')
    else:
        print(f'Request {request_id} succeeded: {response}')

batch = http.BatchHttpRequest(callback=batch_callback)
batch.add(service.users().messages().get(userId='me', id='msg1'))
batch.add(service.users().messages().get(userId='me', id='msg2'))
batch.execute()