Skip to content

About

Official Rust library for the DeepL language translation API.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

DeepL Rust Library

The official Rust client library for the DeepL API.

The DeepL API 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 Rust library offers a convenient way for applications written in Rust to interact with the DeepL API. We intend to support all API functions with the library except those listed as out of scope below, though support for new features may be added to the library after they're added to the API.

Features

  • Text translation with the full option set — formality, glossaries, context, model selection, and tag handling
  • Document translation — upload, poll, and download, streamed with bounded memory
  • Multilingual glossaries (v3)
  • Write (rephrase and correct), style rules, style profiles, spoken terms, and translation memories (metadata, segments, TMX import and export)
  • Languages and usage lookup
  • Admin API — developer keys and usage analytics, with DeepLAdminClient
  • Free/Pro endpoint auto-detection, automatic retries with exponential backoff, per-attempt timeouts, connection pooling, and typed errors

Realtime voice and the legacy glossary v2 API are out of scope.

Getting an authentication key

To use this library you need a DeepL API authentication key. To get one, create a DeepL account. With a Free account you can translate up to 500,000 characters per month for free. Free API keys carry a :fx suffix; the client auto-detects whether to use the Free (api-free.deepl.com) or Pro (api.deepl.com) endpoint from the key.

Installation

The crate is deepl-rust and is imported in code as deepl. Add it to your Cargo.toml:

[dependencies]
deepl-rust = "2"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }

Minimum supported Rust version (MSRV): 1.86.

TLS backend, chosen by Cargo feature:

  • rustls (default): rustls, verifying certificates against the operating system's trust store, so a TLS-inspecting corporate proxy trusted by the system works. Building it needs a C compiler (for aws-lc-rs), as before.
  • native-tls: the platform TLS stack (OpenSSL on Linux).

To use a non-default backend, turn off the default features, for example deepl-rust = { version = "2", default-features = false, features = ["native-tls"] }. With no TLS feature enabled, requests to https URLs fail.

Usage

Translating text

translate_text translates one text and returns one TextResult; translate_texts translates a list in one request and returns a Vec<TextResult>, one per text in input order.

#[tokio::main]
async fn main() -> Result<(), deepl::Error> {
    let client = deepl::DeepLClient::new("your-key:fx")?; // :fx => Free endpoint

    let result = client.translate_text("Hello, world!", "DE").send().await?;
    println!("{}", result.text);                 // "Hallo, Welt!"
    println!("{}", result.detected_source_lang); // "EN"
    println!("{}", result.billed_characters);    // 13

    let results = client.translate_texts(["Hello", "Goodbye"], "DE").send().await?;
    for r in &results {
        println!("{}", r.text);
    }

    Ok(())
}

TextResult has text, detected_source_lang, billed_characters (the client always asks for it), and model_type_used and tag_handling_version when the API returns them.

Both methods return the same builder; chain options before .send(). DeepLClient is cheap to clone, and a builder owns a clone of it, so a pending call can run on another task: tokio::spawn(client.translate_text("Hello", "DE").send()). For a method without a builder (get_usage, get_target_languages, ...), move a clone of the client into the task.

use deepl::{Formality, TagHandlingMode};

let result = client
    .translate_text("<p>Hello</p>", "DE")
    .source_lang("EN")
    .formality(Formality::PreferMore)
    .tag_handling(TagHandlingMode::Html)
    .glossary(&glossary)          // a glossary ID or a `MultilingualGlossaryInfo`
    .style_rule("style-rule-id")  // a style rule ID or a `StyleRuleInfo`
    .send()
    .await?;
  • source_lang(..): the source language; unset, the API detects it.
  • formality(..), model_type(..), split_sentences(..), context(..), preserve_formatting(..), custom_instructions(..).
  • tag_handling(..), tag_handling_version(..), outline_detection(..), splitting_tags(..), non_splitting_tags(..), ignore_tags(..).
  • glossary(..): a glossary, as its ID or a MultilingualGlossaryInfo. glossary_ids(..): up to five of them. Use one or the other; both need source_lang.
  • style_rule(..): a style rule list, as its ID or a StyleRuleInfo.
  • style_profile(..): a style profile, by ID or as a StyleProfile.
  • translation_memory(..): a translation memory, as its ID or a TranslationMemoryInfo; translation_memory_threshold(..) (0–100) needs it.
  • extra_body_parameters(..): see Configuration.

send() returns Error::Argument without sending a request if a text, target_lang or source_lang is empty, if glossary and glossary_ids are both set or glossary_ids has more than five entries, or if translation_memory_threshold is set without translation_memory or is above 100. It returns Error::Api if the response holds no translation for the text.

Point the client at another server with the builder:

let client = deepl::DeepLClient::builder("your-key").server_url("http://localhost:3000").build()?;

