The [DeepL API][api-docs] is a language AI API that allows other computer programs to send texts and documents to DeepL's servers and receive high-quality translations and improvements to the text. This opens a whole universe of opportunities for developers: any translation product you can imagine can now be built on top of DeepL's best-in-class translation technology.
The DeepL Python library offers a convenient way for applications written in Python to interact with the DeepL API. We intend to support all API functions with the library, though support for new features may be added to the library after they’re added to the API.
To use the DeepL Python Library, you'll need an API authentication key. To get a key, [please create an account here][create-account]. With a DeepL API Free account you can consume up to 500,000 characters/month for free.
The library can be installed from [PyPI][pypi-project] using pip:
pip install --upgrade deepl
If you need to modify this source code, install the dependencies using poetry:
poetry install
On Ubuntu 22.04 an error might occur: ModuleNotFoundError: No module named
'cachecontrol'. Use the workaround sudo apt install python3-cachecontrol as
explained in this [bug report][bug-report-ubuntu-2204].
The library is tested with Python versions 3.9 to 3.13.
The requests module is used to perform HTTP requests; the minimum is version
2.32.4.
We periodically drop support for older Python versions that have reached official end-of-life. You can find the Python versions and support timelines [here][python-version-list].
Import the package and construct a DeepLClient. The first argument is a string
containing your API authentication key as found in your
[DeepL Pro Account][pro-account].
Be careful not to expose your key, for example when sharing source code.
import deepl
auth_key = "f63c02c5-f056-..." # Replace with your key
deepl_client = deepl.DeepLClient(auth_key)
result = deepl_client.translate_text("Hello, world!", target_lang="FR")
print(result.text) # "Bonjour, le monde !"
This example is for demonstration purposes only. In production code, the authentication key should not be hard-coded, but instead fetched from a configuration file or environment variable.
DeepLClient accepts additional options, see Configuration
for more information.
To translate text, call translate_text(). The first argument is a string
containing the text you want to translate, or a list of strings if you want to
translate multiple texts.
source_lang and target_lang specify the source and target language codes
respectively. The source_lang is optional, if it is unspecified the source
language will be auto-detected.
Language codes are case-insensitive strings according to ISO 639-1, for
example 'DE', 'FR', 'JA''. Some target languages also include the regional
variant according to ISO 3166-1, for example 'EN-US', or 'PT-BR'. The full
list of supported languages is in the
[API documentation][api-docs-lang-list].
There are additional optional arguments to control translation, see Text translation options below.
translate_text() returns a TextResult, or a list of TextResults
corresponding to your input text(s). TextResult has the following properties:
- text is the translated text,
- detected_source_lang is the detected source language code,
- billed_characters is the number of characters billed for the translation.
- model_type_used indicates the translation model used, but is None unless
the model_type option is specified.
# Translate text into a target language, in this case, French:
result = deepl_client.translate_text("Hello, world!", target_lang="FR")
print(result.text) # "Bonjour, le monde !"
# Translate multiple texts into British English
result = deepl_client.translate_text(
["お元気ですか?", "¿Cómo estás?"],
target_lang="EN-GB",
)
print(result[0].text) # "How are you?"
print(result[0].detected_source_lang) # "JA" the language code for Japanese
print(result[0].billed_characters) # 7 - the number of characters in the source text "お元気ですか?"
print(result[1].text) # "How are you?"
print(result[1].detected_source_lang) # "ES" the language code for Spanish
print(result[1].billed_characters) # 12 - the number of characters in the source text "¿Cómo estás?"
# Translate into German with less and more Formality:
print(
deepl_client.translate_text(
"How are you?", target_lang="DE", formality="less"
)
) # 'Wie geht es dir?'
print(
deepl_client.translate_text(
"How are you?", target_lang="DE", formality="more"
)
) # 'Wie geht es Ihnen?'
In addition to the input text(s) argument, the available translate_text()
arguments are:
source_lang: Specifies the source language code, but may be omitted to
auto-detect the source language.target_lang: Required. Specifies the target language code.split_sentences: specify how input text should be split into sentences,
default: 'on'.'on'' (SplitSentences.ON): input text will be split into sentences
using both newlines and punctuation.'off' (SplitSentences.OFF): input text will not be split into
sentences. Use this for applications where each input text contains only
one sentence.'nonewlines' (SplitSentences.NO_NEWLINES): input text will be split
into sentences using punctuation but not newlines.preserve_formatting: controls automatic-formatting-correction. Set to True
to prevent automatic-correction of formatting, default: False.formality: controls whether translations should lean toward informal or
formal language. This option is only available for some target languages, see
Listing available languages.'less' (Formality.LESS): use informal language.'more' (Formality.MORE): use formal, more polite language.glossary: specifies a glossary to use with translation, either as a string
containing the glossary ID, or a GlossaryInfo as returned by
get_glossary().context: specifies additional context to influence translations, that is not
translated itself. Characters in the context parameter are not counted toward billing.
See the [API documentation][api-docs-context-param] for more information and
example usage.model_type: specifies the type of translation model to use, options are:'quality_optimized' (ModelType.QUALITY_OPTIMIZED): use a translation
model that maximizes translation quality, at the cost of response time.
This option may be unavailable for some language pairs.'prefer_quality_optimized' (ModelType.PREFER_QUALITY_OPTIMIZED): use
the highest-quality translation model for the given language pair.'latency_optimized' (ModelType.LATENCY_OPTIMIZED): use a translation
model that minimizes response time, at the cost of translation quality.tag_handling: type of tags to parse before translation, options are 'html'
and 'xml'.tag_handling_version: specifies which version of the tag handling algorithm to
use, options are 'v1' and 'v2'.style_rule: specifies a style rule to use with translation, either as a string
containing the ID of the style rule, or a StyleRuleInfo object.translation_memory: specifies a translation memory to use with translation,
either as a string containing the ID of the translation memory, or a
TranslationMemoryInfo object.translation_memory_threshold: the minimum matching percentage for fuzzy
matches from the translation memory (0-100). We recommend a minimum threshold
of 75%.custom_instructions: an array of instructions to customize the text
translation behavior. Up to 10 custom instructions can be specified, each with
a maximum of 300 characters.
Important: The target language must be de, en, es, fr, it, ja,
ko, zh or any variants of these languages.
Note: Any request with the custom_instructions parameter enabled will use
the quality_optimized model type as the default. Requests combining
custom_instructions and model_type: latency_optimized will be rejected.extra_body_parameters: Dictionary of extra parameters to pass in the body of
the HTTP request. Mostly used by DeepL employees to test functionality, or for
beta programs.The following options are only used if tag_handling is 'xml':
outline_detection: specify False to disable automatic tag detection,
default is True.splitting_tags: list of XML tags that should be used to split text into
sentences. Tags may be specified as an array of strings (['tag1', 'tag2']),
or a comma-separated list of strings ('tag1,tag2'). The default is an empty
list.non_splitting_tags: list of XML tags that should not be used to split text
into sentences. Format and default are the same as for splitting_tags.ignore_tags: list of XML tags that containing content that should not be
translated. Format and default are the same as for splitting_tags.For a detailed explanation of the XML handling options, see the [API documentation][api-docs-xml-handling].
You can use the Write API to improve or rephrase text. This is implemented in
the rephrase_text() method. The first argument is a string containing the text
you want to translate, or a list of strings if you want to translate multiple texts.
target_lang optionally specifies the target language, e.g. when you want to change
the variant of a text (for example, you can send an english text to the write API and
use target_lang to turn it into British or American English). Please note that the
Write API itself does NOT translate. If you wish to translate and improve a text, you
will need to make multiple calls in a chain.
Language codes are the same as for translating text.
Example call:
result = deepl_client.rephrase_text("A rainbouw has seven colours.", target_lang="EN-US")
print(result.text)
Additionally, you can optionally specify a style OR a tone (not both at once) that the
improvement should be in. The following styles are supported (default will be used if
nothing is selected):
academicbusinesscasualdefaultsimpleThe following tones are supported (default will be used if nothing is selected):
confidentdefaultdiplomaticenthusiasticfriendlyYou can also prefix any non-default style or tone with prefer_ (prefer_academic, etc.),
in which case the style/tone will only be applied if the language supports it. If you do not
use prefer_, requests with target_langs or detected languages that do not support
styles and tones will fail. The current list of supported languages can be found in our
[API documentation][api-docs]. We plan to also expose this information via an API endpoint
in the future.
You can use the predefined constants in the library to use a style:
result = deepl_client.rephrase_text(
"A rainbouw has seven colours.", target_lang="EN-US", style=WritingStyle.BUSINESS.value
)
print(result.text)
To translate documents, you may call either translate_document() using file IO
objects, or translate_document_from_filepath() using file paths. For both
functions, the first and second arguments correspond to the input and output
files respectively.
Just as for the translate_text() function, the source_lang and
target_lang arguments specify the source and target language codes.
There are additional optional arguments to control translation, see Document translation options below.
# Translate a formal document from English to German
input_path = "/path/to/Instruction Manual.docx"
output_path = "/path/to/Bedienungsanleitung.docx"
try:
# Using translate_document_from_filepath() with file paths
deepl_client.translate_document_from_filepath(
input_path,
output_path,
target_lang="DE",
formality="more"
)
# Alternatively you can use translate_document() with file IO objects
with open(input_path, "rb") as in_file, open(output_path, "wb") as out_file:
deepl_client.translate_document(
in_file,
out_file,
target_lang="DE",
formality="more"
)
except deepl.DocumentTranslationException as error:
# If an error occurs during document translation after the document was
# already uploaded, a DocumentTranslationException is raised. The
# document_handle property contains the document handle that may be used to
# later retrieve the document from the server, or contact DeepL support.
doc_id = error.document_handle.id
doc_key = error.document_handle.key
print(f"Error after uploading ${error}, id: ${doc_id} key: ${doc_key}")
except deepl.DeepLException as error:
# Errors during upload raise a DeepLException
print(error)
translate_document() and translate_document_from_filepath() are convenience
functions that wrap multiple API calls: uploading, polling status until the
translation is complete, and downloading. If your application needs to execute
these steps individually, y
$ claude mcp add deepl-python \
-- python -m otcore.mcp_server <graph>