Home/Blog/How to Use a Translation API in Python: Complete Tutorial (2026)
Python Tutorial

How to Use a Translation API in Python: Complete Tutorial (2026)

Step-by-step guide to adding machine translation to your Python project. Covers the Langbly SDK, raw HTTP requests, Google's official client, error handling, and best practices.

Thomas van Leer· Content Manager, LangblyFebruary 13, 202611 min read

Adding translation to a Python application is one of the most common integration tasks for developers building multilingual products. Whether you're localizing a web app, translating user content, processing multilingual data, or building a chatbot that speaks multiple languages, you need a reliable translation API.

This tutorial walks you through three approaches, from the simplest (using a dedicated SDK) to the most manual (raw HTTP requests), with full code examples, error handling, and production best practices.

Prerequisites

Before starting, make sure you have:

  • Python 3.8+ installed
  • pip for package management
  • A translation API key. You can get a free Langbly key (500K characters/month, no credit card)

We'll use Langbly for the primary examples because it offers the simplest setup (no cloud project required) and has a Google Translate v2-compatible API, so the patterns translate directly to Google's API as well.

Option 1: Using Langbly's Python SDK

The fastest way to add translation to a Python project is with the Langbly Python SDK. It handles authentication, retries, error handling, and type hints out of the box.

Installation

pip install langbly

Basic Translation

from langbly import Langbly

client = Langbly("YOUR_API_KEY")

# Translate a single string
result = client.translate("Hello, how are you?", target="nl")
print(result.translated_text)
# Output: Hallo, hoe gaat het met je?

Specifying Source Language

# Let the API auto-detect the source language
result = client.translate("Bonjour le monde", target="en")
print(result.translated_text)
# Output: Hello world
print(result.detected_source_language)
# Output: fr

# Or specify it explicitly
result = client.translate("Bonjour le monde", source="fr", target="en")
print(result.translated_text)
# Output: Hello world

Batch Translation

Translate multiple strings in a single API call for better performance:

# Translate multiple strings at once
texts = [
    "Welcome to our platform",
    "Your account has been created",
    "Click here to get started"
]

results = client.translate(texts, target="de")
for r in results:
    print(r.translated_text)

# Output:
# Willkommen auf unserer Plattform
# Dein Konto wurde erstellt
# Klicke hier, um loszulegen

Translating HTML Content

When translating HTML, the API preserves tags and only translates the text content:

# HTML content: tags are preserved, only text is translated
html = "<p>Welcome to <strong>our platform</strong>. Click <a href='/start'>here</a> to begin.</p>"

result = client.translate(html, target="fr", format="html")
print(result.translated_text)
# Output: <p>Bienvenue sur <strong>notre plateforme</strong>. Cliquez <a href='/start'>ici</a> pour commencer.</p>

Language Detection

# Detect the language of a text
detections = client.detect("Ciao, come stai?")
print(detections[0].language)    # it
print(detections[0].confidence)  # 1.0

Listing Supported Languages

# Get all supported languages
languages = client.get_languages()
for lang in languages[:5]:
    print(f"{lang.language}: {lang.name}")

# Output:
# af: Afrikaans
# ar: Arabic
# bg: Bulgarian
# bn: Bengali
# ca: Catalan

Option 2: Using Requests Directly

If you prefer not to install an SDK, you can call the translation API directly with the requests library. Since Langbly uses the Google Translate v2 API format, these examples work with both providers; just change the URL and auth method.

Installation

pip install requests

Basic Translation

import requests

API_KEY = "YOUR_LANGBLY_API_KEY"
BASE_URL = "https://api.langbly.com/language/translate/v2"

def translate(text, target, source=None, format="text"):
    """Translate text using the Google Translate v2-compatible API."""
    payload = {
        "q": text,
        "target": target,
        "format": format,
    }
    if source:
        payload["source"] = source

    response = requests.post(
        BASE_URL,
        headers={
            "Authorization": f"Bearer {API_KEY}",
            "Content-Type": "application/json",
        },
        json=payload,
    )
    response.raise_for_status()
    data = response.json()
    return data["data"]["translations"][0]["translatedText"]

# Usage
print(translate("Hello world", target="es"))
# Output: Hola mundo

Batch Translation

