Translating Text

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

Translating text

This section demonstrates a few ways to request translations. To run the HTTP examples, copy the URL and paste it into your browser. Don't forget to replace YOUR_API_KEY with your actual API key.

The URL for a request has the following format:

https://translation.googleapis.com/language/translate/v2?parameters

Three query parameters are required with each translation request:

  • API key: Use the key parameter to identify your application.
  • Target language: Use the target parameter to specify the language you want to translate into.
  • Source text string: Use the q parameter to specify each text string to translate.

All other query parameters are optional. The URL for GET requests, including parameters, must be less than 2K characters.

Translating input strings

Protocol

Use a separate q parameter for each string. This example sends two strings for translation, and uses the optional source query parameter to specify the language of the source strings (en: English):

https://translation.googleapis.com/language/translate/v2?key=YOUR_API_KEY&source=en&target=de&q=Hello%20world&q=My%20name%20is%20Jeff

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"
      },
      {
        "translatedText": "Mein Name ist Jeff"
      }
    ]
  }
}

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 strings in the request.

Go

For more on installing and creating a Cloud Translation API client, refer to Cloud Translation API Client Libraries.

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

For more on installing and creating a Cloud Translation API client, refer to Cloud Translation API Client Libraries.

public static void translateText(String sourceText, PrintStream out) {
  Translate translate = createTranslateService();
  Translation translation = translate.translate(sourceText);
  out.printf("Source Text:\n\t%s\n", sourceText);
  out.printf("Translated Text:\n\t%s\n", translation.getTranslatedText());
}

Node.js

For more on installing and creating a Cloud Translation API client, refer to Cloud Translation API Client Libraries.

function translateText (input, target) {
  if (!Array.isArray(input)) {
    input = [input];
  }

  // Instantiates a client
  const translate = Translate();

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

      console.log('Translations:');
      translations.forEach((translation, i) => {
        console.log(`${input[i]} => (${target}) ${translation}`);
      });

      return translations;
    });
}

PHP

For more on installing and creating a Cloud Translation API client, refer to Cloud Translation API Client Libraries.

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

For more on installing and creating a Cloud Translation API client, refer to Cloud Translation API Client Libraries.

def translate_text_with_model(target, text, model=translate.BASE):
    """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()

    # 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

For more on installing and creating a Cloud Translation API client, refer to Cloud Translation API Client Libraries.

# 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}"

Send feedback about...

Google Cloud Translation API Documentation