Skip to main content

A strongly-typed, performant, and modular Python SDK for consuming the Translaas Translation Delivery API

Project description

Translaas SDK

Tests PyPI version PyPI downloads License Python PyPI - Python versions GitHub stars GitHub forks Code size

A strongly-typed, performant, and modular Python SDK for consuming the Translaas Translation Delivery API. This SDK provides a clean, easy-to-use way to retrieve translations in your Python applications.

Features

  • Strongly-typed API - Full type hints support with IDE autocomplete and type safety
  • Convenience API - Simple t() method for quick translation lookups via TranslaasService
  • Automatic Language Resolution - Optional language parameter with configurable providers (HTTP request, default)
  • Framework Integrations - Flask, FastAPI, Django, and other framework integrations
  • Flexible Caching - Built-in memory caching with configurable cache modes
  • Offline Caching - File-based caching for offline mode with automatic sync
  • Hybrid Caching - Two-level caching (memory L1 + file L2) for optimal performance
  • Multi-Environment Support - Works in Python 3.8+, CPython, PyPy, and modern Python runtimes
  • Configurable timeouts - HTTP client timeout via TranslaasOptions
  • Single installable package - All modules ship in the translaas PyPI package
  • Async/Await - Fully asynchronous API for optimal performance
  • Type Hints - Native Python type hints with full IDE support

Installation

pip

pip install translaas

pip with virtual environment (Recommended)

python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
pip install translaas

Quick Start

1. Install Package

pip install translaas

2. Create Client

Option A: Using TranslaasService (Recommended for simple lookups)

from translaas import TranslaasService, TranslaasOptions, CacheMode, LanguageCodes

options = TranslaasOptions(
    api_key='your-api-key-here',
    base_url='https://api.translaas.com',  # or your custom base URL
    cache_mode=CacheMode.GROUP,  # Optional: configure caching
)

translaas = TranslaasService(options)

# Use the convenient t() method
# lang parameter is optional when language providers are configured
welcome = await translaas.t('common', 'welcome', LanguageCodes.ENGLISH)

# Automatic language resolution (requires providers configured)
welcome_auto = await translaas.t('common', 'welcome')  # lang omitted

# With pluralization
items = await translaas.t('messages', 'item', LanguageCodes.ENGLISH, 5)

Option B: Using TranslaasClient (Full API access)

from translaas import TranslaasClient, TranslaasOptions

options = TranslaasOptions(
    api_key='your-api-key-here',
    base_url='https://api.translaas.com',
)

client = TranslaasClient(options)

# Get a single translation entry
translation = await client.get_entry('common', 'welcome', 'en')

Configuration

Basic Configuration

from translaas import TranslaasService, TranslaasOptions, LanguageCodes

options = TranslaasOptions(
    # Required: API key and base URL
    api_key='your-api-key',
    base_url='https://api.translaas.com',
)

translaas = TranslaasService(options)

Advanced Configuration

from translaas import TranslaasService, TranslaasOptions, CacheMode, LanguageCodes

options = TranslaasOptions(
    # Required: API key and base URL
    api_key='your-api-key',
    base_url='https://api.translaas.com',

    # Optional: Default language fallback
    default_language=LanguageCodes.ENGLISH,

    # Optional: Caching configuration
    cache_mode=CacheMode.GROUP,
    cache_absolute_expiration=3600.0,  # 1 hour in seconds
    cache_sliding_expiration=900.0,  # 15 minutes in seconds

    # Optional: HTTP Client timeout
    timeout=30.0,  # 30 seconds
)

translaas = TranslaasService(options)

Configuration Options:

