CtrlK
BlogDocsLog inGet started
Tessl Logo

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.

Pending
Overview
Eval results
Files

discovery.mddocs/

API Discovery and Service Building

The discovery module provides the core functionality for dynamically building Google API service clients. It fetches API discovery documents, generates Python classes and methods, and handles authentication integration.

Capabilities

Service Building

Create service clients for Google APIs with automatic method generation and authentication.

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', 'youtube')
        version (str): Version of the service (e.g., 'v1', 'v2', 'v3')
        http (httplib2.Http, optional): HTTP client instance for requests
        discoveryServiceUrl (str, optional): URL for the discovery service
        developerKey (str, optional): API key for public API access
        model (BaseModel, optional): Data model for request/response handling  
        requestBuilder (RequestBuilder, optional): Custom request builder
        credentials (Credentials, optional): OAuth2 credentials for authenticated requests
        cache_discovery (bool): Whether to cache discovery documents (default: True)
        cache (Cache, optional): Custom cache implementation for discovery documents
        client_options (ClientOptions, optional): Client configuration options
        adc_cert_path (str, optional): Path to Application Default Credentials certificate
        adc_key_path (str, optional): Path to Application Default Credentials private key
        num_retries (int): Number of retry attempts for discovery document retrieval (default: 1)
        static_discovery (bool, optional): Use static discovery documents when available (None for auto-detection)
        always_use_jwt_access (bool): Always use JWT access tokens for service account credentials (default: False)
        
    Returns:
        Resource: A Resource object with dynamically generated methods for each API endpoint
        
    Raises:
        UnknownApiNameOrVersion: When the specified API name or version is not found
        HttpError: When the discovery document cannot be retrieved
    """

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 as a Python dictionary or JSON string
        base (str, optional): Base URI for the service endpoints (deprecated)
        future (str, optional): Future version identifier for experimental features (deprecated)
        developerKey (str, optional): API key for public API access
        http (httplib2.Http, optional): HTTP client instance for requests
        model (BaseModel, optional): Data model for request/response handling
        requestBuilder (RequestBuilder, optional): Custom request builder implementation
        credentials (Credentials, optional): OAuth2 credentials for authenticated requests
        client_options (ClientOptions, optional): Client configuration options
        adc_cert_path (str, optional): Path to Application Default Credentials certificate
        adc_key_path (str, optional): Path to Application Default Credentials private key
        always_use_jwt_access (bool): Always use JWT access tokens for service account credentials (default: False)
        
    Returns:
        Resource: A Resource object built from the provided discovery document
        
    Raises:
        ValueError: When the discovery document is malformed or incomplete
    """

Discovery Document Access

Retrieve and process Google API discovery documents.

def key2param(key):
    """
    Convert a discovery document key to a Python parameter name.
    
    Args:
        key (str): Key from discovery document
        
    Returns:
        str: Python-safe parameter name
    """

def fix_method_name(name):
    """
    Convert an API method name to Python naming convention.
    
    Args:
        name (str): Method name from discovery document
        
    Returns:
        str: Python-compatible method name
    """

Discovery Constants

DISCOVERY_URI = "https://www.googleapis.com/discovery/v1/apis/{api}/{apiVersion}/rest"
V1_DISCOVERY_URI = "https://www.googleapis.com/discovery/v1/apis/{api}/{apiVersion}/rest" 
V2_DISCOVERY_URI = "https://{api}.googleapis.com/$discovery/rest?version={apiVersion}"

# Environment variables for mTLS configuration
GOOGLE_API_USE_CLIENT_CERTIFICATE = "GOOGLE_API_USE_CLIENT_CERTIFICATE"
GOOGLE_API_USE_MTLS_ENDPOINT = "GOOGLE_API_USE_MTLS_ENDPOINT"
GOOGLE_CLOUD_UNIVERSE_DOMAIN = "GOOGLE_CLOUD_UNIVERSE_DOMAIN"
DEFAULT_UNIVERSE = "googleapis.com"

# HTTP and parameter processing constants
HTTP_PAYLOAD_METHODS = frozenset(["PUT", "POST", "PATCH"])
STACK_QUERY_PARAMETERS = frozenset(["trace", "pp", "userip", "strict"])
RESERVED_WORDS = frozenset(["body"])
DEFAULT_METHOD_DOC = "A description of how to use this function"

Resource Classes

Dynamic API resource classes generated from discovery documents.