deepl::is_free_account_auth_key(key) tells whether a key is a DeepL API Free key (it ends with :fx).

Translating documents

translate_document uploads a file, waits until the translation is done and writes the result to a new file:

use std::time::Duration;

let status = client
    .translate_document("report.docx", "report.de.docx", "DE")
    .source_lang("EN")
    .timeout(Duration::from_secs(600))
    .send()
    .await?;
println!("billed characters: {:?}", status.billed_characters);

The output file must not exist yet; it is removed if the translation fails or the future is dropped before it finishes. Every failure, except a missing input file (Error::Argument), is an Error::DocumentTranslation wrapping the cause. Once the document is uploaded, the error carries its DocumentHandle, so you can resume without uploading (and paying for) it again.

The steps are also available one by one:

use std::time::Duration;

let handle = client
    .translate_document_upload("report.docx", "DE")
    .send()
    .await?;
let status = client.translate_document_get_status(&handle).await?;
println!("{} ok={} done={}", status.status, status.ok(), status.done());
client
    .translate_document_wait_until_done(&handle)
    .timeout(Duration::from_secs(600))
    .send()
    .await?;
client.translate_document_download(&handle, "report.de.docx").await?;
  • translate_document_upload(..) returns a DocumentHandle. It is retried only on HTTP 429 and on failures before the upload was sent. To resume from a stored ID and key, build one with DocumentHandle::new(document_id, document_key).
  • translate_document_get_status(..) returns a DocumentStatus: document_id, status, and seconds_remaining, billed_characters and error_message when the API sends them. ok() is false once the translation failed; done() is true once it succeeded.
  • translate_document_wait_until_done(..) checks the status every 5 s until the translation is done and returns the final status. A failed translation is Error::Api with the API's message. timeout(..) limits the wait (default: no limit; zero checks once); when it expires the call returns Error::Api, and it never runs past it.
  • translate_document_download(..) streams the result to a new file. HTTP 503 means the translation is not done: it is retried like any 5xx, then returned as Error::DocumentNotReady. A download cut off mid-body is retried from the start. The file is removed if the download fails or the future is dropped.

Options of translate_document and translate_document_upload:

  • source_lang(..): the source language; unset, the API detects it. Required with a glossary.
  • formality(..).
  • glossary(..): a glossary, as its ID or a MultilingualGlossaryInfo. glossary_ids(..): up to five of them. Use one or the other.
  • style_rule(..), style_profile(..), translation_memory(..) and translation_memory_threshold(..), as for text translation.
  • filename(..): the file name sent with the upload; the API reads the format from its extension. Default: the input's file name.
  • output_format(..): the file extension of the output format, e.g. pdf.
  • enable_watermark(..): add a watermark to the translated document.
  • extra_body_parameters(..): see Configuration. In the multipart upload a null value removes the field, lists are comma-joined.
  • timeout(..) (translate_document only): limits the wait between upload and download.

send() returns Error::Argument without sending a request if the input file does not exist, target_lang or source_lang is empty, glossary and glossary_ids are both set or glossary_ids has more than five entries, a glossary is set without source_lang, or translation_memory_threshold is set without translation_memory or is above 100. Error::Io reports an input that cannot be read or an output that cannot be created.

Languages and usage

use deepl::{LanguageInclude, LanguageResourceName};

let targets = client.get_target_languages().await?;
for lang in &targets {
    // supports_formality is Some(..) on target languages, None on source languages
    println!("{} ({}) formality={:?}", lang.code, lang.name, lang.supports_formality);
}

let pairs = client.get_glossary_languages().await?; // e.g. DE -> EN

let resources = client.get_language_resources().await?;
for resource in &resources {
    println!("{}: {:?}", resource.name, resource.features.keys());
}

let write_langs = client
    .get_languages_for_resource(LanguageResourceName::Write)
    .include([LanguageInclude::Beta])
    .send()
    .await?;

let usage = client.get_usage().await?;
if let Some(character) = &usage.character {
    println!("characters: {} of {}", character.count, character.limit);
}
if usage.any_character_limit_reached() {
    eprintln!("a character limit has been reached this billing period");
}
  • get_source_languages and get_target_languages return the languages for text translation as Language, with codes in upper case ("EN-GB"). supports_formality is None on source languages.
  • get_glossary_languages returns the source/target pairs usable in a glossary dictionary, codes in upper case.
  • get_language_resources returns each API resource (translate_text, write, …) with its features, keyed by name, and whether a feature needs support from the source or the target language.
  • get_languages_for_resource(resource) returns the languages of one resource as LanguageSupport, with the codes as the API sends them ("en-GB"), their status and features. resource is a LanguageResourceName or any string. Option: include(..), LanguageInclude::Beta and/or LanguageInclude::External (or any string), to include beta languages and features or features that rely on third-party providers. send() returns Error::Argument without sending a request if resource is empty.
  • get_usage returns the usage of the current billing period as Usage: character (the account) and api_key_character (this API key) count characters of translate and write; speech_to_text_minutes and speech_to_speech_minutes count minutes. Each is a UsageDetail with count, limit and limit_reached(), and is None when the account does not have it. products lists the usage per product (UsageProduct), and start_time/end_time bound the billing period (None when the API omits them or sends a value that is not an RFC 3339 time). any_character_limit_reached() is true when character or api_key_character has reached its limit; the speech minutes are not considered.