Option Required Description
api_key Required Your Translaas API key
base_url Required API origin (e.g. https://api.translaas.com). May include /sdk/v1; it is stripped automatically.
default_project ⚪ Optional Default project query for text calls and offline get_entry when using a multi-project key
channel ⚪ Optional SDK snapshot channel query (channel)
snapshot_version ⚪ Optional SDK snapshot version query (v)
include_context ⚪ Optional Adds includeContext on project/group/offline-cache requests
use_conditional_requests ⚪ Optional Send If-None-Match and handle 304 Not Modified when caching is enabled
offline_cache ⚪ Optional OfflineCacheOptions for file-based offline mode (see below)
default_language ⚪ Optional Default language code fallback (e.g., LanguageCodes.ENGLISH)
cache_mode ⚪ Optional Caching mode (CacheMode.NONE, CacheMode.ENTRY, CacheMode.GROUP, CacheMode.PROJECT)
cache_absolute_expiration ⚪ Optional Absolute cache expiration time (seconds)
cache_sliding_expiration ⚪ Optional Sliding cache expiration time (seconds)
timeout ⚪ Optional HTTP client timeout (seconds)

Configuration from Environment Variables

# .env file
TRANSLAAS_API_KEY=your-api-key
TRANSLAAS_BASE_URL=https://api.translaas.com
TRANSLAAS_CACHE_MODE=GROUP
TRANSLAAS_DEFAULT_LANGUAGE=en
import os
from translaas import TranslaasService, TranslaasOptions, CacheMode

options = TranslaasOptions(
    api_key=os.getenv('TRANSLAAS_API_KEY'),
    base_url=os.getenv('TRANSLAAS_BASE_URL', 'https://api.translaas.com'),
    cache_mode=CacheMode[os.getenv('TRANSLAAS_CACHE_MODE', 'NONE')],
    default_language=os.getenv('TRANSLAAS_DEFAULT_LANGUAGE'),
)

translaas = TranslaasService(options)

Note: api_key should be stored in environment variables or secure configuration, not in source code.

Framework integrations (Flask, Django, from_env) also accept TRANSLAAS_DEFAULT_PROJECT, TRANSLAAS_CHANNEL, TRANSLAAS_SNAPSHOT_VERSION, TRANSLAAS_INCLUDE_CONTEXT, TRANSLAAS_USE_CONDITIONAL_REQUESTS, and offline settings (TRANSLAAS_OFFLINE_CACHE_ENABLED, TRANSLAAS_OFFLINE_CACHE_DIRECTORY, TRANSLAAS_OFFLINE_FALLBACK_MODE, etc.). See translaas.extensions.config.

Offline mode

When offline_cache.enabled is True, TranslaasService wraps the HTTP client with CachingTranslaasClient and reads/writes the on-disk layout from the HTTP spec (§7.6): manifest.json, {project}/locales.json, {project}/{lang}/project.json.

from translaas import TranslaasOptions, TranslaasService
from translaas.models.enums import OfflineFallbackMode
from translaas.models.options import OfflineCacheOptions

options = TranslaasOptions(
    api_key="your-api-key",
    base_url="https://api.translaas.com",
    default_project="my-project",
    offline_cache=OfflineCacheOptions(
        enabled=True,
        cache_directory=".translaas-cache",
        fallback_mode=OfflineFallbackMode.CACHE_FIRST,
        default_project_id="my-project",
    ),
)

async with TranslaasService(options) as service:
    text = await service.t("common", "welcome", "en")

Use OfflineCacheSyncService to populate the cache from the API or an offline ZIP bundle (parse_offline_zip).

Usage Examples

Get Single Translation Entry

Using TranslaasService (Convenience API):

from translaas import LanguageCodes

# Basic usage with explicit language
translation = await translaas.t('ui', 'button.save', LanguageCodes.ENGLISH)

# Automatic language resolution (requires providers configured)
translation = await translaas.t('ui', 'button.save')  # lang omitted

# With pluralization
message = await translaas.t('messages', 'item.count', LanguageCodes.ENGLISH, 5)

Using TranslaasClient (Full API):

from translaas import LanguageCodes

# Basic usage
translation = await client.get_entry('ui', 'button.save', LanguageCodes.ENGLISH)

# With pluralization
message = await client.get_entry(
    'messages',
    'item.count',
    LanguageCodes.ENGLISH,
    5  # Used for pluralization rules
)

Environment Compatibility

The SDK supports multiple Python environments:

Environment Compatible With
CPython Python 3.8+
PyPy PyPy 3.8+
AsyncIO Full async/await support

The SDK uses httpx for async HTTP requests and requests for synchronous requests.

Error Handling

from translaas import TranslaasApiException, LanguageCodes

try:
    translation = await client.get_entry('group', 'entry', LanguageCodes.ENGLISH)
except TranslaasApiException as e:
    # Handle Translaas-specific errors
    print(f"Error: {e.message}")
    print(f"Status Code: {e.status_code}")
except Exception as e:
    # Handle other errors
    print(f"Error: {str(e)}")

Development

Building from Source

git clone https://github.com/acuencadev/translaas-sdk-python.git
cd translaas-sdk-python
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
pip install -e ".[dev]"
python -m build

Running Tests

pytest

Running Tests with Coverage

pytest --cov=translaas --cov-report=html

API Endpoints

The SDK communicates with the Translaas HTTP API (OpenAPI-aligned paths). base_url should be the API origin only (for example https://api.translaas.com).

Endpoint Method Purpose
/sdk/v1/translations/text GET Get single translation entry
/sdk/v1/translations/group GET Get all translations for a group
/sdk/v1/translations/project GET Get all translations for a project
/sdk/v1/translations/locales GET Get available locales for a project
/sdk/v1/translations/report-missing POST Report missing keys (project-scoped API key)
/sdk/v1/translations/offline-cache GET Download offline translation ZIP bundle
/api/v1/api-keys/validate GET Validate API key (connectivity / bootstrap)

Note: Translation endpoints use GET with query parameters except report-missing (JSON body). Optional query flags include channel, v, and includeContext where the backend supports them; configure via TranslaasOptions or per-call arguments on the client.

Authentication

The SDK uses API key authentication via the X-Api-Key header. Provide your API key during client creation:

options = TranslaasOptions(
    api_key='your-api-key-here',
    base_url='https://api.translaas.com',
)

Examples

In the translaas-all meta-repo, Python samples live under examples/python/ (mirroring the JavaScript samples under examples/js/).

Offline — Node-style console sample

CacheOnly demo using CachingTranslaasClient and a pre-seeded file cache (no live API calls):

cd examples/python/offline-node
python -m venv venv
source venv/bin/activate  # Windows: venv\Scripts\activate
pip install -r requirements.txt
python main.py

Optional: copy .env.example to .env when extending the sample to call the live API for cache sync.

Additional framework examples (basic, flask, fastapi, django) may exist locally but are not tracked in the SDK repository (see .gitignore).

License

This project is licensed under the MIT License - see the LICENSE file for details.

Copyright (c) 2025 Translaas SDK Contributors

Support

  • Documentation: [Link to full documentation]
  • Issues: [https://github.com/acuencadev/translaas-sdk-python/issues]
  • API Reference: [Swagger/API Docs URL]

Contributing

We welcome contributions to the Translaas SDK! Please read our Contributing Guidelines for details on:

  • How to get started
  • Development guidelines and code style
  • Pull request process
  • Commit message conventions
  • Reporting issues

For more information, see CONTRIBUTING.md.


Made with ❤️ for the Python community

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

translaas-0.4.0b1.tar.gz (70.0 kB view details)

Uploaded Source

Built Distribution

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

translaas-0.4.0b1-py3-none-any.whl (69.0 kB view details)

Uploaded Python 3

File details

Details for the file translaas-0.4.0b1.tar.gz.

File metadata

  • Download URL: translaas-0.4.0b1.tar.gz
  • Upload date:
  • Size: 70.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for translaas-0.4.0b1.tar.gz
Algorithm Hash digest
SHA256 91248eb534790bf341ff737b80e49224c0f05d536950262d93e5f725289383ca
MD5 a87c913a61e695c9d4efafa95d404806
BLAKE2b-256 f3bb10fb7918f7432de162fe551a726cc5c3a8d029c5b1d1460c7e38d909b5ed

See more details on using hashes here.

Provenance

The following attestation bundles were made for translaas-0.4.0b1.tar.gz:

Publisher: release.yml on acuencadev/translaas-sdk-python

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file translaas-0.4.0b1-py3-none-any.whl.

File metadata

  • Download URL: translaas-0.4.0b1-py3-none-any.whl
  • Upload date:
  • Size: 69.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for translaas-0.4.0b1-py3-none-any.whl
Algorithm Hash digest
SHA256 4879ef0f4383555a6547295dbfc2383d81876f68e170a12a0d30a8f7786585e6
MD5 8fd0f2ab6cbd3a3a0f39c821167af1ce
BLAKE2b-256 ce450187663074ebccfd9971a281cfdca436ce477e97fd37d696a9aba80b1d8f

See more details on using hashes here.

Provenance

The following attestation bundles were made for translaas-0.4.0b1-py3-none-any.whl:

Publisher: release.yml on acuencadev/translaas-sdk-python

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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