This page shows how to get started with the Cloud Client Libraries for the
Cloud Translation API. Client libraries make it easier to access
Google Cloud APIs from a supported language. Although you can use
Google Cloud APIs directly by making raw requests to the server, client
libraries provide simplifications that significantly reduce the amount of code
you need to write.

Read more about the Cloud Client Libraries
and the older Google API Client Libraries in
[Client libraries explained](https://docs.cloud.google.com/apis/docs/client-libraries-explained).

## Install the client library

### C#

```
nuget install Google.Cloud.Translation.V2
```

For more information, see [Setting Up a C# Development Environment](https://docs.cloud.google.com/dotnet/docs/setup).

### Go

```
go get cloud.google.com/go/translate
```

For more information, see [Setting Up a Go Development Environment](https://docs.cloud.google.com/go/docs/setup).

### Java

> [!CAUTION]
> **Caution:** The Java client library does not support Android.

If you are using [Maven](https://maven.apache.org/), add
the following to your `pom.xml` file. For more information about
BOMs, see [The Google Cloud Platform Libraries BOM](https://cloud.google.com/java/docs/bom).

    <dependencyManagement>
      <dependencies>
        <dependency>
          <groupId>com.google.cloud</groupId>
          <artifactId>libraries-bom</artifactId>
          <version>26.90.0</version>
          <type>pom</type>
          <scope>import</scope>
        </dependency>
      </dependencies>
    </dependencyManagement>

    <dependencies>
      <dependency>
        <groupId>com.google.cloud</groupId>
        <artifactId>google-cloud-translate</artifactId>
      </dependency>
    </dependencies>

If you are using [Gradle](https://gradle.org/),
add the following to your dependencies:

    implementation platform('com.google.cloud:libraries-bom:26.90.0')

    implementation 'com.google.cloud:google-cloud-translate'

If you are using [sbt](https://www.scala-sbt.org/), add
the following to your dependencies:

    libraryDependencies += "com.google.cloud" % "google-cloud-translate" % "2.100.0"

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

- [Cloud Code for VS Code](https://docs.cloud.google.com/code/docs/vscode/client-libraries)
- [Cloud Code for IntelliJ](https://docs.cloud.google.com/code/docs/intellij/client-libraries)

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

> [!NOTE]
> **Note:** Cloud Java client libraries do not currently support Android.

For more information, see [Setting Up a Java Development Environment](https://docs.cloud.google.com/java/docs/setup).

### Node.js


For more on setting up your Node.js development environment, refer to the
[Node.js Development Environment Setup Guide](https://docs.cloud.google.com/nodejs/docs/setup).

```
npm install @google-cloud/translate
```

For more information, see [Setting Up a Node.js Development Environment](https://docs.cloud.google.com/nodejs/docs/setup).

### PHP

```
composer require google/cloud-translate
```

For more information, see [Using PHP on Google Cloud](https://docs.cloud.google.com/php/docs).

### Python


For more on setting up your Python development environment, refer to the
[Python Development Environment Setup Guide](https://docs.cloud.google.com/python/docs/setup).

```
pip install google-cloud-translate==2.0.1
```

For more information, see [Setting Up a Python Development Environment](https://docs.cloud.google.com/python/docs/setup).

### Ruby


For more on setting up your Ruby development environment, refer to the
[Ruby Development Environment Setup Guide](https://docs.cloud.google.com/ruby/docs/setup).

```
gem install google-cloud-translate-v2
```

For more information, see [Setting Up a Ruby Development Environment](https://docs.cloud.google.com/ruby/docs/setup).

<br />

## Set up authentication

To authenticate calls to Google Cloud APIs, client libraries support [Application Default Credentials (ADC)](https://docs.cloud.google.com/docs/authentication/application-default-credentials); the libraries look for credentials in a set of defined locations and use those credentials to authenticate requests to the API. With ADC, you can make credentials available to your application in a variety of environments, such as local development or production, without needing to modify your application code.

For production environments, the way you set up ADC depends on the service
and context. For more information, see [Set up Application Default Credentials](https://docs.cloud.google.com/docs/authentication/provide-credentials-adc).

For a local development environment, you can set up ADC with the credentials
that are associated with your Google Account:

1.
   [Install](https://docs.cloud.google.com/sdk/docs/install) the Google Cloud CLI.

   After installation,
   [initialize](https://docs.cloud.google.com/sdk/docs/initializing) the Google Cloud CLI by running the following command:

   ```bash
   gcloud init
   ```


   If you're using an external identity provider (IdP), you must first
   [sign in to the gcloud CLI with your federated identity](https://docs.cloud.google.com/iam/docs/workforce-log-in-gcloud).
2.

   If you're using a local shell, then create local authentication credentials for your user
   account:

   ```bash
   gcloud auth application-default login
   ```

   You don't need to do this if you're using Cloud Shell.


   If an authentication error is returned, and you are using an external identity provider
   (IdP), confirm that you have
   [signed in to the gcloud CLI with your federated identity](https://docs.cloud.google.com/iam/docs/workforce-log-in-gcloud).


   A sign-in screen appears. After you sign in, your credentials are stored in the
   [local credential file used by ADC](https://docs.cloud.google.com/docs/authentication/application-default-credentials#personal).

## Use the client library


The following example shows how to use the client library.

### Go

    import (
    	"context"
    	"fmt"
    	"io"

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

    // translateText translates the given text into the specified targetLanguage. sourceLanguage
    // is optional. If empty, the API will attempt to detect the source language automatically.
    // targetLanguage and sourceLanguage should follow ISO 639 language code of the input text
    // (e.g., 'fr' for French)
    //
    // Find a list of supported languages and codes here:
    // https://cloud.google.com/translate/docs/languages#nmt
    func translateText(w io.Writer, targetLanguage, sourceLanguage, text string) error {
    	ctx := context.Background()

    	// Create new Translate client.
    	client, err := translate.https://docs.cloud.google.com/go/docs/reference/cloud.google.com/go/translate/latest/index.html#cloud_google_com_go_translate_Client_NewClient(ctx)
    	if err != nil {
    		return fmt.Errorf("translate.NewClient error: %w", err)
    	}
    	defer client.Close()

    	// Get required tag by parsing the target language.
    	targetLang, err := language.Parse(targetLanguage)
    	if err != nil {
    		return fmt.Errorf("language.Parse: %w", err)
    	}

    	options := &translate.https://docs.cloud.google.com/go/docs/reference/cloud.google.com/go/translate/latest/index.html#cloud_google_com_go_translate_Options{}

    	if sourceLanguage != "" {
    		sourceLang, err := language.Parse(sourceLanguage)
    		if err != nil {
    			return fmt.Errorf("language.Parse: %w", err)
    		}
    		options = &translate.https://docs.cloud.google.com/go/docs/reference/cloud.google.com/go/translate/latest/index.html#cloud_google_com_go_translate_Options{
    			Source: sourceLang,
    		}
    	}

    	// Find more information about translate function here:
    	// https://pkg.go.dev/cloud.google.com/go/translate#Client.Translate
    	resp, err := client.https://docs.cloud.google.com/go/docs/reference/cloud.google.com/go/translate/latest/index.html#cloud_google_com_go_translate_Client_Translate(ctx, []string{text}, targetLang, options)
    	if err != nil {
    		return fmt.Errorf("client.Translate error: %w", err)
    	}
    	if len(resp) == 0 {
    		return fmt.Errorf("client.Translate returned empty response to text: %s", text)
    	}

    	// Print results to buffer.
    	fmt.Fprintf(w, "Input Text: %s\n", resp[0].https://docs.cloud.google.com/go/docs/reference/cloud.google.com/go/translate/latest/index.html#cloud_google_com_go_translate_HTML_Text)
    	fmt.Fprintf(w, "Translated Test: %s\n", text)

    	return nil
    }

### Java

    // 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

    // Imports the Google Cloud client library
    const {Translate} = require('https://docs.cloud.google.com/nodejs/docs/reference/translate/latest/overview.html').v2;

    // Creates a client
    const translate = new https://docs.cloud.google.com/nodejs/docs/reference/translate/latest/translate/v2.translate.html();

    /**
     * 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';

    async function translateText() {
      // 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.
      let [translations] = await https://docs.cloud.google.com/nodejs/docs/reference/translate/latest/translate/v2.translate.html.https://docs.cloud.google.com/nodejs/docs/reference/translate/latest/translate/v2.translate.html(text, target);
      translations = Array.isArray(translations) ? translations : [translations];
      console.log('Translations:');
      translations.forEach((translation, i) => {
        console.log(`${text[i]} => (${target}) ${translation}`);
      });
    }

    translateText();

### PHP

    use Google\Cloud\Translate\TranslateClient;

    /**
     * @param string $text The text to translate.
     * @param string $targetLanguage Language to translate to.
     */
    function translate(string $text, string $targetLanguage): void
    {
        /** Uncomment and populate these variables in your code */
        // $text = 'The text to translate.';
        // $targetLanguage = 'ja';  // 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

    def translate_text(
        text: str | bytes | list[str] = "¡Hola amigos y amigas!",
        target_language: str = "en",
        source_language: str | None = None,
    ) -> dict:
        """Translates a given text into the specified target language.

        Find a list of supported languages and codes here:
        https://cloud.google.com/translate/docs/languages#nmt

        Args:
            text: The text to translate. Can be a string, bytes or a list of strings.
                  If bytes, it will be decoded as UTF-8.
            target_language: The ISO 639 language code to translate the text into
                             (e.g., 'en' for English, 'es' for Spanish).
            source_language: Optional. The ISO 639 language code of the input text
                             (e.g., 'fr' for French). If None, the API will attempt
                             to detect the source language automatically.

        Returns:
            A dictionary containing the translation results.
        """

        from google.cloud import translate_v2 as translate

        translate_client = translate.Client()

        if isinstance(text, bytes):
            text = [text.decode("utf-8")]

        if isinstance(text, str):
            text = [text]

        # If a string is supplied, a single dictionary will be returned.
        # In case a list of strings is supplied, this method
        # will return a list of dictionaries.

        # Find more information about translate function here:
        # https://cloud.google.com/python/docs/reference/translate/latest/google.cloud.translate_v2.client.Client#google_cloud_translate_v2_client_Client_translate
        results = translate_client.translate(
            values=text,
            target_language=target_language,
            source_language=source_language
        )

        for result in results:
            if "detectedSourceLanguage" in result:
                print(f"Detected source language: {result['detectedSourceLanguage']}")

            print(f"Input text: {result['input']}")
            print(f"Translated text: {result['translatedText']}")
            print()

        return results

<br />

## Additional resources

### C#

The following list contains links to more resources related to the
client library for C#:

- [API reference](https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.Translation.V2/latest)
- [Client libraries best practices](https://docs.cloud.google.com/apis/docs/client-libraries-best-practices)
- [Issue tracker](https://github.com/googleapis/google-cloud-dotnet/tree/master/apis/Google.Cloud.Translation.V2/issues)
- [`google-translate` on Stack Overflow](https://stackoverflow.com/search?q=%5Bgoogle-translate%5D+%5Bc%23%5D)
- [Source code](https://github.com/googleapis/google-cloud-dotnet/tree/master/apis/Google.Cloud.Translation.V2)

### Go

The following list contains links to more resources related to the
client library for Go:

- [API reference](https://godoc.org/cloud.google.com/go/translate)
- [Client libraries best practices](https://docs.cloud.google.com/apis/docs/client-libraries-best-practices)
- [Issue tracker](https://github.com/googleapis/google-cloud-go/tree/master/translate/issues)
- [`google-translate` on Stack Overflow](https://stackoverflow.com/search?q=%5Bgoogle-translate%5D+%5Bgo%5D)
- [Source code](https://github.com/googleapis/google-cloud-go/tree/master/translate)

### Java

The following list contains links to more resources related to the
client library for Java:

- [API reference](https://docs.cloud.google.com/java/docs/reference/google-cloud-translate/latest/com.google.cloud.translate)
- [Client libraries best practices](https://docs.cloud.google.com/apis/docs/client-libraries-best-practices)
- [Issue tracker](https://github.com/googleapis/java-translate/issues)
- [`google-translate` on Stack Overflow](https://stackoverflow.com/search?q=%5Bgoogle-translate%5D+%5Bjava%5D)
- [Source code](https://github.com/googleapis/java-translate)

### Node.js

The following list contains links to more resources related to the
client library for Node.js:

- [API reference](https://googleapis.dev/nodejs/translate/latest/index.html)
- [Client libraries best practices](https://docs.cloud.google.com/apis/docs/client-libraries-best-practices)
- [Issue tracker](https://github.com/googleapis/nodejs-translate/issues)
- [`google-translate` on Stack Overflow](https://stackoverflow.com/search?q=%5Bgoogle-translate%5D+%5Bnode.js%5D)
- [Source code](https://github.com/googleapis/nodejs-translate)

### PHP

The following list contains links to more resources related to the
client library for PHP:

- [API reference](https://googleapis.github.io/google-cloud-php/#/docs/google-cloud/latest/translate/v2/translateclient)
- [Client libraries best practices](https://docs.cloud.google.com/apis/docs/client-libraries-best-practices)
- [Issue tracker](https://github.com/googleapis/google-cloud-php-translate/issues)
- [`google-translate` on Stack Overflow](https://stackoverflow.com/search?q=%5Bgoogle-translate%5D+%5Bphp%5D)
- [Source code](https://github.com/googleapis/google-cloud-php-translate)

### Python

The following list contains links to more resources related to the
client library for Python:

- [API reference](https://docs.cloud.google.com/python/docs/reference/translate/latest)
- [Client libraries best practices](https://docs.cloud.google.com/apis/docs/client-libraries-best-practices)
- [Issue tracker](https://github.com/googleapis/python-translate#python-client-for-google-cloud-translation/issues)
- [`google-translate` on Stack Overflow](https://stackoverflow.com/search?q=%5Bgoogle-translate%5D+%5Bpython%5D)
- [Source code](https://github.com/googleapis/python-translate#python-client-for-google-cloud-translation)

### Ruby

The following list contains links to more resources related to the
client library for Ruby:

- [API reference](https://googleapis.dev/ruby/google-cloud-translate/latest/Google/Cloud/Translate/V2.html)
- [Client libraries best practices](https://docs.cloud.google.com/apis/docs/client-libraries-best-practices)
- [Issue tracker](https://github.com/googleapis/google-cloud-ruby/tree/master/google-cloud-translate/issues)
- [`google-translate` on Stack Overflow](https://stackoverflow.com/search?q=%5Bgoogle-translate%5D+%5Bruby%5D)
- [Source code](https://github.com/googleapis/google-cloud-ruby/tree/master/google-cloud-translate)

<br />