Skip to content
DeepLPublic

About

Official Go library for the DeepL language translation API.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

79 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

DeepL Go Library

The official Go 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 Go library offers a convenient way for applications written in Go 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 — one call, or upload, status, wait and a streamed download
  • Multilingual glossaries (v3)
  • Write (rephrase and correct), style rules with custom instructions, style profiles, spoken terms, and translation memories (management, segments, import and export of TMX files)
  • Languages and usage lookup
  • Admin API — developer keys and usage analytics (AdminClient)
  • Free/Pro endpoint auto-detection, automatic retries with exponential backoff, typed errors, and context.Context support throughout
  • Zero third-party dependencies — only the Go standard library

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

go get github.com/DeepL/deepl-go

Minimum supported Go version: 1.23.

Usage

Translating text

package main

import (
	"context"
	"fmt"
	"log"

	deepl "github.com/DeepL/deepl-go"
)

func main() {
	client, err := deepl.New("your-key:fx") // :fx => Free endpoint
	if err != nil {
		log.Fatal(err)
	}

	// "" as the source language lets DeepL detect it; nil means no options.
	result, err := client.TranslateText(context.Background(), "Hello, world!", "", "DE", nil)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(result.Text)               // "Hallo, Welt!"
	fmt.Println(result.DetectedSourceLang) // "EN"
	fmt.Println(result.BilledCharacters)   // 13
}

TranslateText translates one text and returns one TextResult; TranslateTexts takes a []string and returns a []TextResult in the same order. Both take the source language ("" to auto-detect), the target language and an optional *deepl.TranslateTextOptions (nil for none):

results, err := client.TranslateTexts(ctx, []string{"Hello", "World"}, "EN", "DE",
	&deepl.TranslateTextOptions{
		Formality:          deepl.FormalityMore,
		PreserveFormatting: deepl.Ptr(true),
		Glossary:           deepl.GlossaryID(glossaryID), // or a deepl.MultilingualGlossaryInfo
	})

Each TextResult has Text, DetectedSourceLang, BilledCharacters (always set), and ModelTypeUsed and TagHandlingVersion (nil when the API does not return them).

TranslateTextOptions fields (empty strings, nil slices and nil pointers are not sent):

  • Glossary: a glossary, as deepl.GlossaryID("…") or a deepl.MultilingualGlossaryInfo.
  • GlossaryIDs: up to five glossaries, by id or object. Not together with Glossary.
  • StyleRule: a style rule list, as deepl.StyleRuleID("…") or a deepl.StyleRuleInfo.
  • StyleProfile: a style profile, as deepl.StyleProfileID("…") or a deepl.StyleProfile.
  • TranslationMemory: a translation memory, as deepl.TranslationMemoryID("…") or a deepl.TranslationMemoryInfo.
  • TranslationMemoryThreshold: minimum match percentage, 0 to 100 (deepl.Ptr(80)). Requires TranslationMemory.
  • Formality: deepl.FormalityLess, FormalityMore, FormalityPreferLess, FormalityPreferMore or FormalityDefault.
  • SplitSentences: deepl.SentenceSplittingModeAll, SentenceSplittingModeOff or SentenceSplittingModeNoNewlines.
  • PreserveFormatting, OutlineDetection: *bool.
  • Context: text that influences the translation but is not translated.
  • TagHandling: deepl.TagHandlingModeHTML or TagHandlingModeXML.
  • TagHandlingVersion: deepl.TagHandlingVersionV1 or TagHandlingVersionV2.
  • SplittingTags, NonSplittingTags, IgnoreTags: XML tag names.
  • ModelType: deepl.ModelTypeQualityOptimized, ModelTypePreferQualityOptimized or ModelTypeLatencyOptimized.
  • CustomInstructions: instructions that customize the translation.
  • ExtraBodyParameters: extra request body fields, added last; they replace a field with the same key, and a nil value is sent as JSON null.

Enum fields also accept any string, e.g. deepl.Formality("new_value").

An empty text or target language, Glossary together with GlossaryIDs, more than five GlossaryIDs, or a TranslationMemoryThreshold without TranslationMemory or outside 0..100 returns a *deepl.ArgumentError without sending a request. billed_characters is always requested.

Languages and usage

targets, err := client.GetTargetLanguages(ctx) // also GetSourceLanguages
for _, lang := range targets {
	// SupportsFormality is set on target languages, nil on source languages.
	fmt.Printf("%s (%s) formality=%v\n", lang.Code, lang.Name, *lang.SupportsFormality)
}

pairs, err := client.GetGlossaryLanguages(ctx) // source/target pairs usable in glossaries

usage, err := client.GetUsage(ctx)
if usage.AnyCharacterLimitReached() {
	log.Println("a character limit has been reached this billing period")
}
if c := usage.Character; c != nil {
	fmt.Printf("characters: %d of %d\n", c.Count, c.Limit)
}

