Translating Text

This document describes how to use the Cloud Translation API to translate text.

The input text can be plain text or HTML. Cloud Translation API does not translate any HTML tags in the input, only text that appears between the tags. The output retains the (untranslated) HTML tags, with the translated text between the tags to the extent possible due to differences between the source and target languages. The order of HTML tags in the output may differ from the order in the input text due to word order changes in the translation.

Translating text

This section demonstrates a few ways to request translations from the https://translation.googleapis.com/language/translate/v2 endpoint.

Translating input strings

Protocol

To detect the language of some text, make a POST request and provide JSON in the request body that identifies the language to translate from (source), the language to translate to (target), and the text to translate (q). You can provide multiple strings of text to translate by including multiple q parameters in your JSON. You identify your source and target languages by using their iso-639-1 codes.

The following shows an example of a POST request using curl. The example uses the access token for a service account set up for the project using the Google Cloud Platform Cloud SDK. For instructions on installing the Cloud SDK, setting up a project with a service account, and obtaining an access token, see the Quickstart.

curl -X POST \
     -H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
     -H "Content-Type: application/json; charset=utf-8" \
     --data "{
  'q': 'Hello world',
  'q': 'My name is Jeff',
  'target': 'de'
}" "https://translation.googleapis.com/language/translate/v2"

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

{
  "data": {
    "translations": [
      {
        "translatedText": "Hallo Welt",
        "detectedSourceLanguage": "en"
      },
      {
        "translatedText": "Mein Name ist Jeff",
        "detectedSourceLanguage": "en"
      }
    ]
  }
}

The translations array contains two translatedText fields with translations provided in the requested target language (de: German). The translations are listed in the same order as the corresponding source array in the request.

C#

Before trying this sample, follow the C# setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API C# API reference documentation .

using Google.Cloud.Translation.V2;
using System;

public partial class TranslateSample
{
    public string TranslateText()
    {
        TranslationClient client = TranslationClient.Create();
        var response = client.TranslateText(
            text: "Hello World.",
            targetLanguage: "ru",  // Russian
            sourceLanguage: "en");  // English
        Console.WriteLine(response.TranslatedText);
        return response.TranslatedText;
    }
}

Go

Before trying this sample, follow the Go setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API Go API reference documentation .

func translateText(targetLanguage, text string) (string, error) {
	ctx := context.Background()

	lang, err := language.Parse(targetLanguage)
	if err != nil {
		return "", err
	}

	client, err := translate.NewClient(ctx)
	if err != nil {
		return "", err
	}
	defer client.Close()

	resp, err := client.Translate(ctx, []string{text}, lang, nil)
	if err != nil {
		return "", err
	}
	return resp[0].Text, nil
}

Java

Before trying this sample, follow the Java setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API Java API reference documentation .

// TODO(developer): Uncomment these lines.
// import com.google.cloud.translate.*;
// Translate translate = TranslateOptions.getDefaultInstance().getService();

Translation translation = translate.translate("¡Hola Mundo!");
System.out.printf("Translated Text:\n\t%s\n", translation.getTranslatedText());

Node.js

Before trying this sample, follow the Node.js setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API Node.js API reference documentation .

// Imports the Google Cloud client library
const {Translate} = require('@google-cloud/translate');

// Creates a client
const translate = new Translate();

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const text = 'The text to translate, e.g. Hello, world!';
// const target = 'The target language, e.g. ru';

