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

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.90.0</version>
</dependency>
If you are using Gradle, add the following to your dependencies:
compile 'com.google.cloud:google-cloud-translate:1.90.0'
If you are using SBT, add the following to your dependencies:
libraryDependencies += "com.google.cloud" % "google-cloud-translate" % "1.90.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

Python

For more on setting up your Python development environment, refer to the Python Development Environment Setup Guide.
pip install --upgrade 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:

Java

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


/**
 * Translates a given text to a target language.
 *
 * @param projectId - Id of the project.
 * @param location - location name.
 * @param text - Text for translation.
 * @param sourceLanguageCode - Language code of text. e.g. "en"
 * @param targetLanguageCode - Language code for translation. e.g. "sr"
 */
static TranslateTextResponse translateText(
    String projectId,
    String location,
    String text,
    String sourceLanguageCode,
    String targetLanguageCode) {
  try (TranslationServiceClient translationServiceClient = TranslationServiceClient.create()) {

    LocationName locationName =
        LocationName.newBuilder().setProject(projectId).setLocation(location).build();

    TranslateTextRequest translateTextRequest =
        TranslateTextRequest.newBuilder()
            .setParent(locationName.toString())
            .setMimeType("text/plain")
            .setSourceLanguageCode(sourceLanguageCode)
            .setTargetLanguageCode(targetLanguageCode)
            .addContents(text)
            .build();

    // Call the API
    TranslateTextResponse response = translationServiceClient.translateText(translateTextRequest);
    System.out.format(
        "Translated Text: %s", response.getTranslationsList().get(0).getTranslatedText());
    return response;

  } catch (Exception e) {
    throw new RuntimeException("Couldn't create client.", e);
  }
}

Node.js

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

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'global';
// const text = 'text to translate';

// Imports the Google Cloud Translation library
const {TranslationServiceClient} = require('@google-cloud/translate').v3beta1;

// Instantiates a client
const translationClient = new TranslationServiceClient();
async function translateText() {
  // Construct request
  const request = {
    parent: translationClient.locationPath(projectId, location),
    contents: [text],
    mimeType: 'text/plain', // mime types: text/plain, text/html
    sourceLanguageCode: 'en-US',
    targetLanguageCode: 'sr-Latn',
  };

  // Run request
  const [response] = await translationClient.translateText(request);

  for (const translation of response.translations) {
    console.log(`Translation: ${translation.translatedText}`);
  }
}

translateText();

Python

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

from google.cloud import translate_v3beta1 as translate
client = translate.TranslationServiceClient()

# project_id = YOUR_PROJECT_ID
# text = 'Text you wish to translate'
location = 'global'

parent = client.location_path(project_id, location)

response = client.translate_text(
    parent=parent,
    contents=[text],
    mime_type='text/plain',  # mime types: text/plain, text/html
    source_language_code='en-US',
    target_language_code='sr-Latn')

for translation in response.translations:
    print('Translated Text: {}'.format(translation))

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

How did it go?

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.

Var denne side nyttig? Giv os en anmeldelse af den:

Send feedback om...

Cloud Translation
Har du brug for hjælp? Besøg vores supportside.