Automate file localization with the API
Upload a source file, start a document job, and download translations into a separate output directory.
Use the document API when your backend owns the files and needs to coordinate translation with its own storage. This example translates messages/en.json into German and French. The CLI performs the same file operations for a local project.
You need Node.js 22 or later, an organization, an engine configured with a model, and an API key with translation access. Configure translation without human review for this first run; add review after the file lifecycle works.
Prepare a source file #
Create messages/en.json:
{
"title": "Account settings",
"save": "Save changes"
}Set the following environment variables with your own values:
export LINGO_API_KEY="YOUR_API_KEY"
export LINGO_ORGANIZATION_ID="YOUR_ORGANIZATION_ID"
export LINGO_ENGINE_ID="YOUR_ENGINE_ID"
export LINGO_REQUEST_ID="account-settings-v1-de-fr"Keep the same request ID for retries of this source and configuration. Change it when submitting a new revision.
Upload, start, and collect #
Save this program as translate-file.mjs:
import { createHash } from "node:crypto";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { setTimeout as delay } from "node:timers/promises";
const origin = "https://api.lingo.dev";
const {
LINGO_API_KEY: apiKey,
LINGO_ORGANIZATION_ID: orgId,
LINGO_ENGINE_ID: engineId,
LINGO_REQUEST_ID: requestId,
} = process.env;
if (!apiKey || !orgId || !engineId || !requestId) throw new Error("Set the four LINGO environment variables");
async function request(path, options = {}) {
const response = await fetch(new URL(path, origin), {
...options,
headers: { "X-API-Key": apiKey, ...options.headers },
signal: AbortSignal.timeout(30_000),
});
if (!response.ok) throw new Error(`HTTP ${response.status}: ${await response.text()}`);
return response;
}
const bytes = await readFile("messages/en.json");
const address = createHash("sha256").update(bytes).digest("hex");
let job = await (
await request(`/v2/organizations/${encodeURIComponent(orgId)}/localization/jobs`, {
method: "POST",
headers: { "Content-Type": "application/json", "Idempotency-Key": requestId },
body: JSON.stringify({
engineId,
sourceLocale: "en",
targetLocales: ["de", "fr"],
documents: [{ key: "messages/en.json", format: { type: "json" }, source: address }],
}),
})
).json();
await writeFile("file-job.json", JSON.stringify({ id: job.id, requestId, source: address }, null, 2));
for (const upload of job.uploads) {
await request(upload.uploadUrl, {
method: "PUT",
headers: { "Content-Type": "application/octet-stream" },
body: bytes,
});
}
job = await (
await request(`/v2/localization/jobs/${encodeURIComponent(job.id)}/start`, {
method: "POST",
})
).json();
const deadline = Date.now() + 120_000;
while (["Pending", "Running"].includes(job.status._tag)) {
if (Date.now() >= deadline) throw new Error(`Keep job ${job.id} and check again later`);
await delay(2000);
job = await (await request(`/v2/localization/jobs/${encodeURIComponent(job.id)}`)).json();
}
await mkdir("translated", { recursive: true });
for (const { locale, status } of job.documents[0].targets) {
if (status._tag !== "Completed") {
throw new Error(`Inspect job ${job.id}: ${locale} is ${status._tag}`);
}
const output = await request(status.downloadUrl);
await writeFile(`translated/${locale}.json`, new Uint8Array(await output.arrayBuffer()));
console.log(`Saved translated/${locale}.json`);
}Run node translate-file.mjs, then inspect translated/de.json and translated/fr.json. Both should preserve the source keys and contain the corresponding language. The program keeps outputs separate from application files so you can review them before replacing accepted content.
Recover without duplicating the job #
file-job.json records the remote identity and source hash. If an upload or start response is lost, retrieve that job, upload any remaining artifacts, and repeat start. Repeating creation with the original idempotency key also returns the same job.
A polling timeout does not cancel work. Continue reading the recorded job; do not create another merely because the local program stopped waiting.
This example stops at the first incomplete target or failed request. Files already saved remain in translated/. To continue, retrieve the job recorded in file-job.json and download its completed targets using their downloadUrl values; see job status and results. A failed download does not require a new translation job.
Add incremental updates #
For the next revision, provide previousSource and previousTranslations along with the new source address. Keep the bytes for every referenced artifact until upload succeeds. Include accepted human edits in the previous target files you supply.
Translate documents gives the fields and reuse rules. Before publishing, compare the job's source revision with your current source and check for target edits made after submission. Build a translation workflow explains that acceptance step.