Skip to main content

A Python HTTP client library for Google Translation API Server

Project description

Google API Client

A Python client library for Google Cloud APIs.

Installation

From Source

cd google-api-client
pip install -e .

Or install dependencies only:

pip install -r requirements.txt

Using pip

pip install google-api-client

Features

  • Interface Segregation: Clean separation of interface and implementation
  • Strong Typing: Full type hints for better IDE support and error detection
  • HTTP client interface for Google API Server
  • Easy integration with Translation API
  • Support for custom domain configuration
  • Async/await support
  • Streaming translation support
  • Batch translation support
  • Testability: Easy to create mock implementations
  • Extensibility: Multiple implementations possible (HTTP, gRPC, etc.)

Architecture

The library follows Interface Segregation Principle with clear separation:

  • Interface (interface.py): Protocol definition for type checking
  • Implementation (client.py): HTTP client implementation
  • Types (types.py): Strong type definitions
  • Response (response.py): Response data models

This separation enables:

  • ✅ Easy testing with mock implementations
  • ✅ Multiple implementations (HTTP, gRPC, WebSocket, etc.)
  • ✅ Strong type safety and IDE support
  • ✅ Dependency injection and loose coupling

Quick Start

Basic Usage

import asyncio
from google_api_client import GoogleAPIClient

async def main():
    # Create client with custom domain
    async with GoogleAPIClient(base_url="http://localhost:8000") as client:
        # Translate text
        result = await client.translate(
            text="Hello, World!",
            source_language="en",
            target_language="zh-CN"
        )
        print(f"Translated: {result.translated_text}")

asyncio.run(main())

Using Interface for Dependency Injection

from google_api_client import IGoogleAPIClient, GoogleAPIClient

async def translate_text(client: IGoogleAPIClient, text: str):
    """Function accepts interface, allowing easy testing with mocks"""
    return await client.translate(text, "en", "zh-CN")

# Use concrete implementation
async with GoogleAPIClient() as client:
    result = await translate_text(client, "Hello")

Custom Domain Configuration

from google_api_client import GoogleAPIClient

# Use custom domain
client = GoogleAPIClient(base_url="https://api.example.com")

# Or with port
client = GoogleAPIClient(base_url="http://192.168.1.100:8000")

# Or with subdomain
client = GoogleAPIClient(base_url="https://translate.company.com")

Batch Translation

async with GoogleAPIClient(base_url="http://localhost:8000") as client:
    result = await client.translate_to_multiple(
        text="Good morning!",
        source_language="en",
        target_languages=["zh-CN", "ja", "es", "fr", "de"]
    )
    
    for lang, translation in result.translations.items():
        print(f"{lang}: {translation}")

Streaming Translation

async with GoogleAPIClient(base_url="http://localhost:8000") as client:
    async for data in client.translate_stream(
        text="Hello, World!",
        source_language="en",
        target_languages=["zh-CN", "ja", "es"]
    ):
        if data.get('type') == 'translation':
            print(f"{data.get('language')}: {data.get('translated_text')}")

Language Detection

async with GoogleAPIClient(base_url="http://localhost:8000") as client:
    result = await client.detect_language("Hello, how are you?")
    print(f"Detected language: {result.detected_language}")

API Reference

GoogleAPIClient

Main client class for interacting with Google API Server.

Constructor

GoogleAPIClient(
    base_url: str = "http://localhost:8000",
    timeout: float = 30.0,
    max_retries: int = 3
)

Parameters:

  • base_url: Base URL of the API server (default: "http://localhost:8000")
  • timeout: Request timeout in seconds (default: 30.0)
  • max_retries: Maximum number of retry attempts (default: 3)

Methods

translate()

Translate text from source language to target language.

result: TranslationResponse = await client.translate(
    text: str,
    source_language: str,
    target_language: str
)
translate_to_multiple()

Translate text to multiple languages concurrently.

result: BatchTranslationResponse = await client.translate_to_multiple(
    text: str,
    source_language: str,
    target_languages: List[str]
)
detect_language()

Detect the language of text.

result: LanguageDetectionResponse = await client.detect_language(text: str)
translate_stream()

Stream translations using Server-Sent Events (SSE).

async for data in client.translate_stream(
    text: str,
    source_language: str,
    target_languages: List[str]
):
    # Process each translation result
    pass

Response Types

TranslationResponse

@dataclass
class TranslationResponse:
    original_text: str
    translated_text: str
    source_language: str
    target_language: str

BatchTranslationResponse

@dataclass
class BatchTranslationResponse:
    original_text: str
    source_language: str
    translations: Dict[str, str]  # Map of target language to translation

LanguageDetectionResponse

@dataclass
class LanguageDetectionResponse:
    text: str
    detected_language: str

Configuration

Enabling Required APIs

Make sure the following APIs are enabled in your Google Cloud project:

  • Google Cloud Translation API

Requirements

  • Python 3.8 or higher
  • httpx>=0.24.0 (for HTTP client)

Dependencies

  • httpx>=0.24.0

License

MIT

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

smooth_google_api_client-0.1.0.tar.gz (12.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

smooth_google_api_client-0.1.0-py3-none-any.whl (10.4 kB view details)

Uploaded Python 3

File details

Details for the file smooth_google_api_client-0.1.0.tar.gz.

File metadata

  • Download URL: smooth_google_api_client-0.1.0.tar.gz
  • Upload date:
  • Size: 12.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.7

File hashes

Hashes for smooth_google_api_client-0.1.0.tar.gz
Algorithm Hash digest
SHA256 c63ddf600dbe089c9c1d508ba423ed1f7f456fd05e50c45b68367d5bd6ca6ede
MD5 e2ed8d0db6e27818e021aee10a5a64ee
BLAKE2b-256 932498fab07c2ebe8a1b042a6120db322217118c5678c138c1cf779c49c0ce50

See more details on using hashes here.

File details

Details for the file smooth_google_api_client-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for smooth_google_api_client-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 be058440fc23a020b5aa3640867e228718378e90b90c8b3c444b28d110f03fd5
MD5 8798e5c8f712b26aad19a978b13ec448
BLAKE2b-256 3de1390702408f8dc8435bbabbe11eae6bbf7e79a66e882c5e5c6d1f32c838a7

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page