class Resource:
    """
    A class for interacting with a resource.
    
    Methods are dynamically generated based on the discovery document and provide
    typed access to API endpoints with proper parameter validation and authentication.
    """
    
    def __init__(self, http, baseUrl, model, requestBuilder, developerKey, 
                 resourceDesc, rootDesc, schema, universe_domain="googleapis.com"):
        """
        Initialize a Resource object.
        
        Args:
            http (httplib2.Http): Object to make HTTP requests
            baseUrl (str): Base URL for the API
            model (googleapiclient.Model): Wire format converter
            requestBuilder (callable): HttpRequest object instantiator
            developerKey (str): API key from Google APIs Console
            resourceDesc (dict): Section of discovery document describing resource
            rootDesc (dict): Entire deserialized discovery document
            schema (dict): Mapping of schema names to descriptions
            universe_domain (str): Universe for the API (default: "googleapis.com")
        """
    
    def close(self):
        """
        Close httplib2 connections.
        """
    
    def __enter__(self):
        """
        Context manager entry.
        
        Returns:
            Resource: Self for context management
        """
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        """
        Context manager exit with connection cleanup.
        """
    
    def new_batch_http_request(self, callback=None):
        """
        Create a BatchHttpRequest object (only available on root resources).
        
        Args:
            callback (callable, optional): Default callback for batch requests
            
        Returns:
            BatchHttpRequest: Batch request object for combining multiple requests
        """

class ResourceMethodParameters:
    """
    Represents the parameters associated with a method.
    
    Stores metadata about API method parameters including validation rules,
    location information, and parameter types extracted from discovery documents.
    """
    
    def __init__(self, method_desc):
        """
        Initialize method parameters from discovery document.
        
        Args:
            method_desc (dict): Dictionary with metadata describing an API method
        """
    
    def set_parameters(self, method_desc):
        """
        Populate parameter maps and lists based on method description.
        
        Args:
            method_desc (dict): Method description from discovery document
        """

class APICoreVersionError(ValueError):
    """
    Raised when google-api-core >= 2.18.0 is required for universe domain features.
    
    This error occurs when attempting to use universe domain functionality
    without the required version of google-api-core installed.
    """

Usage Examples

Basic Service Building

from googleapiclient import discovery
import google.auth

# Build Gmail service with default credentials
credentials, project = google.auth.default()
gmail_service = discovery.build('gmail', 'v1', credentials=credentials)

# Build YouTube service with API key (for public data)
youtube_service = discovery.build('youtube', 'v3', developerKey='YOUR_API_KEY')

# Build Drive service with custom HTTP client
import httplib2
http = httplib2.Http()
drive_service = discovery.build('drive', 'v3', http=http, credentials=credentials)

Service Building with Custom Configuration

from googleapiclient import discovery
from googleapiclient.discovery_cache.file_cache import Cache
from google.api_core.client_options import ClientOptions

# Build service with custom cache
cache = Cache(max_age=3600)  # 1 hour cache
service = discovery.build(
    'gmail', 
    'v1', 
    credentials=credentials, 
    cache=cache,
    cache_discovery=True
)

# Build service with client options
client_options = ClientOptions(api_endpoint='https://custom-endpoint.googleapis.com')
service = discovery.build(
    'customsearch', 
    'v1', 
    credentials=credentials,
    client_options=client_options
)

Building from Discovery Document

import json
from googleapiclient import discovery

# Load discovery document from file
with open('gmail-v1-discovery.json', 'r') as f:
    discovery_doc = json.load(f)

# Build service from document
service = discovery.build_from_document(
    discovery_doc, 
    credentials=credentials
)

Error Handling During Service Building

from googleapiclient import discovery, errors

try:
    service = discovery.build('unknown-api', 'v1', credentials=credentials)
except errors.UnknownApiNameOrVersion as e:
    print(f"API not found: {e}")
except errors.HttpError as e:
    print(f"HTTP error during discovery: {e}")

Working with Generated Resource Methods

# Build service
service = discovery.build('gmail', 'v1', credentials=credentials)

# Access nested resources and methods
messages_resource = service.users().messages()

# Call methods (returns HttpRequest objects)
list_request = messages_resource.list(userId='me', maxResults=10)
get_request = messages_resource.get(userId='me', id='message_id')

# Execute requests
messages = list_request.execute()
message = get_request.execute()

Install with Tessl CLI

npx tessl i tessl/pypi-google-api-python-client@2.181.1

docs

auth.md

channel.md

discovery.md

errors.md

http.md

index.md

media.md

mimeparse.md

model.md

schema.md

testing.md

tile.json