Improving text (write)

rephrase_text rewrites a text, optionally in a writing style or a tone (the API rejects a request that sets both); correct_text fixes its grammar, spelling and punctuation. Without target_lang the text keeps its language. rephrase_texts and correct_texts take a list and return one WriteResult per text, in input order. send() returns Error::Argument without sending a request for an empty text or an empty target_lang, and Error::Api if the response holds fewer results than texts sent.

use deepl::WritingStyle;

let improved = client
    .rephrase_text("How are you?")
    .target_lang("EN-US")
    .writing_style(WritingStyle::Business) // or .tone(WritingTone::Confident)
    .send()
    .await?;
println!("{}", improved.text);

let corrected = client
    .correct_texts(["How are yuo?", "I has a cat."])
    .send()
    .await?;
for result in &corrected {
    println!("{} ({})", result.text, result.detected_source_language);
}

Glossaries

Glossaries are multilingual: one glossary holds a dictionary per language pair. A dictionary's entries are GlossaryEntries, built from source/target pairs or parsed from TSV with GlossaryEntries::from_tsv; the *_from_csv variants take CSV content (source,target per line) instead.

use deepl::{GlossaryEntries, MultilingualGlossaryDictionaryEntries};

let glossary = client
    .create_multilingual_glossary(
        "My Glossary",
        [MultilingualGlossaryDictionaryEntries::new("en", "de", [("Hello", "Guten Tag")])],
    )
    .send()
    .await?;

// Merge entries into a dictionary (created if missing), or replace them.
let entries = GlossaryEntries::from_tsv("Goodbye\tTschüss")?;
client
    .update_multilingual_glossary_dictionary(
        &glossary,
        MultilingualGlossaryDictionaryEntries::new("en", "de", entries),
    )
    .send()
    .await?;
client
    .replace_multilingual_glossary_dictionary_from_csv(&glossary, "en", "fr", "Hello,Bonjour")
    .send()
    .await?;

let dictionary = client
    .get_multilingual_glossary_dictionary_entries(&glossary, "en", "de")
    .await?;
for (source, target) in dictionary.entries.iter() {
    println!("{source} -> {target}");
}

client.delete_multilingual_glossary(&glossary).await?;

Methods that address a glossary take its ID or a MultilingualGlossaryInfo.

Method Returns
create_multilingual_glossary(name, dictionaries) MultilingualGlossaryInfo
create_multilingual_glossary_from_csv(name, source_lang, target_lang, csv) MultilingualGlossaryInfo
list_multilingual_glossaries() Vec<MultilingualGlossaryInfo>
get_multilingual_glossary(glossary) MultilingualGlossaryInfo
update_multilingual_glossary(glossary) with name(..) and dictionaries(..); only what is set is sent MultilingualGlossaryInfo
update_multilingual_glossary_name(glossary, name) MultilingualGlossaryInfo
update_multilingual_glossary_dictionary(glossary, dictionary): merges the entries MultilingualGlossaryInfo
update_multilingual_glossary_dictionary_from_csv(glossary, source_lang, target_lang, csv) MultilingualGlossaryInfo
replace_multilingual_glossary_dictionary(glossary, dictionary): replaces the entries MultilingualGlossaryDictionaryInfo
replace_multilingual_glossary_dictionary_from_csv(glossary, source_lang, target_lang, csv) MultilingualGlossaryDictionaryInfo
get_multilingual_glossary_dictionary_entries(glossary, source_lang, target_lang) MultilingualGlossaryDictionaryEntries; Error::NotFound if the glossary has no such dictionary
delete_multilingual_glossary_dictionary(glossary, source_lang, target_lang) ()
delete_multilingual_glossary(glossary) ()

The create, update and replace methods return builders: finish them with .send().await; each has extra_body_parameters(..).

Each method returns Error::Argument without sending a request for an empty glossary ID, an empty language code, and an invalid term: each term is trimmed, and must then be non-empty and free of control characters (C0, C1, U+2028, U+2029). Beyond that:

  • create_multilingual_glossary: an empty name, no dictionaries, or a dictionary without entries.
  • create_multilingual_glossary_from_csv, update_multilingual_glossary_name: an empty name.
  • update_multilingual_glossary_dictionary, replace_multilingual_glossary_dictionary: a dictionary without entries.
  • update_multilingual_glossary_dictionary_from_csv, replace_multilingual_glossary_dictionary_from_csv: empty CSV content.