def translate_batch(texts, target, source=None):
    """Translate multiple texts in a single API call."""
    payload = {
        "q": texts,  # Pass a list of strings
        "target": target,
        "format": "text",
    }
    if source:
        payload["source"] = source

    response = requests.post(
        BASE_URL,
        headers={
            "Authorization": f"Bearer {API_KEY}",
            "Content-Type": "application/json",
        },
        json=payload,
    )
    response.raise_for_status()
    data = response.json()
    return [t["translatedText"] for t in data["data"]["translations"]]

# Usage
results = translate_batch(
    ["Good morning", "Good night", "Thank you"],
    target="ja"
)
for text in results:
    print(text)

Language Detection

def detect_language(text):
    """Detect the language of the given text."""
    response = requests.post(
        "https://api.langbly.com/language/translate/v2/detect",
        headers={
            "Authorization": f"Bearer {API_KEY}",
            "Content-Type": "application/json",
        },
        json={"q": text},
    )
    response.raise_for_status()
    data = response.json()
    return data["data"]["detections"][0][0]

detection = detect_language("Wie geht es Ihnen?")
print(f"Language: {detection['language']}, Confidence: {detection['confidence']}")
# Language: de, Confidence: 1.0

Option 3: Using Google's Official SDK

If you're using Google Cloud and want to use Google's official client library, here's how. This approach requires a Google Cloud project with the Translation API enabled and a service account or API key.

Installation

pip install google-cloud-translate

Setup

from google.cloud import translate_v2 as translate

# Option 1: Use a service account (recommended for production)
# Set the GOOGLE_APPLICATION_CREDENTIALS environment variable
# to the path of your service account JSON file
client = translate.Client()

# Option 2: Use an API key
client = translate.Client(target_language="en")

Basic Translation

from google.cloud import translate_v2 as translate

client = translate.Client()

result = client.translate(
    "Hello, how are you?",
    target_language="fr"
)

print(result["translatedText"])
# Output: Bonjour, comment allez-vous ?
print(result["detectedSourceLanguage"])
# Output: en

Key Differences from Langbly

Google's official SDK is more verbose to set up: you need a Google Cloud project, billing account, enabled API, and either a service account JSON file or API key. The SDK itself is well-designed, but the infrastructure requirements add friction. You also don't get built-in retry logic for rate limits, so you'll need to implement that yourself or use a separate retry library.

Error Handling

Production applications need robust error handling. Here are the most common errors and how to handle them:

With the Langbly SDK

from langbly import Langbly
from langbly.errors import (
    AuthenticationError,
    RateLimitError,
    LangblyError,
)

client = Langbly("YOUR_API_KEY")

try:
    result = client.translate("Hello", target="nl")
    print(result.translated_text)

except AuthenticationError:
    print("Invalid API key. Check your key at langbly.com/dashboard")

except RateLimitError as e:
    print(f"Rate limited. Retry after {e.retry_after} seconds")
    # The SDK handles retries automatically by default

except LangblyError as e:
    print(f"Translation failed: {e.message} (status: {e.status_code})")

With Raw Requests

import requests
import time

def translate_with_retry(text, target, max_retries=3):
    """Translate with automatic retry for rate limits."""
    for attempt in range(max_retries):
        response = requests.post(
            "https://api.langbly.com/language/translate/v2",
            headers={
                "Authorization": f"Bearer {API_KEY}",
                "Content-Type": "application/json",
            },
            json={"q": text, "target": target, "format": "text"},
        )

        if response.status_code == 200:
            return response.json()["data"]["translations"][0]["translatedText"]

        if response.status_code == 429:
            # Rate limited - wait and retry
            retry_after = int(response.headers.get("Retry-After", 2))
            print(f"Rate limited. Waiting {retry_after}s (attempt {attempt + 1})")
            time.sleep(retry_after)
            continue

        if response.status_code == 401:
            raise ValueError("Invalid API key")

        if response.status_code == 400:
            error = response.json()
            raise ValueError(f"Bad request: {error.get('error', {}).get('message')}")

        response.raise_for_status()

    raise RuntimeError(f"Translation failed after {max_retries} retries")

Best Practices

1. Cache Translations

If you translate the same text repeatedly (like UI labels or product categories), cache the results to avoid unnecessary API calls and costs:

from functools import lru_cache
from langbly import Langbly

client = Langbly("YOUR_API_KEY")

@lru_cache(maxsize=10000)
def cached_translate(text: str, target: str) -> str:
    """Cache translations to avoid redundant API calls."""
    result = client.translate(text, target=target)
    return result.translated_text

# First call hits the API
print(cached_translate("Save", "nl"))  # API call

# Second call returns cached result
print(cached_translate("Save", "nl"))  # From cache - free and instant

For persistent caching across application restarts, use Redis or a database:

import redis
import json

r = redis.Redis(host="localhost", port=6379, db=0)

def cached_translate_redis(text: str, target: str) -> str:
    """Cache translations in Redis for persistence across restarts."""
    cache_key = f"translate:{target}:{text}"
    cached = r.get(cache_key)

    if cached:
        return cached.decode("utf-8")

    result = client.translate(text, target=target)
    translated = result.translated_text
    r.setex(cache_key, 86400, translated)  # Cache for 24 hours
    return translated

2. Batch Your Requests

Sending 100 individual translation requests is slower and less efficient than sending one request with 100 strings. Always use batch translation when translating multiple texts:

# Bad: 100 individual API calls
for text in texts:
    result = client.translate(text, target="fr")

# Good: 1 batch API call
results = client.translate(texts, target="fr")

3. Use Async for High Throughput

For applications that need to translate large volumes concurrently, use aiohttp for async HTTP requests:

import aiohttp
import asyncio

API_KEY = "YOUR_LANGBLY_API_KEY"

async def translate_async(session, text, target):
    """Translate a single text asynchronously."""
    async with session.post(
        "https://api.langbly.com/language/translate/v2",
        headers={
            "Authorization": f"Bearer {API_KEY}",
            "Content-Type": "application/json",
        },
        json={"q": text, "target": target, "format": "text"},
    ) as response:
        data = await response.json()
        return data["data"]["translations"][0]["translatedText"]

async def translate_many(texts, target, max_concurrent=10):
    """Translate multiple texts concurrently with rate limiting."""
    semaphore = asyncio.Semaphore(max_concurrent)

    async def limited_translate(session, text):
        async with semaphore:
            return await translate_async(session, text, target)

    async with aiohttp.ClientSession() as session:
        tasks = [limited_translate(session, text) for text in texts]
        return await asyncio.gather(*tasks)

# Usage
texts = ["Hello", "World", "How are you?"] * 100
results = asyncio.run(translate_many(texts, target="nl"))

4. Handle HTML Properly

When translating HTML content, always set format="html" to preserve tags:

# Correct: tags are preserved
result = client.translate(
    "<p>Welcome to <strong>our site</strong></p>",
    target="de",
    format="html"
)
# Output: <p>Willkommen auf <strong>unserer Website</strong></p>

# Incorrect: tags might be translated or corrupted
result = client.translate(
    "<p>Welcome to <strong>our site</strong></p>",
    target="de",
    format="text"  # Don't do this with HTML!
)

5. Set Timeouts

Always set timeouts on your API calls to prevent hanging requests:

import requests

response = requests.post(
    "https://api.langbly.com/language/translate/v2",
    headers={"Authorization": f"Bearer {API_KEY}"},
    json={"q": text, "target": "nl"},
    timeout=30,  # 30-second timeout
)

Pricing Comparison for Python Developers

If you're choosing between translation APIs for your Python project, here's what you'd pay at typical development and production volumes:

VolumeLangblyGoogle TranslateDeepL ProSavings vs Google
500K/month (dev/testing) Free $10 $18 100%
5M/month (small SaaS) $19 $100 $131 81%
25M/month (growing app) $69 $500 $631 86%
100M/month (production) $199 $2,000 $2,506 90%

The free tier is particularly useful for Python developers: 500K characters per month is enough to build, test, and prototype without spending anything. When you go to production, plans start at $19/month. See our pricing page for full details.

Next Steps

You now have everything you need to add translation to your Python project. Here's the recommended path:

  1. Get a free Langbly API key (30-second signup, no credit card)
  2. Install the SDK: pip install langbly
  3. Start with the basic translation example above
  4. Add caching and error handling for production
  5. Check the full API documentation for advanced features

The Langbly Python SDK is open source and available on GitHub. Issues and contributions are welcome.

Related Articles

PythonTranslation APITutorialSDKCode ExamplesDeveloper Guide

Start translating in Python today

Get a free Langbly API key. 500K characters/month, no credit card. Install the SDK and translate in under 2 minutes.