0

Request Translation

by
Published Apr 8, 2025

The translate function. The total request body size must not exceed 128 KiB (128 · 1024 bytes). Please split up your text into multiple calls if it exceeds this limit.

Script deepl Verified

The script

Submitted by hugo697 Bun
Verified 428 days ago
1
//native
2
type Deepl = {
3
  apiKey: string;
4
  baseUrl: string;
5
};
6
/**
7
 * Request Translation
8
 * The translate function.
9

10

11
The total request body size must not exceed 128 KiB (128 · 1024 bytes). Please split up your text into multiple
12
calls if it exceeds this limit.
13
 */
14
export async function main(
15
  auth: Deepl,
16
  body: {
17
    text: string[];
18
    source_lang?:
19
      | "AR"
20
      | "BG"
21
      | "CS"
22
      | "DA"
23
      | "DE"
24
      | "EL"
25
      | "EN"
26
      | "ES"
27
      | "ET"
28
      | "FI"
29
      | "FR"
30
      | "HU"
31
      | "ID"
32
      | "IT"
33
      | "JA"
34
      | "KO"
35
      | "LT"
36
      | "LV"
37
      | "NB"
38
      | "NL"
39
      | "PL"
40
      | "PT"
41
      | "RO"
42
      | "RU"
43
      | "SK"
44
      | "SL"
45
      | "SV"
46
      | "TR"
47
      | "UK"
48
      | "ZH";
49
    target_lang:
50
      | "AR"
51
      | "BG"
52
      | "CS"
53
      | "DA"
54
      | "DE"
55
      | "EL"
56
      | "ES"
57
      | "ET"
58
      | "FI"
59
      | "FR"
60
      | "HU"
61
      | "ID"
62
      | "IT"
63
      | "JA"
64
      | "KO"
65
      | "LT"
66
      | "LV"
67
      | "NB"
68
      | "NL"
69
      | "PL"
70
      | "RO"
71
      | "RU"
72
      | "SK"
73
      | "SL"
74
      | "SV"
75
      | "TR"
76
      | "UK"
77
      | "ZH"
78
      | "EN-GB"
79
      | "EN-US"
80
      | "PT-BR"
81
      | "PT-PT"
82
      | "ZH-HANS"
83
      | "ZH-HANT";
84
    context?: string;
85
    show_billed_characters?: false | true;
86
    split_sentences?: "0" | "1" | "nonewlines";
87
    preserve_formatting?: false | true;
88
    formality?: "default" | "more" | "less" | "prefer_more" | "prefer_less";
89
    model_type?:
90
      | "quality_optimized"
91
      | "prefer_quality_optimized"
92
      | "latency_optimized";
93
    glossary_id?: string;
94
    tag_handling?: "xml" | "html";
95
    outline_detection?: false | true;
96
    non_splitting_tags?: string[];
97
    splitting_tags?: string[];
98
    ignore_tags?: string[];
99
  },
100
) {
101
  const url = new URL(`${auth.baseUrl}/v2/translate`);
102

103
  const response = await fetch(url, {
104
    method: "POST",
105
    headers: {
106
      "Content-Type": "application/json",
107
      Authorization: "DeepL-Auth-Key " + auth.apiKey,
108
    },
109
    body: JSON.stringify(body),
110
  });
111
  if (!response.ok) {
112
    const text = await response.text();
113
    throw new Error(`${response.status} ${text}`);
114
  }
115
  return await response.json();
116
}
117