CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-google-api-core

Google API client core library providing common helpers, utilities, and components for Python client libraries

Pending
Overview
Eval results
Files

client-config.mddocs/

Client Configuration

Configuration classes for customizing Google API client behavior, including authentication, endpoints, transport options, and client metadata. These utilities provide standardized ways to configure Google Cloud client libraries.

Capabilities

Client Options

Configuration class for customizing client behavior and transport settings.

class ClientOptions:
    """
    Configuration options for Google API clients.
    
    Args:
        api_endpoint (str, optional): Custom API endpoint URL
        client_cert_source (Callable, optional): Function returning client certificate
        client_encrypted_cert_source (Callable, optional): Function returning encrypted client certificate
        quota_project_id (str, optional): Project ID for quota attribution
        credentials_file (str, optional): Path to service account credentials file
        scopes (List[str], optional): OAuth 2.0 scopes for authentication
        default_scopes (List[str], optional): Default scopes if none provided
        universe_domain (str, optional): Universe domain (default: googleapis.com)
    """
    def __init__(self, api_endpoint=None, client_cert_source=None, client_encrypted_cert_source=None, quota_project_id=None, credentials_file=None, scopes=None, default_scopes=None, universe_domain=None): ...
    
    @property
    def api_endpoint(self):
        """
        Custom API endpoint URL.
        
        Returns:
            str or None: API endpoint URL
        """
    
    @property
    def client_cert_source(self):
        """
        Function that returns client certificate for mTLS.
        
        Returns:
            Callable or None: Certificate source function
        """
    
    @property
    def client_encrypted_cert_source(self):
        """
        Function that returns encrypted client certificate.
        
        Returns:
            Callable or None: Encrypted certificate source function
        """
    
    @property
    def quota_project_id(self):
        """
        Project ID for quota and billing attribution.
        
        Returns:
            str or None: Project ID
        """
    
    @property
    def credentials_file(self):
        """
        Path to service account credentials file.
        
        Returns:
            str or None: Credentials file path
        """
    
    @property
    def scopes(self):
        """
        OAuth 2.0 scopes for authentication.
        
        Returns:
            List[str] or None: Authentication scopes
        """
    
    @property
    def universe_domain(self):
        """
        Universe domain for the service.
        
        Returns:
            str: Universe domain (default: googleapis.com)
        """

def from_dict(options):
    """
    Construct ClientOptions from a dictionary or mapping.
    
    Args:
        options (dict): Dictionary containing client option values
        
    Returns:
        ClientOptions: Constructed client options instance
    """

Client Information

Client metadata for identifying library and version in API requests.

class ClientInfo:
    """
    Client information for user-agent headers and telemetry.
    
    Args:
        client_library_name (str, optional): Name of the client library
        client_library_version (str, optional): Version of the client library
        application_name (str, optional): Name of the application using the client
        user_agent (str, optional): Custom user agent string
    """
    def __init__(self, client_library_name=None, client_library_version=None, application_name=None, user_agent=None): ...
    
    @property
    def client_library_name(self):
        """
        Name of the client library.
        
        Returns:
            str or None: Client library name
        """
    
    @property
    def client_library_version(self):
        """
        Version of the client library.
        
        Returns:
            str or None: Client library version
        """
    
    @property
    def application_name(self):
        """
        Name of the application using the client.
        
        Returns:
            str or None: Application name
        """
    
    @property
    def user_agent(self):
        """
        User agent string for HTTP requests.
        
        Returns:
            str: Complete user agent string
        """
    
    def to_grpc_metadata(self):
        """
        Convert client info to gRPC metadata format.
        
        Returns:
            List[Tuple[str, str]]: gRPC metadata pairs
        """
    
    def to_user_agent(self):
        """
        Generate user agent string from client info.
        
        Returns:
            str: User agent string for HTTP headers
        """

Usage Examples

Basic Client Configuration

from google.api_core import client_options
from google.auth import default

# Create basic client options
options = client_options.ClientOptions(
    api_endpoint="https://custom-api.example.com",
    quota_project_id="my-billing-project"
)

# Use with a client library
from google.cloud import storage

client = storage.Client(client_options=options)

mTLS Configuration

from google.api_core import client_options
import ssl

def get_client_cert():
    """Load client certificate for mTLS."""
    with open("/path/to/client.crt", "rb") as cert_file:
        cert_data = cert_file.read()
    with open("/path/to/client.key", "rb") as key_file:
        key_data = key_file.read()
    return cert_data, key_data

# Configure mTLS
options = client_options.ClientOptions(
    api_endpoint="https://mtls-api.example.com",
    client_cert_source=get_client_cert
)

# Client will use mTLS for authentication
client = MyAPIClient(client_options=options)

Configuration from Dictionary

from google.api_core import client_options

# Configuration from dictionary
config_dict = {
    "api_endpoint": "https://europe-west1-api.example.com",
    "quota_project_id": "my-project-123",
    "scopes": [
        "https://www.googleapis.com/auth/cloud-platform",
        "https://www.googleapis.com/auth/bigquery"
    ],
    "universe_domain": "googleapis.com"
}

options = client_options.from_dict(config_dict)

# Use configured options
client = MyAPIClient(client_options=options)

Client Information Setup

from google.api_core import client_info