update_multilingual_glossary sends a dictionary without entries as given, and create_multilingual_glossary_from_csv sends empty CSV content as given; the API rejects them.

Style rules

A style rule list holds formatting and spelling rules for one language, plus custom instructions in free text. Apply one to a translation with style_rule(..).

use std::collections::BTreeMap;
use deepl::{ConfiguredRules, CustomInstructionInput};

let rules: ConfiguredRules = BTreeMap::from([(
    "dates_and_times".to_string(),
    BTreeMap::from([("calendar_era".to_string(), "use_bc_and_ad".to_string())]),
)]);
let style_rule = client
    .create_style_rule("My rules", "en")
    .configured_rules(rules)
    .custom_instructions([CustomInstructionInput::new("Tone", "Use a formal tone")])
    .send()
    .await?;

let instruction = client
    .create_style_rule_custom_instruction(&style_rule, "Units", "Use SI units")
    .source_language("de")
    .send()
    .await?;

let page = client.get_all_style_rules().detailed(true).send().await?;

client.delete_style_rule_custom_instruction(&style_rule, &instruction).await?;
client.delete_style_rule(&style_rule).await?;

Methods take the style rule list as its ID or a StyleRuleInfo, and the custom instruction as its ID or a CustomInstruction.

Method Returns
get_all_style_rules() with page(..), page_size(..) and detailed(..); one page, by default page 0 with 10 lists Vec<StyleRuleInfo>
create_style_rule(name, language) with configured_rules(..) and custom_instructions(..) StyleRuleInfo
get_style_rule(style_rule) StyleRuleInfo
update_style_rule_name(style_rule, name) StyleRuleInfo
update_style_rule_configured_rules(style_rule, configured_rules): replaces all configured rules StyleRuleInfo
delete_style_rule(style_rule) ()
create_style_rule_custom_instruction(style_rule, label, prompt) with source_language(..) CustomInstruction
get_style_rule_custom_instruction(style_rule, instruction) CustomInstruction
update_style_rule_custom_instruction(style_rule, instruction, label, prompt) with source_language(..) CustomInstruction
delete_style_rule_custom_instruction(style_rule, instruction) ()

get_all_style_rules and the create and update methods return builders: finish them with .send().await; the create and update methods have extra_body_parameters(..). update_style_rule_configured_rules sends the rules map itself as the body, so its extra parameters become further keys of that map. configured_rules and custom_instructions of a StyleRuleInfo are None in a list fetched without detailed(true).

Each method returns Error::Argument without sending a request for an empty style rule ID or instruction ID, an empty name, language, label or prompt, and a source_language that is an empty string.

Style profiles

A style profile links glossaries, style rule lists and translation memories under one name. Apply one to a translation with style_profile(..).

let profile = client
    .create_style_profile("Legal, German")
    .description("Contract wording for the German market")
    .industry("Legal")
    .glossary_ids([&glossary])
    .style_rule_ids([&style_rule])
    .glossary_priority_order_enabled(true)
    .send()
    .await?;

let result = client
    .translate_text("Hello", "DE")
    .style_profile(&profile)
    .send()
    .await?;

let profile = client
    .update_style_profile(&profile)
    .description("") // clears the description
    .style_rule_ids(Vec::<&str>::new()) // unlinks all style rule lists
    .send()
    .await?;

client.delete_style_profile(&profile).await?;

Methods take the style profile as its ID or a StyleProfile.

Method Returns
list_style_profiles() with page(..) and page_size(..); one page, newest first, by default page 0 with 10 profiles Vec<StyleProfile>
create_style_profile(name) with the options below StyleProfile
get_style_profile(style_profile) StyleProfile
update_style_profile(style_profile) with name(..) and the options below; sends only the fields set, {} if none StyleProfile
delete_style_profile(style_profile); the linked resources are kept ()

Options of create_style_profile and update_style_profile:

  • description(..), industry(..): free text; in an update an empty string clears it.
  • glossary_ids(..): glossaries to link, as IDs or MultilingualGlossaryInfos, highest priority first.
  • style_rule_ids(..): style rule lists, as IDs or StyleRuleInfos.
  • translation_memory_ids(..): translation memories, as IDs or TranslationMemoryInfos.
  • glossary_priority_order_enabled(..): whether the order of the glossary IDs sets their priority.
  • extra_body_parameters(..).

An ID list in an update replaces the linked list of that kind in full; an empty list unlinks all of them. List elements are sent as given; the API rejects IDs it cannot use. The create request is retried only when it was not sent, so a retry never creates a second profile.

get_style_profile, update_style_profile and delete_style_profile return Error::Argument without sending a request for an empty style profile ID.

Spoken terms

A spoken terms collection holds term lists, one per language, that improve how speech recognition transcribes those terms. A term list is a SpokenTermsEntries: a language code and its terms.

use deepl::SpokenTermsEntries;

let spoken_terms = client
    .create_spoken_terms(
        "Product names",
        [SpokenTermsEntries::new("en", ["DeepL", "webhook"])],
    )
    .send()
    .await?;

// Merge terms into a list (created if missing), or replace the list.
client
    .update_spoken_terms(&spoken_terms)
    .term_lists([SpokenTermsEntries::new("en", ["endpoint"])])
    .send()
    .await?;
client
    .replace_spoken_terms_list(&spoken_terms, SpokenTermsEntries::new("de", ["Schnittstelle"]))
    .send()
    .await?;

let entries = client.get_spoken_terms_entries(&spoken_terms, "en").await?;
for term in &entries.entries {
    println!("{term}");
}

client.delete_spoken_terms(&spoken_terms).await?;

Methods take the collection as its ID or a SpokenTerms.

Method Returns
create_spoken_terms(name, term_lists) SpokenTerms
list_spoken_terms() Vec<SpokenTerms>
get_spoken_terms(spoken_terms) SpokenTerms
update_spoken_terms(spoken_terms) with name(..) and term_lists(..): merges the terms; sends only the fields set, {} if none SpokenTerms
get_spoken_terms_entries(spoken_terms, lang) SpokenTermsEntries
replace_spoken_terms_list(spoken_terms, entries): replaces the terms of one language, or adds the list SpokenTermsList
delete_spoken_terms_list(spoken_terms, lang) ()
delete_spoken_terms(spoken_terms) ()

The create, update and replace methods return builders: finish them with .send().await; each has extra_body_parameters(..). The create request is retried only when it was not sent, so a retry never creates a second collection.

Each method returns Error::Argument without sending a request for an empty spoken terms ID, an empty language code, and an invalid term: each term is trimmed, and must then be non-empty and free of control characters (C0, C1, U+2028, U+2029). The trimmed terms are sent.

Translation memories

A translation memory stores source segments with their translations; pass one to translate_text(..).translation_memory(..). A translation memory is created by importing a TMX file and read back by exporting it, both as background jobs. The file helpers run a whole job in one call:

use std::time::Duration;

// Import: create the job, upload the file, wait until the job completes.
let job = client
    .import_translation_memory_from_filepath("legal.tmx")
    .display_name("Legal")
    .timeout(Duration::from_secs(300))
    .send()
    .await?;
let id = job.result().and_then(|r| r.translation_memory_id.clone());

// Export: create the job, wait until it completes, download the file.
client
    .export_translation_memory_to_filepath("a74d88fb-ed2a-4943-a664-a4512398b994", "legal-export.tmx")
    .send()
    .await?;

The other calls:

use std::time::Duration;

let tm = client.get_translation_memory("a74d88fb-ed2a-4943-a664-a4512398b994").await?;
println!("{}: {} segments", tm.name, tm.segment_count);

// Segments come in cursor pages.
let mut cursor = None;
loop {
    let mut request = client.list_translation_memory_segments(&tm).page_size(100);
    if let Some(c) = cursor {
        request = request.page_cursor(c);
    }
    let page = request.send().await?;
    for segment in &page.segments {
        println!("{}", segment.source_text);
    }
    match page.next_page_cursor {
        Some(next) => cursor = Some(next),
        None => break,
    }
}

// Export step by step: create the job, wait for it, download the file.
let export = client.create_translation_memory_export(&tm).await?;
let job = client
    .wait_until_translation_memory_job_done(export.job_id.as_str())
    .send()
    .await?;
client.download_translation_memory_export(&job, "legal-export.tmx").await?;

// Import step by step: create the job, upload the file, wait for it.
// `deepl::Error` does not convert from `std::io::Error`: read the file in a
// function with your own error type (`Box<dyn std::error::Error>`, `anyhow`).
let content = std::fs::read("legal.tmx")?;
let import = client
    .create_translation_memory_import("legal.tmx", content.len() as u64)
    .send()
    .await?;
client.upload_translation_memory_file(&import, content).send().await?;
let job = client
    .wait_until_translation_memory_job_done(import.job_id.as_str())
    .timeout(Duration::from_secs(300))
    .send()
    .await?;

The translation_memory_id in the result of a completed import is the new translation memory. The API notices an upload with a delay, so an import job reports awaiting_input for a while after the upload.

Methods take the translation memory as its ID or a TranslationMemoryInfo, and the job as its ID or a TranslationMemoryJob.

