Translate Text Programmatically: Python, Node.js, and cURL
Working code examples for translating text using Python, Node.js, and cURL with multiple translation APIs including Google, DeepL, and auto18n.
You need to translate text in your app. Here are working code examples for every major translation API, in Python, Node.js, and cURL. Copy, paste, and adapt.
Google Cloud Translation (v2)
cURL
curl -X POST \
"https://translation.googleapis.com/language/translate/v2" \
-H "Content-Type: application/json" \
-d '{
"q": "Hello, how are you?",
"target": "es",
"key": "YOUR_GOOGLE_API_KEY"
}'
Response:
{
"data": {
"translations": [
{
"translatedText": "Hola, \u00bfc\u00f3mo est\u00e1s?",
"detectedSourceLanguage": "en"
}
]
}
}
Python
from google.cloud import translate_v2 as translate
client = translate.Client()
result = client.translate(
"Hello, how are you?",
target_language="es"
)
print(result["translatedText"])
# Hola, cómo estás?
Requires pip install google-cloud-translate and GOOGLE_APPLICATION_CREDENTIALS env var pointing to your service account JSON.
Node.js
const { Translate } = require("@google-cloud/translate").v2;
const translate = new Translate();
async function main() {
const [translation] = await translate.translate("Hello, how are you?", "es");
console.log(translation);
// Hola, cómo estás?
}
main();
Requires npm install @google-cloud/translate and the same credentials env var.
DeepL
cURL
curl -X POST "https://api.deepl.com/v2/translate" \
-H "Authorization: DeepL-Auth-Key YOUR_KEY" \
-H "Content-Type: application/json" \
-d '{
"text": ["Hello, how are you?"],
"target_lang": "ES"
}'
Response:
{
"translations": [
{
"detected_source_language": "EN",
"text": "Hola, ¿cómo estás?"
}
]
}
Note: DeepL uses uppercase language codes (ES, not es).
Python
import deepl
translator = deepl.Translator("YOUR_AUTH_KEY")
result = translator.translate_text(
"Hello, how are you?",
target_lang="ES"
)
print(result.text)
# Hola, ¿cómo estás?
Requires pip install deepl.
Node.js
const deepl = require("deepl-node");
const translator = new deepl.Translator("YOUR_AUTH_KEY");
async function main() {
const result = await translator.translateText(
"Hello, how are you?",
null, // auto-detect source language
"es",
);
console.log(result.text);
// Hola, ¿cómo estás?
}
main();
Requires npm install deepl-node.
auto18n
cURL
curl -X POST "https://api.auto18n.com/translate" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"text": "Hello, how are you?",
"to": "es"
}'
Response:
{
"translation": "Hola, ¿cómo estás?",
"from": "en",
"cached": false
}
Python
import requests
response = requests.post(
"https://api.auto18n.com/translate",
headers={"Authorization": "Bearer YOUR_API_KEY"},
json={
"text": "Hello, how are you?",
"to": "es"
}
)
data = response.json()
print(data["translation"])
# Hola, ¿cómo estás?
Node.js
async function translate(text, targetLang) {
const response = await fetch("https://api.auto18n.com/translate", {
method: "POST",
headers: {
Authorization: "Bearer " + process.env.AUTO18N_API_KEY,
"Content-Type": "application/json",
},
body: JSON.stringify({ text, to: targetLang }),
});
const data = await response.json();
return data.translation;
}
const result = await translate("Hello, how are you?", "es");
console.log(result);
// Hola, ¿cómo estás?
No SDK needed — just fetch.
Batch Translation
Translating one string at a time is fine for prototyping. In production, you want batch translation to reduce HTTP overhead.
Google (batch)
texts = ["Hello", "Goodbye", "Thank you"]
results = client.translate(texts, target_language="es")
for r in results:
print(r["translatedText"])
# Hola
# Adiós
# Gracias
DeepL (batch)
texts = ["Hello", "Goodbye", "Thank you"]
results = translator.translate_text(texts, target_lang="ES")
for r in results:
print(r.text)
auto18n (batch)
curl -X POST "https://api.auto18n.com/translate/batch" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"texts": ["Hello", "Goodbye", "Thank you"],
"to": "es"
}'
Error Handling
Every API can fail. Rate limits, network issues, invalid input. Here's a robust wrapper:
import time
import requests
def translate_with_retry(
text: str,
target_lang: str,
max_retries: int = 3
) -> str:
for attempt in range(max_retries):
try:
response = requests.post(
"https://api.auto18n.com/translate",
headers={"Authorization": f"Bearer {API_KEY}"},
json={"text": text, "to": target_lang},
timeout=10,
)
if response.status_code == 429:
retry_after = int(
response.headers.get("Retry-After", 5)
)
time.sleep(retry_after)
continue
response.raise_for_status()
return response.json()["translation"]
except requests.exceptions.Timeout:
if attempt == max_retries - 1:
raise
time.sleep(2 ** attempt)
raise Exception("Translation failed after retries")
async function translateWithRetry(text, targetLang, maxRetries = 3) {
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
const response = await fetch("https://api.auto18n.com/translate", {
method: "POST",
headers: {
Authorization: Bearer ${API_KEY},
"Content-Type": "application/json",
},
body: JSON.stringify({ text, to: targetLang }),
signal: AbortSignal.timeout(10000),
});
if (response.status === 429) {
const retryAfter = parseInt(response.headers.get("Retry-After") ?? "5");
await new Promise((r) => setTimeout(r, retryAfter * 1000));
continue;
}
if (!response.ok) {
throw new Error(HTTP ${response.status});
}
const data = await response.json();
return data.translation;
} catch (err) {
if (attempt === maxRetries - 1) throw err;
await new Promise((r) => setTimeout(r, 2 * attempt 1000));
}
}
}
Language Detection
Sometimes you don't know the source language. All three major APIs support auto-detection:
# Google — auto-detects by default
result = client.translate("Bonjour le monde", target_language="en")
print(result["detectedSourceLanguage"]) # "fr"
# DeepL — pass None as source_lang
result = translator.translate_text("Bonjour le monde", target_lang="EN")
print(result.detected_source_lang) # "FR"
# auto18n — just omit the "from" field
response = requests.post(
"https://api.auto18n.com/translate",
headers={"Authorization": f"Bearer {API_KEY}"},
json={"text": "Bonjour le monde", "to": "en"}
)
print(response.json()["from"]) # "fr"
Which API to Pick
If you just need to translate text and want the simplest setup: auto18n. One API key, one endpoint, built-in caching.
If you need 100+ languages: Google Cloud Translation. Widest coverage.
If European language quality is critical: DeepL. Best NMT for European pairs.
If cost is king: Amazon Translate at $15/1M chars or Microsoft Translator at $10/1M chars (not covered in detail here, but the same patterns apply — they all accept text and return text).
The code patterns above work with any translation API. The request/response format varies, but the logic (retry, batch, error handling) is universal.