# Create client info for telemetry
info = client_info.ClientInfo(
    client_library_name="my-python-client",
    client_library_version="1.2.3",
    application_name="data-processor-app"
)

# Use with API client
client = MyAPIClient(client_info=info)

# Get user agent string
user_agent = info.to_user_agent()
print(user_agent)  # "my-python-client/1.2.3 data-processor-app"

# Get gRPC metadata
metadata = info.to_grpc_metadata()
print(metadata)  # [('x-goog-api-client', 'my-python-client/1.2.3')]

Environment-Based Configuration

import os
from google.api_core import client_options

def create_client_options_from_env():
    """Create client options from environment variables."""
    options = client_options.ClientOptions()
    
    # Set endpoint from environment
    if endpoint := os.getenv("API_ENDPOINT"):
        options = client_options.ClientOptions(api_endpoint=endpoint)
    
    # Set quota project from environment
    if project := os.getenv("QUOTA_PROJECT_ID"):
        options = client_options.ClientOptions(
            api_endpoint=options.api_endpoint,
            quota_project_id=project
        )
    
    # Set credentials file from environment
    if creds_file := os.getenv("GOOGLE_APPLICATION_CREDENTIALS"):
        options = client_options.ClientOptions(
            api_endpoint=options.api_endpoint,
            quota_project_id=options.quota_project_id,
            credentials_file=creds_file
        )
    
    return options

# Use environment-based configuration
options = create_client_options_from_env()
client = MyAPIClient(client_options=options)

Regional Endpoint Configuration

from google.api_core import client_options

def create_regional_client(region="us-central1"):
    """Create client configured for specific region."""
    # Regional endpoint pattern for Google Cloud APIs
    endpoint = f"https://{region}-api.example.com"
    
    options = client_options.ClientOptions(
        api_endpoint=endpoint,
        quota_project_id="my-regional-project"
    )
    
    return MyAPIClient(client_options=options)

# Create clients for different regions
us_client = create_regional_client("us-central1")
eu_client = create_regional_client("europe-west1") 
asia_client = create_regional_client("asia-southeast1")

Advanced Configuration Pattern

from google.api_core import client_options, client_info
from google.auth import default
import logging

class ConfiguredClient:
    """Example of a properly configured Google API client."""
    
    def __init__(self, service_name, version, **config):
        # Set up client info
        self.client_info = client_info.ClientInfo(
            client_library_name=f"{service_name}-python",
            client_library_version=version,
            application_name=config.get("app_name", "unknown-app")
        )
        
        # Set up client options
        self.client_options = client_options.ClientOptions(
            api_endpoint=config.get("endpoint"),
            quota_project_id=config.get("quota_project"),
            credentials_file=config.get("credentials_file"),
            universe_domain=config.get("universe_domain", "googleapis.com")
        )
        
        # Initialize credentials
        self.credentials, self.project = default(
            scopes=config.get("scopes"),
            quota_project_id=self.client_options.quota_project_id
        )
        
        # Configure logging
        self.logger = logging.getLogger(f"{service_name}.client")
        
    def get_config_summary(self):
        """Get summary of current configuration."""
        return {
            "endpoint": self.client_options.api_endpoint,
            "project": self.project,
            "quota_project": self.client_options.quota_project_id,
            "client_info": self.client_info.to_user_agent(),
            "universe_domain": self.client_options.universe_domain
        }

# Usage
config = {
    "endpoint": "https://api.example.com",
    "quota_project": "my-billing-project",
    "app_name": "data-pipeline",
    "scopes": ["https://www.googleapis.com/auth/cloud-platform"]
}

configured_client = ConfiguredClient("myservice", "1.0.0", **config)
print("Client configuration:", configured_client.get_config_summary())

Scope Management

from google.api_core import client_options

# Define scopes for different access levels
READ_ONLY_SCOPES = [
    "https://www.googleapis.com/auth/cloud-platform.read-only"
]

FULL_ACCESS_SCOPES = [
    "https://www.googleapis.com/auth/cloud-platform"
]

SPECIFIC_SERVICE_SCOPES = [
    "https://www.googleapis.com/auth/bigquery",
    "https://www.googleapis.com/auth/storage.full_control"
]

def create_client_with_scopes(access_level="read-only"):
    """Create client with appropriate scopes based on access level."""
    scope_map = {
        "read-only": READ_ONLY_SCOPES,
        "full": FULL_ACCESS_SCOPES,
        "specific": SPECIFIC_SERVICE_SCOPES
    }
    
    scopes = scope_map.get(access_level, READ_ONLY_SCOPES)
    
    options = client_options.ClientOptions(
        scopes=scopes,
        quota_project_id="my-project"
    )
    
    return MyAPIClient(client_options=options)

# Create clients with different access levels
readonly_client = create_client_with_scopes("read-only")
full_client = create_client_with_scopes("full")
specific_client = create_client_with_scopes("specific")

Install with Tessl CLI

npx tessl i tessl/pypi-google-api-core

docs

bidirectional-streaming.md

client-config.md

datetime.md

exceptions.md

gapic-framework.md

iam-policies.md

index.md

operations.md

page-iteration.md

path-templates.md

protobuf-helpers.md

retry.md

timeout.md

transport.md

universe-domain.md

tile.json