Method Returns
list_translation_memories() with page(..) (0-based) and page_size(..); the API defaults to page 0, 10 items Vec<TranslationMemoryInfo>
get_translation_memory(translation_memory) TranslationMemoryInfo
delete_translation_memory(translation_memory) ()
list_translation_memory_segments(translation_memory) with page_size(..), page_cursor(..), filter_text(..) and filter_case_sensitive(..) TranslationMemorySegments
create_translation_memory_import(file_name, content_length) with content_type(..) (the API defaults to application/xml) and display_name(..) TranslationMemoryImport
create_translation_memory_export(translation_memory) TranslationMemoryExport
get_translation_memory_job(job) TranslationMemoryJob
upload_translation_memory_file(translation_memory_import, content) with content_type(..) (default application/xml); the import is a TranslationMemoryImport or its upload URL ()
wait_until_translation_memory_job_done(job) with timeout(..) the completed TranslationMemoryJob
download_translation_memory_export(&job, output) ()
import_translation_memory_from_filepath(input) with display_name(..), content_type(..), timeout(..) and extra_body_parameters(..) the completed TranslationMemoryJob
export_translation_memory_to_filepath(translation_memory, output) with timeout(..) the completed TranslationMemoryJob

The list methods, create_translation_memory_import, the upload, the wait and the file helpers return builders: finish them with .send().await. The import and export requests are retried only when they were not sent, so a retry never creates a second job. TranslationMemoryExport::reused_existing is true when the API reused a recent export of the same translation memory instead of starting a new one.

The waits check the job status every 5 s and return the job once it completes. A failed or expired job is Error::Api with the job's error message; timeout(..) limits the wait (default: none; zero checks once) and running out of time is Error::Api too. An import whose file is never uploaded does not finish on its own.

The upload and download URLs are pre-signed storage URLs, not the DeepL API: their requests carry no Authorization header and none of the client's headers(..), only its User-Agent. An error answer from them is always Error::Api with its HTTP status, never Error::NotFound or another DeepL API variant; should_retry() is true for 429 and 5xx. Both are retried like reads. download_translation_memory_export and export_translation_memory_to_filepath create the output file before any request, fail if it exists, and remove it if the download fails; download_translation_memory_export returns Error::Api if the job has no download URL (not completed, or not an export).

import_translation_memory_from_filepath returns Error::Argument if the input file does not exist. Every other failure of the two file helpers is an Error::TranslationMemoryJob { job_id, job, source, .. } wrapping the cause: job_id is set once the job was created and job holds the last status fetched, so the job can be resumed with wait_until_translation_memory_job_done. status() and should_retry() report the cause's.

A TranslationMemoryJob flattens the API's nested objects: display_name, source_content_type and source_content_length for imports, translation_memory_id for exports. result() is its single result and status() that result's TranslationMemoryJobStatus; done() is true once the job completed, ok() is false once it failed or expired.

Each method returns Error::Argument without sending a request for an empty translation memory ID or job ID, create_translation_memory_import for an empty file name or a content_length of 0, and upload_translation_memory_file for an empty upload URL.

Admin API

DeepLAdminClient manages the developer keys of your organization and reads its usage analytics. It needs an admin key, which cannot translate (and an admin key cannot be used with DeepLClient). Build it with DeepLAdminClient::new(admin_key) or DeepLAdminClient::builder(admin_key), which takes the same options as DeepLClient::builder (see Configuration); the default server is always https://api.deepl.com, also for a key ending in :fx.

use deepl::{AdminUsageGroupBy, DeepLAdminClient, DeveloperKeyUsageLimitsUpdate};

let admin = DeepLAdminClient::new("your-admin-key")?;

let key = admin.create_developer_key().label("Production").send().await?;
let keys = admin.list_developer_keys().await?;
let key = admin.rename_developer_key(&key, "Staging").send().await?;
let limits = DeveloperKeyUsageLimitsUpdate::new()
    .characters(Some(500_000))
    .speech_to_text_milliseconds(None); // unlimited
let key = admin.set_developer_key_usage_limits(&key, limits).send().await?;
let key = admin.deactivate_developer_key(&key).send().await?;

let report = admin
    .get_usage_analytics("2026-10-01", "2026-10-31")
    .group_by(AdminUsageGroupBy::Key)
    .send()
    .await?;
for usage in &report.key_usages {
    println!("{}: {}", usage.api_key, usage.usage.total_characters);
}

Developer key methods take the key as its key ID or a DeveloperKey.