// Translates the text into the target language. "text" can be a string for
// translating a single piece of text, or an array of strings for translating
// multiple texts.
translate
  .translate(text, target)
  .then(results => {
    let translations = results[0];
    translations = Array.isArray(translations)
      ? translations
      : [translations];

    console.log('Translations:');
    translations.forEach((translation, i) => {
      console.log(`${text[i]} => (${target}) ${translation}`);
    });
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

PHP

Before trying this sample, follow the PHP setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API PHP API reference documentation .

use Google\Cloud\Translate\TranslateClient;

// $text = 'The text to translate."
// $targetLanguage = 'ja';  // Which language to translate to?

$translate = new TranslateClient();
$result = $translate->translate($text, [
    'target' => $targetLanguage,
]);
print("Source language: $result[source]\n");
print("Translation: $result[text]\n");

Python

Before trying this sample, follow the Python setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API Python API reference documentation .

"""Translates text into the target language.

Target must be an ISO 639-1 language code.
See https://g.co/cloud/translate/v2/translate-reference#supported_languages
"""
translate_client = translate.Client()

if isinstance(text, six.binary_type):
    text = text.decode('utf-8')

# Text can also be a sequence of strings, in which case this method
# will return a sequence of results for each text.
result = translate_client.translate(
    text, target_language=target)

print(u'Text: {}'.format(result['input']))
print(u'Translation: {}'.format(result['translatedText']))
print(u'Detected source language: {}'.format(
    result['detectedSourceLanguage']))

Ruby

Before trying this sample, follow the Ruby setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API Ruby API reference documentation .

# project_id    = "Your Google Cloud project ID"
# text          = "The text you would like to translate"
# language_code = "The ISO 639-1 code of language to translate to, eg. 'en'"

require "google/cloud/translate"

translate   = Google::Cloud::Translate.new project: project_id
translation = translate.translate text, to: language_code

puts "Translated '#{text}' to '#{translation.text.inspect}'"
puts "Original language: #{translation.from} translated to: #{translation.to}"

Specifying a model

By default, when you make a translation request to the Cloud Translation API, your text is translated using the Neural Machine Translation (NMT) model. If the NMT model is not supported for the requested language translation pair, then the Phrase-Based Machine Translation (PBMT) model is used.

Comparing models

The NMT model can provide improved translation for longer and more complex content. For example, consider the following request:

{
  'q': 'So let us begin anew--remembering on both sides that civility is not a
        sign of weakness, and sincerity is always subject to proof. Let us never
        negotiate out of fear. But let us never fear to negotiate.',
  'target': 'de',
}

Because no model is specified in the request, and the translation language pair of English to German is supported by the NMT model, the request is translated using the nmt model. The following is returned in the response's translations field:

"translatedText": "Fangen wir also von neuem an - auf beiden Seiten erinnern wir
                   uns, daß die Höflichkeit kein Zeichen der Schwäche ist und
                   die Aufrichtigkeit immer unter Beweis gestellt wird. Lasst
                   uns nie aus Furcht verhandeln. Aber lassen Sie uns niemals
                   Angst haben, zu verhandeln.",
"detectedSourceLanguage": "en",
"model": "nmt"

Alternatively, you can specifically request that the text be translated using the base (PBMT) model.

{
  'q': 'So let us begin anew--remembering on both sides that civility is not a
        sign of weakness, and sincerity is always subject to proof. Let us never
        negotiate out of fear. But let us never fear to negotiate.',
  'target': 'de',
  'model': 'base',
}

Using the base model returns the following result in the response's translations field, which differs from the translation using the nmt model.

"translatedText": "Lassen Sie uns also neu beginnen - auf beiden Seiten nicht
                   vergessen, dass Zivilität ist kein Zeichen von Schwäche, und
                   Aufrichtigkeit ist immer unter Beweis. Lassen Sie uns nie aus
                   Angst verhandeln. Aber lassen Sie uns nie zu verhandeln
                   fürchten.",
"detectedSourceLanguage": "en",
"model": "base"

Using the model parameter

You can specify which model to use for translation by using the model query parameter. Specify base to use the PBMT model, and nmt to use the NMT model. If you specify the NMT model in your request and the requested language translation pair is not supported for the NMT model, then the PBMT model is used.

The following sample shows how to use the model parameter in a translate request.

Protocol

To translate text using the nmt model, include the model parameter in your POST request.

curl -X POST \
     -H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
     -H "Content-Type: application/json; charset=utf-8" \
     --data "{
  'q': 'So let us begin anew--remembering on both sides that civility is not a
        sign of weakness, and sincerity is always subject to proof. Let us never
        negotiate out of fear. But let us never fear to negotiate.',
  'target': 'de',
  'model': 'nmt',
}" "https://translation.googleapis.com/language/translate/v2"

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

{
  "data": {
    "translations": [
      {
        "translatedText": "Lasst uns also von neuem beginnen - erinnert euch
           auf beiden Seiten, dass Höflichkeit kein Zeichen von Schwäche ist,
           und Aufrichtigkeit immer dem Beweis unterliegt. Lasst uns niemals
           aus Angst verhandeln. Aber lassen Sie uns niemals Angst haben zu
           verhandeln.",
        "detectedSourceLanguage": "en",
        "model": "nmt"
      }
    ]
  }
}

C#

Before trying this sample, follow the C# setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API C# API reference documentation .

using Google.Cloud.Translation.V2;
using System;

public partial class TranslateSample
{
    public TranslationResult TranslateTextWithModel()
    {
        TranslationClient client = TranslationClient.Create();
        TranslationResult result = client.TranslateText(
            text: "Hello World.",
            targetLanguage: "ja",  // Japanese
            sourceLanguage: "en",  // English
            model: TranslationModel.NeuralMachineTranslation);
        Console.WriteLine($"Model: {result.Model}");
        Console.WriteLine(result.TranslatedText);
        return result;
    }
}

Java

Before trying this sample, follow the Java setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API Java API reference documentation .

Translation translation = translate.translate(
    "Hola Mundo!",
    Translate.TranslateOption.sourceLanguage("es"),
    Translate.TranslateOption.targetLanguage("de"),
    // Use "base" for standard edition, "nmt" for the premium model.
    Translate.TranslateOption.model("nmt"));

System.out.printf(
    "TranslatedText:\nText: %s\n",
    translation.getTranslatedText());

Node.js

Before trying this sample, follow the Node.js setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API Node.js API reference documentation .

// Imports the Google Cloud client library
const {Translate} = require('@google-cloud/translate');

// Creates a client
const translate = new Translate();

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const text = 'The text to translate, e.g. Hello, world!';
// const target = 'The target language, e.g. ru';
// const model = 'The model to use, e.g. nmt';

const options = {
  // The target language, e.g. "ru"
  to: target,
  // Make sure your project is whitelisted.
  // Possible values are "base" and "nmt"
  model: model,
};

// Translates the text into the target language. "text" can be a string for
// translating a single piece of text, or an array of strings for translating
// multiple texts.
translate
  .translate(text, options)
  .then(results => {
    let translations = results[0];
    translations = Array.isArray(translations)
      ? translations
      : [translations];

    console.log('Translations:');
    translations.forEach((translation, i) => {
      console.log(`${text[i]} => (${target}) ${translation}`);
    });
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

PHP

Before trying this sample, follow the PHP setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API PHP API reference documentation .

use Google\Cloud\Translate\TranslateClient;

// $text = 'The text to translate.';
// $targetLanguage = 'ja';  // Which language to translate to?
// $model = 'nmt';  // "base" for standard edition, "nmt" for premium

$translate = new TranslateClient();
$result = $translate->translate($text, [
    'target' => $targetLanguage,
    'model'  => $model,
]);
print("Source language: $result[source]\n");
print("Translation: $result[text]\n");
print("Model: $result[model]\n");

Python

Before trying this sample, follow the Python setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API Python API reference documentation .

"""Translates text into the target language.

Make sure your project is whitelisted.

Target must be an ISO 639-1 language code.
See https://g.co/cloud/translate/v2/translate-reference#supported_languages
"""
translate_client = translate.Client()

if isinstance(text, six.binary_type):
    text = text.decode('utf-8')

# Text can also be a sequence of strings, in which case this method
# will return a sequence of results for each text.
result = translate_client.translate(
    text, target_language=target, model=model)

print(u'Text: {}'.format(result['input']))
print(u'Translation: {}'.format(result['translatedText']))
print(u'Detected source language: {}'.format(
    result['detectedSourceLanguage']))

Ruby

Before trying this sample, follow the Ruby setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API Ruby API reference documentation .

# project_id    = "Your Google Cloud project ID"
# text          = "The text you would like to translate"
# language_code = "The ISO 639-1 code of language to translate to, eg. 'en'"

require "google/cloud/translate"

translate   = Google::Cloud::Translate.new project: project_id
translation = translate.translate text, to: language_code, model: "nmt"

puts "Translated '#{text}' to '#{translation.text.inspect}'"
puts "Original language: #{translation.from} translated to: #{translation.to}"

Was this page helpful? Let us know how we did:

Send feedback about...

Cloud Translation API
Need help? Visit our support page.