Article
translationnlplanguage-aipythonapidocument-translationformality-controltext-processing
Translate Text and Documents with the DeepL API
Use the DeepL API for high-quality neural machine translation. This guide shows how to get a key, translate text, handle multiple sentences, and control formality using Python. The free tier is perfect for getting started.
beginner15 min5 steps
The play
- Get Your Free API KeySign up for a DeepL API Free plan at the official website. This plan lets you translate up to 500,000 characters per month for free. After registering, navigate to your account page and copy your 'Authentication Key'.
- Translate a Single StringMake a POST request to the `/v2/translate` endpoint. You must include your API key in the headers and provide the text and target language code (e.g., 'ES' for Spanish) in the body. The API URL depends on your plan (free or pro).
- Translate Multiple Texts EfficientlyTo reduce latency, send multiple strings in a single API call instead of making separate requests. The DeepL API accepts a list of strings for the `text` parameter, returning a corresponding list of translations.
- Control Translation FormalityFor languages with formal/informal registers (e.g., German, French, Spanish), you can guide the translation's tone. Set the `formality` parameter to 'less' for informal or 'more' for formal. The default setting is 'default'.
- Translate a DocumentThe DeepL API can translate entire .docx, .pptx, .pdf, and other file types while preserving formatting. Send a multipart/form-data POST request to the `/v2/document` endpoint with the file and target language. The API returns the translated document content.
Starter code
import os
import requests
# 1. Set your DeepL API key as an environment variable
# export DEEPL_API_KEY="your_key_here"
api_key = os.getenv("DEEPL_API_KEY")
if not api_key:
raise ValueError("DEEPL_API_KEY environment variable not set.")
# Use the free API endpoint. For Pro plans, use "https://api.deepl.com"
api_url = "https://api-free.deepl.com/v2/translate"
headers = {
"Authorization": f"DeepL-Auth-Key {api_key}",
}
def translate_text(text, target_lang, formality=None):
"""Translates text using the DeepL API."""
print(f"\n--- Translating to {target_lang} (Formality: {formality or 'default'}) ---")
print(f"Original: {text}")
data = {
"text": text,
"target_lang": target_lang
}
if formality:
data['formality'] = formality
try:
response = requests.post(api_url, headers=headers, data=data)
response.raise_for_status() # Raise an exception for bad status codes
result = response.json()
for i, translation in enumerate(result['translations']):
print(f"Translation: {translation['text']}")
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
# Example 1: Simple translation to French
translate_text("Artificial intelligence will change the world.", "FR")
# Example 2: Batch translation to Spanish
translate_text(["See you later.", "Good morning!"], "ES")
# Example 3: Formality control in German (informal)
translate_text("Can you help me?", "DE", formality="less")
# Example 4: Formality control in German (formal)
translate_text("Can you help me?", "DE", formality="more")