Method Returns
create_developer_key() with label(..); without a label the API names the key "DeepL API Key" DeveloperKey
list_developer_keys(); deactivated keys included Vec<DeveloperKey>
deactivate_developer_key(key); deactivation is permanent DeveloperKey
rename_developer_key(key, label) DeveloperKey
set_developer_key_usage_limits(key, limits) DeveloperKey
get_usage_analytics(start_date, end_date) with group_by(..) (Key or KeyAndDay) AdminUsageReport
get_custom_tag_usage_analytics(start_date, end_date) with aggregate_by(..) (Period or Day) and page(..) CustomTagUsageReport
get_language_pair_usage_analytics(start_date, end_date) with group_by(..) (Key), aggregate_by(..) and page(..) LanguagePairUsageReport
  • DeveloperKeyUsageLimitsUpdate changes only the limits you set: None is unlimited, Some(0) blocks that usage; a limit you do not set keeps its value. A DeveloperKey's usage_limits read None for unlimited.
  • The report dates take a chrono::NaiveDate, a chrono::DateTime (chrono is re-exported as deepl::chrono) or a YYYY-MM-DD string, and are sent as YYYY-MM-DD. A DateTime is sent as its UTC date, so local midnight in UTC+2 (2026-10-20T00:00+02:00) is sent as 2026-10-19. Both days are included. The API reads them as UTC days and limits the range.
  • The custom tag and language pair reports are paginated: pass a report's next_page to page(..) to get the following page; it is None on the last page. The language pair report is empty for accounts without language pair data.
  • The report times (start_date, end_date, usage_date) are UTC midnight of the day, as chrono::DateTime<Utc>.

deactivate_developer_key, rename_developer_key and set_developer_key_usage_limits return Error::Argument without sending a request for an empty key ID; the report methods do so for a date string that is not a valid YYYY-MM-DD date. create_developer_key is retried only when the request was not sent, so a retry never creates a second key.

Enum values

Formality, ModelType, SentenceSplittingMode, TagHandlingMode, TagHandlingVersion, WritingStyle, WritingTone, DocumentStatusCode, TranslationMemoryJobStatus, AdminUsageGroupBy, CustomTagUsageAggregateBy and LanguagePairUsageGroupBy are open: each has an Unknown variant for values this version of the crate does not know. A new value in an API response lands in Unknown instead of failing the call. Option setters take the enum or any string, which is sent as given:

use deepl::{Formality, ModelType};

let result = client
    .translate_text("Hello", "DE")
    .formality(Formality::PreferMore)
    .model_type("quality_optimized") // same as ModelType::QualityOptimized
    .send()
    .await?;
if let Some(ModelType::Unknown(model)) = &result.model_type_used {
    println!("served by a model this crate does not know yet: {model}");
}

An Unknown value cannot be built or matched by its text, because a later version of the crate can add a variant for it. Build one with From<&str> (ModelType::from("next_gen"), which gives the known variant once there is one) and compare values with as_str().

Match on these enums with a wildcard arm (_ => ...): they are #[non_exhaustive], so new variants are not a breaking change.

Result types

The structs the API returns are #[non_exhaustive]: read their public fields, but do not build them with a struct literal, since new API fields are added in minor releases. For the same reason they implement PartialEq but not Eq. In your own tests, build one that implements Deserialize from the API's JSON with serde_json; Deserialize reads the API's JSON only, not a format of the struct's own. The input structs (CustomInstructionInput, SpokenTermsEntries, MultilingualGlossaryDictionaryEntries, DeveloperKeyUsageLimitsUpdate, DocumentHandle) have a new constructor, and so do Language and GlossaryLanguagePair, which do not implement Deserialize.

Errors

All fallible operations return Result<T, deepl::Error>. Every error from an API response keeps the API's error message. Error::status() returns the HTTP status of the failed response, and Error::should_retry() whether repeating the call could succeed. An error raised on a successful response (a body that does not parse, or fewer results than texts sent) has no status: status() is None.

The enum and its struct variants are #[non_exhaustive]: match variants with .. (Error::NotFound { message, .. }) and add a wildcard arm. Error::Connection, Error::Io and the two wrapping variants return their cause from std::error::Error::source() and do not repeat it in their own message: {e} prints document translation failed or connection failure. To print the whole chain, use an error reporter ({:#} with anyhow) or walk source(). The source of Error::Connection can be printed and walked, but its concrete type can change in a minor release, so downcasting it is not supported.

