Working code for the official SDK, the unofficial library, and a drop-in replacement that costs 90% less.
Adding translation to your Python app sounds simple — until you see the Google Translate API bill. At $20 per million characters, costs spiral fast for any real-world workload. This tutorial covers everything you need to know: the official Google Cloud approach, the free googletrans library (and its pitfalls), and a drop-in alternative that costs 90% less.
By the end you'll have working code for all three approaches, a clear cost comparison, and a decision framework for which one fits your project.
pip install google-cloud-translate
You'll need a Google Cloud project, a service account JSON key, and billing enabled.
import os
from google.cloud import translate_v2 as translate
# Set credentials
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "path/to/service-account.json"
client = translate.Client()
def translate_text(text: str, target_language: str) -> str:
result = client.translate(text, target_language=target_language)
return result["translatedText"]
# Example
print(translate_text("Hello, world!", "es"))
# Output: "¡Hola, mundo!"
def translate_batch(texts: list[str], target: str) -> list[str]:
results = client.translate(texts, target_language=target)
return [r["translatedText"] for r in results]
texts = ["Good morning", "How are you?", "Thank you"]
translated = translate_batch(texts, "fr")
print(translated)
# ['Bonjour', 'Comment allez-vous?', 'Merci']
def detect_language(text: str) -> dict:
result = client.detect_language(text)
return {
"language": result["language"],
"confidence": result["confidence"]
}
print(detect_language("Bonjour le monde"))
# {'language': 'fr', 'confidence': 0.99}
googletrans is a popular Python library that reverse-engineers Google Translate's web interface. It's free — but comes with serious caveats.
pip install googletrans==4.0.0-rc1
from googletrans import Translator
translator = Translator()
# Basic translation
result = translator.translate("Hello, world!", dest="ja")
print(result.text)
# こんにちは、世界!
# Detect language
detected = translator.detect("Hola mundo")
print(detected.lang, detected.confidence)
# es 0.9990234375
| Issue | Impact |
|---|---|
| Unofficial API | Can break any time Google changes their web UI |
| Rate limiting | Gets blocked after ~100 requests/minute |
| No SLA | Zero uptime guarantees |
| ToS violation | Technically violates Google's Terms of Service |
| Async bugs | The asyncio version has known race conditions |
googletrans broke for weeks. If your product depends on it, you're one Google update away from an outage.
Bottom line: Fine for personal scripts. Never for production.
SocketsIO offers a translation API that's fully compatible with Google Translate v2, supports 195 languages, and costs a fraction of the price.
pip install requests # No special SDK needed
Or use the official SDK:
pip install socketsio
import requests
API_KEY = "your_socketsio_api_key"
BASE_URL = "https://api.socketsio.com/v1"
def translate_text(text: str, target: str, source: str = None) -> str:
payload = {"q": text, "target": target}
if source:
payload["source"] = source
response = requests.post(
f"{BASE_URL}/translate",
json=payload,
headers={"Authorization": f"Bearer {API_KEY}"}
)
response.raise_for_status()
return response.json()["data"]["translations"][0]["translatedText"]
print(translate_text("Hello, world!", "zh"))
# 你好,世界!
def translate_batch(texts: list[str], target: str) -> list[str]:
payload = {"q": texts, "target": target} # Pass a list directly
response = requests.post(
f"{BASE_URL}/translate",
json=payload,
headers={"Authorization": f"Bearer {API_KEY}"}
)
response.raise_for_status()
translations = response.json()["data"]["translations"]
return [t["translatedText"] for t in translations]
texts = ["Good morning", "How are you?", "Thank you"]
print(translate_batch(texts, "de"))
# ['Guten Morgen', 'Wie geht es Ihnen?', 'Danke']
def detect_language(text: str) -> dict:
response = requests.post(
f"{BASE_URL}/detect",
json={"q": text},
headers={"Authorization": f"Bearer {API_KEY}"}
)
response.raise_for_status()
result = response.json()["data"]["detections"][0][0]
return {"language": result["language"], "confidence": result["confidence"]}
print(detect_language("Ciao mondo"))
# {'language': 'it', 'confidence': 0.98}
from socketsio import TranslateClient
client = TranslateClient(api_key="your_api_key")
# Single translation
result = client.translate("Hello!", target="ko")
print(result.translated_text)
# 안녕하세요!
# Batch
results = client.translate(["Yes", "No", "Maybe"], target="ar")
for r in results:
print(r.translated_text)
# ============================================================
# GOOGLE CLOUD (Official)
# ============================================================
from google.cloud import translate_v2 as translate
import os
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "key.json"
client = translate.Client()
result = client.translate("Hello", target_language="fr")
print(result["translatedText"]) # Bonjour
# ============================================================
# SOCKETSIO (v2-compatible, no SDK needed)
# ============================================================
import requests
result = requests.post(
"https://api.socketsio.com/v1/translate",
json={"q": "Hello", "target": "fr"},
headers={"Authorization": "Bearer YOUR_KEY"}
).json()
print(result["data"]["translations"][0]["translatedText"]) # Bonjour
# ============================================================
# SOCKETSIO SDK (cleanest)
# ============================================================
from socketsio import TranslateClient
client = TranslateClient(api_key="YOUR_KEY")
print(client.translate("Hello", target="fr").translated_text) # Bonjour
| Provider | Free Tier | Paid Plan | Per Million Chars |
|---|---|---|---|
| Google Cloud Translate v2 | 500K chars/month | Pay-as-you-go | $20.00 |
| DeepL API | 500K chars/month | $5.49/month (1M chars) | ~$5.49 |
| SocketsIO Basic | 100K chars/month | $9/month (5M chars) | $1.80 |
| SocketsIO Pro | 100K chars/month | $29/month (50M chars) | $0.58 |
Imagine you're building a multilingual SaaS with 10 million characters/month:
| Provider | Monthly Cost |
|---|---|
| Google Cloud | $200.00 |
| DeepL | ~$54.90 |
| SocketsIO Pro | $29.00 |
SocketsIO saves you $171/month vs Google — that's $2,052/year back in your pocket.
Yes. The JSON structure mirrors the Google Translate v2 response format, so migration is minimal — swap the endpoint and API key.
Yes. Use httpx or aiohttp with the REST endpoint:
import httpx
import asyncio
async def translate_async(text: str, target: str) -> str:
async with httpx.AsyncClient() as client:
response = await client.post(
"https://api.socketsio.com/v1/translate",
json={"q": text, "target": target},
headers={"Authorization": "Bearer YOUR_KEY"}
)
return response.json()["data"]["translations"][0]["translatedText"]
result = asyncio.run(translate_async("Hello async world!", "ja"))
print(result)
Implement exponential backoff:
import time
import requests
from requests.exceptions import HTTPError
def translate_with_retry(text: str, target: str, max_retries: int = 3) -> str:
for attempt in range(max_retries):
try:
response = requests.post(
"https://api.socketsio.com/v1/translate",
json={"q": text, "target": target},
headers={"Authorization": "Bearer YOUR_KEY"},
timeout=10
)
response.raise_for_status()
return response.json()["data"]["translations"][0]["translatedText"]
except HTTPError as e:
if e.response.status_code == 429 and attempt < max_retries - 1:
time.sleep(2 ** attempt) # 1s, 2s, 4s
continue
raise
195 languages — the same coverage as Google Translate. Full list at socketsio.com/docs.
Yes. The free tier includes 100,000 characters/month — enough for most small projects and prototyping.
Same API format as Google Translate v2. 195 languages. No GCP setup required. Start free — no credit card needed.
Get Your Free API Key →Free tier: 100K chars/month · Basic $9/mo · Pro $29/mo