Translating Text with REST

This document describes how to use the common features of the Google Translate API v2 using the RESTful calling style.

Google Translate API is a paid enterprise service for translating large amounts of text. For website translations, we encourage you to use the Google Website Translator gadget.

Before you begin

Before running this sample, take the following steps:
  1. Sign in to your Google account.

    If you don't already have one, sign up for a new account.

  2. Select or create a Cloud Platform Console project.

    Go to the Projects page

  3. Enable billing for your project.

    Enable billing

  4. Click Continue to enable the API and any related services.
  5. On the Credentials page, get an API key.
    Note: If you have an existing API key, you can use that key.

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://www.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 the text to translate.

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

Translating a single string

Protocol

To translate a string, just make a request using the required parameters. Here is an example that specifies the source language, using the optional source query parameter:

https://www.googleapis.com/language/translate/v2?key=YOUR_API_KEY&source=en&target=de&q=Hello%20world

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

200 OK

{
    "data": {
        "translations": [
            {
                "translatedText": "Hallo Welt"
            }
        ]
    }
}

In this example, the response is an array containing a single translatedText field with the translation.

Node.js

Import the Cloud Client Library for the Translate API:

// By default, the client will use the project specified by the GCLOUD_PROJECT
// environment variable. The Translate API uses an API key for authentication.
// See https://googlecloudplatform.github.io/gcloud-node/#/docs/google-cloud/latest/guides/authentication
var Translate = require('@google-cloud/translate');

Instantiate a client and make the translate request:

// Helper library for language codes
var ISO6391 = require('iso-639-1');

function translateText (input, toLang, fromLang, callback) {
  var translate = Translate({
    // The Translate API uses an API key for authentication. This sample looks
    // at an environment variable for the key.
    key: process.env.TRANSLATE_API_KEY
  });

  // "input" can be a string for translating a single piece of text, or an array
  // of strings for translating multiple texts.
  // See https://googlecloudplatform.github.io/gcloud-node/#/docs/translate/latest/translate?method=translate
  translate.translate(input, {
    from: fromLang,
    to: toLang
  }, function (err, translation, apiResponse) {
    if (err) {
      return callback(err);
    }

    console.log('Translated to %s:', ISO6391.getName(toLang));
    return callback(null, translation, apiResponse);
  });
}

Ruby

Import the Cloud Client Library for the Translate API, instantiate a client, and make the translate request:

# api_key       = "Your API access key"
# 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"

gcloud      = Google::Cloud.new
translate   = gcloud.translate api_key
translation = translate.translate text, to: language_code

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

Translating multiple strings

Protocol

To translate more than one string, use the q parameter to specify each one, using an ampersand (&) to delimit each instance. This example shows passing two separate strings for translation:

https://www.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:

200 OK

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

Here, translations is an array containing two translatedText fields with the translations, in the same order as the corresponding source strings were provided in the request.

Node.js

To translate multiple texts, simply pass an array of strings to the Translate#translate method shown in the example above.

Ruby

To translate multiple texts, simply pass multiple strings to the Translate#translate method shown in the example above.

Detecting the source language

Protocol

If the source parameter is omitted from a request, the API attempts to detect the language of the source text. This example shows such a request:

https://www.googleapis.com/language/translate/v2?key=YOUR_API_KEY&target=de&q=Hello%20world

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

200 OK

{
    "data": {
        "translations": [
            {
                "translatedText": "Hallo Welt",
                "detectedSourceLanguage": "en"
            }
        ]
    }
}

Just as in the example above, translations is an array containing a single object with translatedText and the translation of the query. detectedSourceLanguage is a language code. Note that other languages which are not listed in this table may be returned (these will be iso639-1 language codes).

Node.js

Import the Cloud Client Library for the Translate API:

// By default, the client will use the project specified by the GCLOUD_PROJECT
// environment variable. The Translate API uses an API key for authentication.
// See https://googlecloudplatform.github.io/gcloud-node/#/docs/google-cloud/latest/guides/authentication
var Translate = require('@google-cloud/translate');

Instantiate a client and make the language detection request:

function detectLanguage (input, callback) {
  var translate = Translate({
    // The Translate API uses an API key for authentication. This sample looks
    // at an environment variable for the key.
    key: process.env.TRANSLATE_API_KEY
  });

  // "input" can be a string for detecting the language of a single piece of
  // text, or an array of strings for detecting the languages of multiple texts.
  // See https://googlecloudplatform.github.io/gcloud-node/#/docs/translate/latest/translate?method=detect
  translate.detect(input, function (err, result, apiResponse) {
    if (err) {
      return callback(err);
    }

    console.log('Detected language(s):', result);
    return callback(null, result, apiResponse);
  });
}

Ruby

Import the Cloud Client Library for the Translate API, instantiate a client, and make the detect request:

# api_key = "Your API access key"
# text    = "The text you would like to detect the language of"

require "google/cloud"

gcloud    = Google::Cloud.new
translate = gcloud.translate api_key
detection = translate.detect text

puts "'#{text}' detected as language: #{detection.language}"
puts "Confidence: #{detection.confidence}"

Feedback geben zu...

Translate API Documentation