Variant Meaning
Error::Authorization { status, message, .. } 401 or 403: the auth key is invalid or not allowed
Error::NotFound { message, .. } 404
Error::TooManyRequests { message, .. } 429, after all retries
Error::QuotaExceeded { message, .. } 456: character or document quota exceeded
Error::Api { status, message, should_retry, .. } 400, any other status, a successful response that does not parse or lacks results (status: None), or a failure the API reports in a response body (a failed document translation or translation memory job)
Error::Connection { message, should_retry, source, .. } no HTTP response: DNS, connect, TLS, proxy, timeout, reset
Error::Argument { message, .. } an invalid argument, raised before any request
Error::Io { source, .. } local file read/write failure (document and translation memory file APIs)
Error::DocumentNotReady { message, .. } 503 on a document download: the translation is not done
Error::DocumentTranslation { handle, source, .. } any failure of translate_document; the handle is kept once the document was uploaded
Error::TranslationMemoryJob { job_id, job, source, .. } any failure of import_translation_memory_from_filepath (except a missing input file) or export_translation_memory_to_filepath; the job ID is kept once the job was created

Configuration

DeepLClient::new(key) uses the defaults; DeepLClient::builder(key) sets the options. Both return Err(Error::Argument) for an empty key (the key is trimmed), a server_url or proxy that is not an absolute http/https URL with a host, or an invalid header.

use std::time::Duration;

let client = deepl::DeepLClient::builder("your-key:fx")
    .server_url("https://api-free.deepl.com")
    .headers([("X-My-Header", "1")])
    .max_retries(5)
    .timeout(Duration::from_secs(10))
    .proxy("http://proxy.example.com:8080")
    .send_platform_info(true)
    .app_info("my-app", "1.2.3")
    .build()?;
  • server_url(..): the API base URL; a path prefix in it is kept. Default: https://api-free.deepl.com for a key ending in :fx, else https://api.deepl.com.
  • headers(..): extra headers sent with every request. A header the client also sets is replaced (case-insensitive), Authorization and User-Agent included; Content-Type, Content-Length, Transfer-Encoding and Host keep the client's value.
  • max_retries(..): retries after the first attempt, default 5.
  • timeout(..): timeout of each attempt, connection setup included, default 10 s. An attempt may run until the retry backoff for it ends, if that is later. A document download restarts the timer with each chunk received. A document upload is timed from the last chunk the connection takes, plus the time the send buffers (up to about 4.5 MiB) need to drain at 16 KiB/s: uploads over links slower than that can time out, and an upload the server stops reading fails after at most timeout plus about 5 minutes.
  • proxy(..): an http or https proxy URL.
  • send_platform_info(..): the User-Agent is deepl-rust/<version>, followed by (<os> <arch>) rustc/<version> unless this is false.
  • app_info(name, version): appends <name>/<version> to the User-Agent.
  • danger_accept_invalid_certs(true): disables TLS certificate verification (testing only).
  • sleeper(..): replaces the wait between retries and polls (for tests).

Request builders whose method sends a JSON or form body also take extra_body_parameters(..): fields added to the body last, replacing a field the client sets, sent as given (null included). These are translate_text, translate_texts, translate_document, translate_document_upload, rephrase_text, rephrase_texts, correct_text, correct_texts, the create, update and replace methods of glossaries, style rules (custom instructions included), style profiles and spoken terms, create_translation_memory_import, import_translation_memory_from_filepath, and the DeepLAdminClient methods create_developer_key, deactivate_developer_key, rename_developer_key and set_developer_key_usage_limits.

Retries

Requests are retried on HTTP 429, any 5xx, and transient network failures (DNS, refused or reset connections, timeouts, unreachable hosts). TLS errors and error answers from a proxy are never retried. The first wait is 1 s; each next one is 1.6 times the previous, at most 120 s, with ±23 % jitter. Retry-After headers are ignored.

Calls that create a resource (create_multilingual_glossary, create_multilingual_glossary_from_csv, create_style_rule, create_style_rule_custom_instruction, create_style_profile, create_spoken_terms, translate_document_upload, create_translation_memory_import, create_translation_memory_export, the file helpers' import and export requests, and create_developer_key) are retried only when the request was not sent: on HTTP 429 and on failures before the request was written (including a proxy that closes the connection before answering). For these calls should_retry() is false for a 5xx answer or a failure after sending, except for a response body cut off mid-read.

Limits

  • Error messages taken from API responses are cut to 500 characters.

Issues

If you experience problems, or would like to request a new feature, please open an issue.

Development

cargo build
cargo test --all-targets   # offline tests; the real-API tests skip without a key
DEEPL_AUTH_KEY=your-key cargo test --test live   # real-API tests; DEEPL_SERVER_URL overrides the server
DEEPL_ADMIN_KEY=your-admin-key cargo test --test live admin   # Admin API real-API tests
cargo fmt --all -- --check
cargo clippy --all-targets -- -D warnings

The examples/ directory has runnable programs for text translation, document translation, glossaries and text improvement, e.g. DEEPL_AUTH_KEY=your-key cargo run --example translate.

This project follows TDD, Conventional Commits, and Keep a Changelog. See CONTRIBUTING.md.

License

MIT.

About

Official Rust library for the DeepL language translation API.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages