Quickstart: Using Client Libraries

This page shows you how to get started with the Cloud Translation API in your favorite programming language using the Google Cloud Client Libraries.

Before you begin

  1. Sign in to your Google Account.

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

  2. Set up a GCP Console project.

    Set up a project

    Click to:

    • Create or select a project.
    • Enable the Cloud Translation API for that project.
    • Create a service account.
    • Download a private key as JSON.

    You can view and manage these resources at any time in the GCP Console.

  3. Set the environment variable GOOGLE_APPLICATION_CREDENTIALS to the file path of the JSON file that contains your service account key. This variable only applies to your current shell session, so if you open a new session, set the variable again.

Install the client library

C#

For more on setting up your C# development environment, refer to the C# Development Environment Setup Guide.

The C# client libraries for the Translation are currently released as Alpha.

install-package Google.Cloud.Translation.V2 -pre

Go

go get -u cloud.google.com/go/translate

Java

For more on setting up your Java development environment, refer to the Java Development Environment Setup Guide. If you are using Maven, add the following to your pom.xml file:
<dependency>
  <groupId>com.google.cloud</groupId>
  <artifactId>google-cloud-translate</artifactId>
  <version>1.87.0</version>
</dependency>
If you are using Gradle, add the following to your dependencies:
compile 'com.google.cloud:google-cloud-translate:1.87.0'
If you are using SBT, add the following to your dependencies:
libraryDependencies += "com.google.cloud" % "google-cloud-translate" % "1.87.0"

If you're using IntelliJ or Eclipse, you can add client libraries to your project using the following IDE plugins:

The plugins provide additional functionality, such as key management for service accounts. Refer to each plugin's documentation for details.

Node.js

For more on setting up your Node.js development environment, refer to the Node.js Development Environment Setup Guide.
npm install --save @google-cloud/translate

PHP

composer require google/cloud-translate

Python

For more on setting up your Python development environment, refer to the Python Development Environment Setup Guide.
pip install --upgrade google-cloud-translate

Ruby

For more on setting up your Ruby development environment, refer to the Ruby Development Environment Setup Guide.
gem install google-cloud-translate

Translate some text

Now you can use the Translation to translate some text. Run the following code to perform your first text translation:

C#

For more information, see the Translation C# API reference documentation .


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

public class QuickStart
{
    public static void Main(string[] args)
    {
        Console.OutputEncoding = System.Text.Encoding.Unicode;
        TranslationClient client = TranslationClient.Create();
        var response = client.TranslateText("Hello World.", "ru");
        Console.WriteLine(response.TranslatedText);
    }
}

Go

For more information, see the Translation Go API reference documentation .

import (
	"context"
	"fmt"
	"log"

	"cloud.google.com/go/translate"
	"golang.org/x/text/language"
)

func main() {
	ctx := context.Background()

	// Creates a client.
	client, err := translate.NewClient(ctx)
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)
	}

	// Sets the text to translate.
	text := "Hello, world!"
	// Sets the target language.
	target, err := language.Parse("ru")
	if err != nil {
		log.Fatalf("Failed to parse target language: %v", err)
	}

	// Translates the text into Russian.
	translations, err := client.Translate(ctx, []string{text}, target, nil)
	if err != nil {
		log.Fatalf("Failed to translate text: %v", err)
	}

	fmt.Printf("Text: %v\n", text)
	fmt.Printf("Translation: %v\n", translations[0].Text)
}

Java

For more information, see the Translation Java API reference documentation .

// Imports the Google Cloud client library
import com.google.cloud.translate.Translate;
import com.google.cloud.translate.Translate.TranslateOption;
import com.google.cloud.translate.TranslateOptions;
import com.google.cloud.translate.Translation;

public class QuickstartSample {
  public static void main(String... args) throws Exception {
    // Instantiates a client
    Translate translate = TranslateOptions.getDefaultInstance().getService();

    // The text to translate
    String text = "Hello, world!";

    // Translates some text into Russian
    Translation translation =
        translate.translate(
            text,
            TranslateOption.sourceLanguage("en"),
            TranslateOption.targetLanguage("ru"));


    System.out.printf("Text: %s%n", text);
    System.out.printf("Translation: %s%n", translation.getTranslatedText());
  }
}

Node.js

For more information, see the Translation Node.js API reference documentation .

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

  // Instantiates a client
  const translate = new Translate({projectId});

  // The text to translate
  const text = 'Hello, world!';

  // The target language
  const target = 'ru';

  // Translates some text into Russian
  const [translation] = await translate.translate(text, target);
  console.log(`Text: ${text}`);
  console.log(`Translation: ${translation}`);
}

PHP

For more information, see the Translation PHP API reference documentation .

# Includes the autoloader for libraries installed with composer
require __DIR__ . '/vendor/autoload.php';

# Imports the Google Cloud client library
use Google\Cloud\Translate\TranslateClient;

# Your Google Cloud Platform project ID
$projectId = 'YOUR_PROJECT_ID';

# Instantiates a client
$translate = new TranslateClient([
    'projectId' => $projectId
]);

# The text to translate
$text = 'Hello, world!';
# The target language
$target = 'ru';

# Translates some text into Russian
$translation = $translate->translate($text, [
    'target' => $target
]);

echo 'Text: ' . $text . '
Translation: ' . $translation['text'];

Python

For more information, see the Translation Python API reference documentation .

# Imports the Google Cloud client library
from google.cloud import translate

# Instantiates a client
translate_client = translate.Client()

# The text to translate
text = u'Hello, world!'
# The target language
target = 'ru'

# Translates some text into Russian
translation = translate_client.translate(
    text,
    target_language=target)

print(u'Text: {}'.format(text))
print(u'Translation: {}'.format(translation['translatedText']))

Ruby

For more information, see the Translation Ruby API reference documentation .

# Imports the Google Cloud client library
require "google/cloud/translate"

# Your Google Cloud Platform project ID
project_id = "YOUR_PROJECT_ID"

# Instantiates a client
translate = Google::Cloud::Translate.new project: project_id

# The text to translate
text = "Hello, world!"
# The target language
target = "ru"

# Translates some text into Russian
translation = translate.translate text, to: target

puts "Text: #{text}"
puts "Translation: #{translation}"

Congratulations! You've sent your first request to Translation.

Clean up

To avoid incurring charges to your Google Cloud Platform account for the resources used in this quickstart:

  • Use the GCP Console to delete your project if you do not need it.

What's next

Find out more about our Cloud Translation API Client Libraries.

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

Send feedback about...

Cloud Translation
Need help? Visit our support page.