GetUsage groups the API's count/limit pairs into UsageDetails (Count, Limit, LimitReached()): Character (account-wide), APIKeyCharacter (this API key), SpeechToTextMinutes and SpeechToSpeechMinutes. It also returns the per-product usage (Products) and the billing period (StartTime, EndTime). Every field is nil when the account does not have it; a start or end time that is not an RFC 3339 time is nil too. AnyCharacterLimitReached considers only Character and APIKeyCharacter.

GetSourceLanguages and GetTargetLanguages return upper-case codes (EN, PT-BR), like TextResult.DetectedSourceLang; GetGlossaryLanguages returns codes as the API sends them (en, de).

GetLanguageResources lists the API resources (translate_text, glossary, write, …) and their features, keyed by feature name, each with whether it needs support from the source and/or target language. GetLanguagesForResource returns the languages of one resource, with codes as the API sends them, their status, whether each is usable as source and target, and their features. GetLanguagesForResourceOptions.Include adds beta languages and features (deepl.LanguageIncludeBeta) or ones relying on external providers (deepl.LanguageIncludeExternal). Both resource names and include values accept any string. An empty resource returns an *ArgumentError without sending a request.

resources, err := client.GetLanguageResources(ctx)
for _, r := range resources {
	if f, ok := r.Features["formality"]; ok && f.NeedsTargetSupport {
		fmt.Println(r.Name, "needs a target language that supports formality")
	}
}

langs, err := client.GetLanguagesForResource(ctx, deepl.LanguageResourceNameWrite,
	&deepl.GetLanguagesForResourceOptions{Include: []deepl.LanguageInclude{deepl.LanguageIncludeBeta}})
for _, l := range langs {
	_, tone := l.Features["tone"]
	fmt.Println(l.Code, l.Name, l.Status, l.UsableAsSource, l.UsableAsTarget, tone)
}

Improving text (write)

RephraseText rewrites a text, optionally in a writing style or tone; CorrectText only fixes spelling and grammar. Both take the target language as the second argument ("" keeps the language of the input text) and options as a pointer (nil for none). RephraseTexts and CorrectTexts take a list and return one result per text, in order.

improved, err := client.RephraseText(ctx, "How are you?", "en-US",
	&deepl.RephraseTextOptions{WritingStyle: deepl.WritingStyleBusiness}) // or Tone: deepl.WritingToneConfident
if err != nil {
	log.Fatal(err)
}
fmt.Println(improved.Text, improved.DetectedSourceLanguage, improved.TargetLanguage)

corrected, err := client.CorrectTexts(ctx, []string{"this is a example", "an other one"}, "", nil)
if err != nil {
	log.Fatal(err)
}
fmt.Println(corrected[0].Text, corrected[1].Text)

RephraseTextOptions has WritingStyle, Tone and ExtraBodyParameters; CorrectTextOptions has ExtraBodyParameters. Whether a writing style and a tone can be combined is decided by the API. An empty text is an *ArgumentError (no request is sent), and a response with fewer results than texts sent is an *Error.

Glossaries

Glossaries are multilingual (v3): one glossary holds a dictionary per language pair. Every method that takes a glossary accepts deepl.GlossaryID("…") or a deepl.MultilingualGlossaryInfo.

glossary, err := client.CreateMultilingualGlossary(ctx, "My Glossary",
	[]deepl.MultilingualGlossaryDictionaryEntries{{
		SourceLang: "en",
		TargetLang: "de",
		Entries:    deepl.GlossaryEntries{"Hello": "Guten Tag"},
	}}, nil)

dict, err := client.GetMultilingualGlossaryDictionaryEntries(ctx, glossary, "en", "de")
fmt.Println(dict.Entries["Hello"]) // "Guten Tag"

err = client.DeleteMultilingualGlossary(ctx, glossary)

GlossaryEntries is a map[string]string from source to target term. Entries are sent as TSV: ToTSV() trims each term and returns an *ArgumentError for a term that is empty after trimming or contains a control character (C0, C1, U+2028, U+2029); GlossaryEntriesFromTSV parses TSV (one source<TAB>target pair per line). Every method checks the entries before sending a request.

Methods:

  • CreateMultilingualGlossary(ctx, name, dictionaries, opts) and CreateMultilingualGlossaryFromCSV(ctx, name, sourceLang, targetLang, csv, opts). Like every create, they are retried only on 429 and on failures before the request was sent.
  • ListMultilingualGlossaries(ctx) and GetMultilingualGlossary(ctx, glossary): metadata (GlossaryID, Name, Dictionaries with EntryCount, CreationTime as a time.Time), without entries.
  • UpdateMultilingualGlossary(ctx, glossary, opts): changes the name and merges UpdateMultilingualGlossaryOptions.Dictionaries into the glossary; only the fields set are sent.
  • UpdateMultilingualGlossaryName(ctx, glossary, name, opts).
  • UpdateMultilingualGlossaryDictionary(ctx, glossary, dictionary, opts) and UpdateMultilingualGlossaryDictionaryFromCSV(ctx, glossary, sourceLang, targetLang, csv, opts): merge entries into one dictionary, creating it if missing.
  • ReplaceMultilingualGlossaryDictionary(ctx, glossary, dictionary, opts) and ReplaceMultilingualGlossaryDictionaryFromCSV(ctx, glossary, sourceLang, targetLang, csv, opts): replace one dictionary's entries.
  • GetMultilingualGlossaryDictionaryEntries(ctx, glossary, sourceLang, targetLang): one dictionary's entries; ErrNotFound if it does not exist.
  • DeleteMultilingualGlossaryDictionary(ctx, glossary, sourceLang, targetLang) and DeleteMultilingualGlossary(ctx, glossary).

The options (CreateMultilingualGlossaryOptions, UpdateMultilingualGlossaryOptions, ReplaceMultilingualGlossaryDictionaryOptions, BaseRequestOptions; nil for none) carry ExtraBodyParameters, added to the request body last.

These return an *ArgumentError without sending a request:

  • every method that takes a glossary: a nil glossary or one without an id;
  • every method that takes a language pair, directly or in a dictionary: an empty source or target language;
  • every method that sends GlossaryEntries: an invalid term;
  • CreateMultilingualGlossary, CreateMultilingualGlossaryFromCSV and UpdateMultilingualGlossaryName: an empty name;
  • CreateMultilingualGlossary: no dictionaries;
  • CreateMultilingualGlossary, UpdateMultilingualGlossaryDictionary and ReplaceMultilingualGlossaryDictionary: a dictionary without entries;
  • UpdateMultilingualGlossaryDictionaryFromCSV and ReplaceMultilingualGlossaryDictionaryFromCSV: empty CSV content.

UpdateMultilingualGlossary sends a dictionary without entries as given, and treats an empty Name as unset.

Style rules

A style rule list holds configured rules and custom instructions for one language and is applied with the StyleRule option of TranslateTextOptions and TranslateDocumentOptions. Every method that takes a style rule accepts deepl.StyleRuleID("…") or a deepl.StyleRuleInfo; every method that takes a custom instruction accepts deepl.CustomInstructionID("…") or a deepl.CustomInstruction.

rule, err := client.CreateStyleRule(ctx, "My Style", "de",
	deepl.ConfiguredRules{"punctuation": {"apostrophe": "use_curly_apostrophes"}},
	[]deepl.CustomInstructionInput{{Label: "Tone", Prompt: "Use a warm tone."}}, nil)

instruction, err := client.CreateStyleRuleCustomInstruction(ctx, rule,
	"Currency", "Put currency symbols before the amount.", "en", nil)

res, err := client.TranslateText(ctx, "It costs 100 dollars.", "EN", "DE",
	&deepl.TranslateTextOptions{StyleRule: rule})

err = client.DeleteStyleRule(ctx, rule)

ConfiguredRules is a map[string]map[string]string (category to rule to value, in the API's snake_case), sent and returned as given.

Methods:

  • CreateStyleRule(ctx, name, language, configuredRules, customInstructions, opts): nil configured rules or custom instructions are not sent. Like every create, it is retried only on 429 and on failures before the request was sent.
  • GetAllStyleRules(ctx, opts): one page of style rule lists. GetAllStyleRulesOptions has Page (0-based, API default 0), PageSize (API default 10) and Detailed (include configured rules and custom instructions); all are pointers, nil is not sent.
  • GetStyleRule(ctx, styleRule): one list with its rules and instructions.
  • UpdateStyleRuleName(ctx, styleRule, name, opts).
  • UpdateStyleRuleConfiguredRules(ctx, styleRule, configuredRules, opts): replaces all configured rules; the request body is the map itself.
  • DeleteStyleRule(ctx, styleRule).
  • CreateStyleRuleCustomInstruction(ctx, styleRule, label, prompt, sourceLanguage, opts): returns the new CustomInstruction; retried like a create. sourceLanguage "" is not sent.
  • GetStyleRuleCustomInstruction(ctx, styleRule, instruction).
  • UpdateStyleRuleCustomInstruction(ctx, styleRule, instruction, label, prompt, sourceLanguage, opts): sourceLanguage "" is not sent.
  • DeleteStyleRuleCustomInstruction(ctx, styleRule, instruction).

StyleRuleInfo has StyleID, Name, CreationTime and UpdatedTime (time.Time), Language, Version, and ConfiguredRules and CustomInstructions (nil when the response leaves them out). CustomInstruction.SourceLanguage is a *string, nil when absent.

The options (CreateStyleRuleOptions, UpdateStyleRuleNameOptions, UpdateStyleRuleConfiguredRulesOptions, CreateStyleRuleCustomInstructionOptions, UpdateStyleRuleCustomInstructionOptions; nil for none) carry ExtraBodyParameters, added to the request body last. For UpdateStyleRuleConfiguredRules they become further keys of the configured-rules map.

These return an *ArgumentError without sending a request:

  • every method that takes a style rule: a nil style rule or one without an id;
  • every method that takes a custom instruction: a nil instruction or one without an id;
  • CreateStyleRule: an empty name or language;
  • UpdateStyleRuleName: an empty name;
  • CreateStyleRuleCustomInstruction and UpdateStyleRuleCustomInstruction: an empty label or prompt.

Style profiles

A style profile links glossaries, style rule lists and translation memories under one id and is applied with the StyleProfile option of TranslateTextOptions and TranslateDocumentOptions. Every method that takes a style profile accepts deepl.StyleProfileID("…") or a deepl.StyleProfile.

profile, err := client.CreateStyleProfile(ctx, "Legal, German",
	&deepl.CreateStyleProfileOptions{
		Industry:     deepl.Ptr("Legal"),
		GlossaryIDs:  []deepl.MultilingualGlossaryRef{glossary},
		StyleRuleIDs: []deepl.StyleRuleRef{rule},
	})

res, err := client.TranslateText(ctx, "The parties agree as follows.", "EN", "DE",
	&deepl.TranslateTextOptions{StyleProfile: profile})

profile, err = client.UpdateStyleProfile(ctx, profile,
	&deepl.UpdateStyleProfileOptions{Description: deepl.Ptr("")}) // clears it

err = client.DeleteStyleProfile(ctx, profile)

Methods:

  • ListStyleProfiles(ctx, opts): one page of the style profiles available to the account, newest first, shared ones included. ListStyleProfilesOptions has Page (0-based, API default 0) and PageSize (API default 10, at most 100); both are pointers, nil is not sent.
  • CreateStyleProfile(ctx, name, opts): only name is required. If a linked id cannot be used, the API rejects the request and creates nothing. Like every create, it is retried only on 429 and on failures before the request was sent.
  • GetStyleProfile(ctx, styleProfile).
  • UpdateStyleProfile(ctx, styleProfile, opts): sends only the fields set; with nil options the body is {}.
  • DeleteStyleProfile(ctx, styleProfile): the linked components are not deleted.

CreateStyleProfileOptions has Description and Industry (*string), GlossaryIDs ([]MultilingualGlossaryRef, highest priority first), StyleRuleIDs ([]StyleRuleRef), TranslationMemoryIDs ([]TranslationMemoryRef), GlossaryPriorityOrderEnabled (*bool) and ExtraBodyParameters. nil fields are not sent; "" and an empty non-nil slice are sent as given. List elements are sent as given (a nil element as "") and validated by the API. UpdateStyleProfileOptions has the same fields plus Name ("" leaves it unchanged); there Description or Industry "" clears it, and a non-nil slice replaces the linked components of that kind in full, an empty one unlinks all of them.

StyleProfile has StyleProfileID, Name, Description and Industry (*string, nil when absent), GlossaryIDs, StyleRuleIDs, TranslationMemoryIDs ([]string), GlossaryPriorityOrderEnabled, and CreationTime and UpdatedTime (time.Time).

GetStyleProfile, UpdateStyleProfile and DeleteStyleProfile return an *ArgumentError without sending a request for a nil style profile or one without an id.

Spoken terms

A spoken terms collection holds terms, one list per language, that speech recognition should recognize. Every method that takes a collection accepts deepl.SpokenTermsID("…") or a deepl.SpokenTerms.

terms, err := client.CreateSpokenTerms(ctx, "Technical Terms",
	[]deepl.SpokenTermsEntries{{Lang: "en", Entries: []string{"DeepL", "webhook"}}}, nil)

terms, err = client.UpdateSpokenTerms(ctx, terms, &deepl.UpdateSpokenTermsOptions{
	TermLists: []deepl.SpokenTermsEntries{{Lang: "en", Entries: []string{"endpoint"}}},
}) // merges "endpoint" into the English list

entries, err := client.GetSpokenTermsEntries(ctx, terms, "en")
fmt.Println(entries.Entries) // [DeepL endpoint webhook]

err = client.DeleteSpokenTerms(ctx, terms)

Methods:

  • CreateSpokenTerms(ctx, name, termLists, opts): one SpokenTermsEntries per language. Like every create, it is retried only on 429 and on failures before the request was sent.
  • ListSpokenTerms(ctx): every collection of the account, without the terms.
  • GetSpokenTerms(ctx, spokenTerms): one collection, without the terms.
  • UpdateSpokenTerms(ctx, spokenTerms, opts): sends only the fields set; with nil options the body is {}. UpdateSpokenTermsOptions has Name ("" leaves it unchanged) and TermLists, whose terms are merged into the list of the same language (created if missing); nil is not sent.
  • DeleteSpokenTerms(ctx, spokenTerms).
  • GetSpokenTermsEntries(ctx, spokenTerms, lang): the terms of one language.
  • ReplaceSpokenTermsList(ctx, spokenTerms, entries, opts): replaces the list of entries.Lang, or adds it; returns its SpokenTermsList.
  • DeleteSpokenTermsList(ctx, spokenTerms, lang).

CreateSpokenTermsOptions, UpdateSpokenTermsOptions and ReplaceSpokenTermsListOptions have ExtraBodyParameters.

SpokenTerms has SpokenTermsID, Name, CreationTime (time.Time) and TermLists ([]SpokenTermsList, each with Lang and EntryCount). SpokenTermsEntries has Lang and Entries ([]string).

Each term is trimmed of surrounding white space and sent trimmed, one per line. The methods return an *ArgumentError without sending a request for a nil collection or one without an id, an empty language, or a term that is empty after trimming or contains a C0 or C1 control character (a tab or newline included), U+2028 or U+2029.

Translation memories

A translation memory holds source segments with their translations and is applied with the TranslationMemory option of TranslateTextOptions and TranslateDocumentOptions. Every method that takes a translation memory accepts deepl.TranslationMemoryID("…") or a deepl.TranslationMemoryInfo; every method that takes a job accepts deepl.TranslationMemoryJobID("…") or a deepl.TranslationMemoryJob.

tms, err := client.ListTranslationMemories(ctx,
	&deepl.ListTranslationMemoriesOptions{Page: deepl.Ptr(0), PageSize: deepl.Ptr(25)})

tm, err := client.GetTranslationMemory(ctx, deepl.TranslationMemoryID("a74d88fb-…"))

// Page through the segments.
opts := &deepl.TranslationMemorySegmentsOptions{PageSize: deepl.Ptr(100)}
for {
	page, err := client.ListTranslationMemorySegments(ctx, tm, opts)
	if err != nil {
		return err
	}
	for _, seg := range page.Segments {
		fmt.Println(seg.SourceText, len(seg.Targets))
	}
	if page.NextPageCursor == nil {
		break
	}
	opts.PageCursor = *page.NextPageCursor
}

// Import a TMX file: create the job, upload the file, wait for the job.
wait := &deepl.WaitOptions{Timeout: deepl.Ptr(5 * time.Minute)}
job, err := client.ImportTranslationMemoryFromFilepath(ctx, "legal.tmx",
	&deepl.ImportTranslationMemoryOptions{DisplayName: "Legal", Timeout: wait.Timeout})
var jobErr *deepl.TranslationMemoryJobError
if errors.As(err, &jobErr) && jobErr.JobID != "" {
	// The job exists: resume with WaitUntilTranslationMemoryJobDone.
}
imported := deepl.TranslationMemoryID(*job.Result.TranslationMemoryID)

// Export to a TMX file: create the job, wait for it, download the file.
job, err = client.ExportTranslationMemoryToFilepath(ctx, imported, "legal-export.tmx", wait)

// The same export step by step.
export, err := client.CreateTranslationMemoryExport(ctx, tm)
job, err = client.WaitUntilTranslationMemoryJobDone(ctx, deepl.TranslationMemoryJobID(export.JobID), wait)
err = client.DownloadTranslationMemoryExport(ctx, job, "export.tmx")

err = client.DeleteTranslationMemory(ctx, tm)

Methods:

  • ListTranslationMemories(ctx, opts): one page of the account's translation memories. ListTranslationMemoriesOptions has Page (0-based, API default 0) and PageSize (API default 10, at most 100); both are pointers, nil is not sent. The total count is not returned.
  • GetTranslationMemory(ctx, translationMemory).
  • DeleteTranslationMemory(ctx, translationMemory): deletes it with all its segments.
  • ListTranslationMemorySegments(ctx, translationMemory, opts): one page of segments, each a source segment with its Targets. Pages are cursor-based: pass the page's NextPageCursor as PageCursor; it is nil on the last page. TranslationMemorySegmentsOptions has PageSize (*int, 1..100, API default 50), PageCursor, FilterText (segments whose source or a translation contains it, at least 2 characters) and FilterCaseSensitive (*bool, API default false); unset fields are not sent. SegmentCount is the translation memory's total and is not reduced by FilterText.
  • CreateTranslationMemoryImport(ctx, fileName, contentLength, opts): creates an import job for a TMX file of contentLength bytes and returns its JobID, the pre-signed UploadURL to PUT the file to (without the DeepL auth header), and ExpiresAt. CreateTranslationMemoryImportOptions has ContentType ("" is not sent; the API uses application/xml), DisplayName (the new translation memory's name) and ExtraBodyParameters. Like every create, it is retried only on 429 and on failures before the request was sent.
  • CreateTranslationMemoryExport(ctx, translationMemory): creates an export job and returns its JobID and TranslationMemoryID. If a recent export is still available, the API returns that job and ReusedExisting is true. Retried like a create.
  • GetTranslationMemoryJob(ctx, job): the state of an import or export job.
  • UploadTranslationMemoryFile(ctx, translationMemoryImport, content, opts): PUTs the file to the import's pre-signed upload URL, given as the TranslationMemoryImport or as deepl.TranslationMemoryUploadURL("…"). UploadTranslationMemoryFileOptions has ContentType ("" means application/xml); it must match the one declared on the job. The API notices the upload asynchronously, so the job keeps reporting awaiting_input for a while.
  • WaitUntilTranslationMemoryJobDone(ctx, job, opts): polls the job every 5 s and returns it once completed. A failed or expired job (with the job's error message) and an expired WaitOptions.Timeout are an *Error; without a timeout it waits without limit, and the last sleep is cut so it never runs past the timeout. Unknown statuses keep polling. An import whose file is never uploaded does not finish on its own, so set a timeout.
  • DownloadTranslationMemoryExport(ctx, job, outputPath): downloads a completed export's TMX file to outputPath, which must not exist (checked before any request; the *fs.PathError from os). The file is removed on failure. A job without a download URL is an *Error. The download URL works only once, also when CreateTranslationMemoryExport reuses the job. DownloadTranslationMemoryExportToWriter(ctx, job, w) streams it to an io.Writer instead.
  • ImportTranslationMemoryFromFilepath(ctx, inputPath, opts): creates the import job (with the file's base name), uploads the file and waits until the job is completed; Result.TranslationMemoryID is the new translation memory. ImportTranslationMemoryOptions has DisplayName, ContentType ("" means application/xml), Timeout and ExtraBodyParameters.
  • ExportTranslationMemoryToFilepath(ctx, translationMemory, outputPath, opts): creates the export job, waits until it is completed and downloads the file to outputPath, which must not exist. opts is a *WaitOptions.

The upload and download URLs are storage outside the DeepL API: those requests carry neither the auth key nor the WithHeaders headers, only the User-Agent (a User-Agent set with WithHeaders included). A non-2xx answer from them is an *Error without a kind (a 403 does not match ErrAuthorization) with HTTPStatusCode set; 429 and 5xx are retried and have ShouldRetry set. A URL that is not an absolute http or https URL is an *Error without a kind, returned at once without a retry.

The file helpers return an *ArgumentError only for a missing input file. Every other failure is a *deepl.TranslationMemoryJobError: an input file that is empty or cannot be read, or an output path that exists or cannot be created (all before any request), and any failure of the job creation, upload, wait or download. Its JobID is set once the job was created and Job holds the last status fetched, so you can resume without starting over; HTTPStatusCode and ShouldRetry are copied from an *Error cause, which errors.Is and errors.As reach. A cancelled ctx is returned as ctx.Err().

TranslationMemoryInfo has TranslationMemoryID, Name, SourceLanguage, TargetLanguages, SegmentCount, and CreationTime and UpdatedTime (*time.Time, nil when absent). Segment times (CreationTime, UpdatedTime, LastUsedTime) are also *time.Time.

TranslationMemoryJob flattens the API's nested objects: JobID, Operation ("import" or "export"), Product, Results, CreationTime, UpdatedTime, and, nil when absent, TranslationMemoryID (export), DisplayName, SourceContentType and SourceContentLength (import). Result is the first entry of Results (the API returns one) and Status its status. Each TranslationMemoryJobResult has Status and, nil when absent, RequiredAction, DownloadURL, ExpiresAt, ErrorMessage, TranslationMemoryID (the one an import created) and SkippedSegmentCount. Done() reports completed; OK() reports that the status is neither failed nor expired (also true while pending). TranslationMemoryJobStatus is an open enum: TranslationMemoryJobStatusAwaitingInput, …Processing, …Completed, …Failed, …Expired, or any other value the API returns.

The methods return an *ArgumentError without sending a request for a nil translation memory or job or one without an id, an empty fileName, a contentLength that is not positive, or an empty upload URL.

Admin API

AdminClient manages the developer keys of an organization and reads its usage analytics. It needs an admin key, which cannot translate. NewAdminClient takes the same options as New (see Configuration); without WithServerURL it uses https://api.deepl.com for every key.

admin, err := deepl.NewAdminClient(os.Getenv("DEEPL_ADMIN_KEY"))

key, err := admin.CreateDeveloperKey(ctx, &deepl.CreateDeveloperKeyOptions{Label: "staging"})
keys, err := admin.ListDeveloperKeys(ctx)
key, err = admin.RenameDeveloperKey(ctx, key, "staging (EU)", nil)
key, err = admin.SetDeveloperKeyUsageLimits(ctx, deepl.DeveloperKeyID(key.KeyID),
	deepl.DeveloperKeyUsageLimitsUpdate{
		Characters:               deepl.Limit(500000), // 0 blocks that usage
		SpeechToTextMilliseconds: deepl.Unlimited(),   // sent as null
		// SpeechToSpeechMilliseconds not set: unchanged
	}, nil)
key, err = admin.DeactivateDeveloperKey(ctx, key, nil) // permanent

start := time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC)
end := time.Date(2026, 10, 31, 0, 0, 0, 0, time.UTC)
report, err := admin.GetUsageAnalytics(ctx, start, end,
	&deepl.GetUsageAnalyticsOptions{GroupBy: deepl.AdminUsageGroupByKeyAndDay})
tags, err := admin.GetCustomTagUsageAnalytics(ctx, start, end,
	&deepl.GetCustomTagUsageAnalyticsOptions{AggregateBy: deepl.CustomTagUsageAggregateByDay})
pairs, err := admin.GetLanguagePairUsageAnalytics(ctx, start, end,
	&deepl.GetLanguagePairUsageAnalyticsOptions{GroupBy: deepl.LanguagePairUsageGroupByKey})
  • Developer keys: every method that takes a key accepts deepl.DeveloperKeyID("…") or a deepl.DeveloperKey, and returns an *ArgumentError without sending a request for a nil key or one without an id. DeveloperKey has KeyID, IsDeactivated and, nil when absent, Label, CreationTime, DeactivatedTime and UsageLimits; in DeveloperKeyUsageLimits a nil limit means unlimited. CreateDeveloperKey is retried only on 429 and on failures before the request was sent, so a retry never creates a second key.
  • SetDeveloperKeyUsageLimits: each field of DeveloperKeyUsageLimitsUpdate is a UsageLimitUpdate; the zero value is not sent and keeps the current limit, deepl.Limit(n) sets it and deepl.Unlimited() removes it.
  • Dates: startDate and endDate are time.Time and go out as the UTC calendar day of that moment, so local midnight in UTC+2 (2026-10-20T00:00+02:00) is sent as 2026-10-19. Use UTC midnight for a calendar day. Both days are included; the API requires endDate after startDate and at most 366 days later. Report dates are UTC midnight.
  • Options: GetUsageAnalyticsOptions.GroupBy (AdminUsageGroupByKey, AdminUsageGroupByKeyAndDay); GetCustomTagUsageAnalyticsOptions with AggregateBy (CustomTagUsageAggregateByPeriod, the API default, or …Day) and Page; GetLanguagePairUsageAnalyticsOptions with GroupBy (LanguagePairUsageGroupByKey), AggregateBy and Page. Pass a report's NextPage as Page for the following page; it is nil on the last one. The enums are open: any other string is sent as given, and reports return the API's value as is (GetUsageAnalytics reports the key-and-day grouping as keyAndDay). CreateDeveloperKeyOptions (Label) and the options of the three key actions take ExtraBodyParameters.
  • Reports: AdminUsageReport (TotalUsage, StartDate, EndDate, GroupBy, KeyUsages, KeyAndDayUsages), CustomTagUsageReport (AggregateBy, StartDate, EndDate, NextPage, Usage) and LanguagePairUsageReport (GroupBy, AggregateBy, StartDate, EndDate, NextPage, LanguagePairUsages, empty for accounts without language pair-level data). Optional fields are pointers, nil when absent.

Document translation

TranslateDocument uploads a file, waits until it is translated and downloads the result to a path that must not exist yet. sourceLang "" auto-detects:

status, err := client.TranslateDocument(ctx, "input.docx", "output.docx", "", "DE",
	&deepl.TranslateDocumentOptions{Formality: deepl.FormalityMore, Timeout: deepl.Ptr(10 * time.Minute)})
if err != nil {
	var docErr *deepl.DocumentTranslationError
	if errors.As(err, &docErr) && docErr.Handle != nil {
		// The document was uploaded (and billed): resume with
		// TranslateDocumentWaitUntilDone and TranslateDocumentDownload.
	}
	log.Fatal(err)
}
if status.BilledCharacters != nil {
	fmt.Println("billed characters:", *status.BilledCharacters)
}

Or run the steps yourself:

handle, err := client.TranslateDocumentUpload(ctx, "input.docx", "EN", "DE", nil)
status, err := client.TranslateDocumentGetStatus(ctx, handle)
status, err = client.TranslateDocumentWaitUntilDone(ctx, handle, &deepl.WaitOptions{Timeout: deepl.Ptr(5 * time.Minute)})
err = client.TranslateDocumentDownload(ctx, handle, "output.docx")
  • TranslateDocument: a missing input file is an *ArgumentError; every other failure, including an existing output path (checked before any request), is a *deepl.DocumentTranslationError. Its Handle is set once the upload succeeded; HTTPStatusCode and ShouldRetry are copied from the cause, which errors.Is/errors.As reach. The output file is removed on failure.
  • TranslateDocumentUpload: the file name sent defaults to the path's base name. TranslateDocumentUploadFromReader reads from an io.Reader and needs Filename. The upload is retried only on 429 and on failures before it was sent, so it is never billed twice.
  • TranslateDocumentGetStatus: a DocumentStatus with DocumentID, Status, SecondsRemaining, BilledCharacters and ErrorMessage; OK() is false once the translation failed, Done() true once it succeeded. Status is a DocumentStatusCode: DocumentStatusCodeQueued, …Translating, …Done, …Error, or any other value the API returns.
  • TranslateDocumentWaitUntilDone: polls every 5 s. WaitOptions.Timeout limits the wait (nil: no limit; zero or negative: one status request). A failed translation or an expired timeout is a *deepl.Error.
  • TranslateDocumentDownload: writes to a path that must not exist (an *fs.PathError otherwise, before any request). TranslateDocumentDownloadToWriter streams to an io.Writer. A translation that is not done yet is a *deepl.Error matching deepl.ErrDocumentNotReady. A body cut off mid-download is requested again within WithMaxRetries; the writer variant does so only while nothing has been written to the writer.

TranslateDocumentOptions:

  • Formality, OutputFormat (file extension, e.g. "pdf"), EnableWatermark (*bool), Filename.
  • Glossary or up to five GlossaryIDs (both need a source language), StyleRule, StyleProfile, TranslationMemory and TranslationMemoryThreshold (0..100, needs TranslationMemory), as in TranslateTextOptions.
  • Timeout: used by TranslateDocument only, see WaitOptions.Timeout.
  • ExtraBodyParameters: added to the upload form last; a nil value removes a field.

Errors

API and connection failures are a *deepl.Error with Message (the API's error message), HTTPStatusCode (0 when no response arrived) and ShouldRetry. Match its kind with errors.Is:

Sentinel Meaning
deepl.ErrAuthorization 401 or 403: the auth key is invalid or not authorized
deepl.ErrNotFound 404, or no dictionary in a glossary entries response
deepl.ErrTooManyRequests 429 after all retries
deepl.ErrQuotaExceeded 456: quota exceeded
deepl.ErrConnection no HTTP response: DNS, connect, timeout, reset, TLS, proxy error
deepl.ErrDocumentNotReady 503 on a document download: the translation is not done

Any other status (400, 5xx) and an unparseable response are a *deepl.Error without a kind. Invalid arguments and client options are a *deepl.ArgumentError, returned before any request. When the ctx you pass is cancelled or expires, the call returns ctx.Err() unwrapped. TranslateDocument wraps its failures in a *deepl.DocumentTranslationError that keeps the document Handle; the translation memory file helpers wrap theirs in a *deepl.TranslationMemoryJobError that keeps the JobID and last Job.

_, err := client.TranslateText(ctx, "Hello", "", "DE", nil)
var deeplErr *deepl.Error
switch {
case errors.Is(err, deepl.ErrQuotaExceeded):
	// handle quota exhaustion
case errors.As(err, &deeplErr):
	log.Printf("status %d, retry may help: %v: %s",
		deeplErr.HTTPStatusCode, deeplErr.ShouldRetry, deeplErr.Message)
}

Configuration

New takes the auth key and functional options; NewAdminClient takes the same options:

client, err := deepl.New("your-key:fx",
	deepl.WithServerURL("https://api.deepl.com"),
	deepl.WithHeaders(map[string]string{"X-Trace": "1"}),
	deepl.WithMaxRetries(3),
	deepl.WithTimeout(20*time.Second),
	deepl.WithProxy("http://proxy.local:3128"),
	deepl.WithSendPlatformInfo(false),
	deepl.WithAppInfo("my-app", "1.2.0"),
)
  • WithServerURL: defaults to https://api-free.deepl.com for a Free key (deepl.IsFreeAccountAuthKey, a :fx suffix) and https://api.deepl.com otherwise. Any absolute http or https URL with a host; a path prefix is kept.
  • WithHeaders: sent with every DeepL API request (not to the translation memory upload and download URLs, which get only a User-Agent). They win over the SDK's headers, Authorization and User-Agent included; Content-Type, Content-Length, Transfer-Encoding and Host keep the SDK's value.
  • WithMaxRetries: retries after the first attempt, default 5. Retried: 429, 5xx and network failures except TLS errors and a proxy's error answer. Waits start at 1 s and grow ×1.6 up to 120 s, with ±23 % jitter. Calls that create a resource (document upload, glossary, style rule, custom instruction, style profile, translation memory import/export and developer key creation) retry only on 429 and on failures before the request was sent.
  • WithTimeout: per attempt, default 10 s; at least the time until the next retry would start. For a document download it covers the time until the response starts, not the body copy; while a request body is being sent, it restarts with every chunk, so a slow upload is not cut.
  • WithProxy: an http or https proxy URL. Without it, the standard HTTPS_PROXY/NO_PROXY environment variables apply.
  • WithSendPlatformInfo, WithAppInfo: the User-Agent is deepl-go/<version> (<os>) go/<go version> <appName>/<appVersion>; the platform part is on by default, the app part only with WithAppInfo.

Additional options and limits of this SDK:

  • WithHTTPClient: use your own *http.Client. Retries and WithTimeout apply to it; WithInsecureSkipVerify and the SDK's proxy handling do not: WithProxy is only validated, and a proxy's non-2xx answer to CONNECT is not recognised, so it is retried like any network failure.
  • WithInsecureSkipVerify(true): disables TLS certificate verification, for testing only.
  • Size limits: JSON responses are read up to 10 MiB, document uploads up to 30 MiB.
  • Error messages: the API's error message is truncated to 200 characters.

Runnable examples are in examples/: translate, rephrase, glossary and document. When running them, export the key rather than inlining it:

export DEEPL_AUTH_KEY=your-key:fx
go run ./examples/translate

Development

go build ./...
go test -race ./...    # offline tests; the real-API tests skip without a key
gofmt -l .             # must print nothing
go vet ./...
golangci-lint run
govulncheck ./...
bash ci/clean-repo-lint.sh

The real-API tests (TestLive*) run against the DeepL API when DEEPL_AUTH_KEY is set, and the Admin API tests when DEEPL_ADMIN_KEY is set. DEEPL_SERVER_URL overrides the server URL. They create and delete resources on that account:

export DEEPL_AUTH_KEY=your-key:fx
go test -run '^TestLive' -v ./...

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

License

MIT.

About

Official Go 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