Uso de la API

Cómo traducir con LibreTranslate.

Los siguientes ejemplos usan Javascript, pero puedes usar cualquier lenguaje de programación. También hay enlaces de lenguaje disponibles para muchos lenguajes de programación.

Traducción Simple

Solicitud:

const res = await fetch("https://libretranslate.com/translate", {
  method: "POST",
  body: JSON.stringify({
    q: "Hello!",
    source: "en",
    target: "es",
    api_key: "xxxxxx" // puede ser opcional si lo alojas tú mismo
  }),
  headers: { "Content-Type": "application/json" },
});

console.log(await res.json());

Respuesta:

{
    "translatedText": "¡Hola!"
}
Nota

El parámetro api_key solo es necesario cuando se utiliza una instancia configurada con claves API, como libretranslate.com. Las instancias que alojas tú mismo no lo requieren.

Detección Automática del Idioma de Origen

Solicitud:

const res = await fetch("https://libretranslate.com/translate", {
  method: "POST",
  body: JSON.stringify({
    q: "Bonjour!",
    source: "auto",
    target: "en",
    api_key: "xxxxxx"
  }),
  headers: { "Content-Type": "application/json" },
});

console.log(await res.json());

Respuesta:

{
    "detectedLanguage": {
        "confidence": 90.0,
        "language": "fr"
    },
    "translatedText": "Hello!"
}

Traducir HTML/Marcado

Solicitud:

const res = await fetch("https://libretranslate.com/translate", {
  method: "POST",
  body: JSON.stringify({
    q: '<p class="green">Hello!</p>',
    source: "en",
    target: "es",
    format: "html",
    api_key: "xxxxxx"
  }),
  headers: { "Content-Type": "application/json" },
});

console.log(await res.json());

Respuesta:

{
    "translatedText": "<p class=\"green\">¡Hola!</p>"
}

Traducciones Alternativas

Solicitud:

const res = await fetch("https://libretranslate.com/translate", {
  method: "POST",
  body: JSON.stringify({
    q: "Hello",
    source: "en",
    target: "it",
    format: "text",
    alternatives: 3,
    api_key: "xxxxxx"
  }),
  headers: { "Content-Type": "application/json" },
});

console.log(await res.json());

Respuesta:

{
    "alternatives": [
        "Salve",
        "Pronto"
    ],
    "translatedText": "Ciao"
}

Detección de Idioma

Solicitud:

const res = await fetch("https://libretranslate.com/detect", {
  method: "POST",
  body: JSON.stringify({
    q: "Bonjour!",
  }),
  headers: { "Content-Type": "application/json" },
});

console.log(await res.json());

Respuesta:

[{
    "confidence": 90.0,
    "language": "fr"
}]

Idiomas Soportados

https://libretranslate.com/languages

Enlaces de Lenguaje

Puedes usar la API de LibreTranslate con los siguientes enlaces: