Translating text (Advanced)

Translation API - Advanced supports translating text using custom AutoML Translation models, and for creating glossaries to ensure that the Translation API translates a customer's domain-specific terminology correctly.

Before you can use Translation API - Advanced, you must enable the AutoML API (automl.googleapis.com) if you want to use AutoML custom models for your project. If you are an existing Translation API user, see to our migration guide. For instructions on installing the Cloud SDK, setting up a project with a service account, and obtaining an access token, see the Quickstart. If you plan to use a glossary or the batch features, you also need to create a Google Cloud Storage bucket and grant your service account access to it.

Comparing models

When you request translation from Translation API - Advanced, you can specify which translation model to use. If no model is specified the nmt model is used if the language pair is supported, otherwise the PBMT model is used.

Model Best fit Examples
Neural Machine Translation (NMT) model

General text use cases such as common website content that is not specific to a domain, for example. news articles.

News articles, Social media, Chat applications, Reviews

Phrase-Based Machine Translation (PBMT) model NMT generally results in better quality translations. PBMT might be used by default if the NMT model doesn't exist for a language pair. Use when NMT is not available.
AutoML Translation model Domain specific text. Customers provide training data specific to their use cases, for given language pairs to customize Google's base model for the domain purpose. Financial News, technical documents, any text that uses terms and jargon unique to that field.

You specify the translation model using its model ID. For the general Google models, the model IDs are general/nmt for the NMT model and general/base for the PBMT model. See the next section for information about AutoML Translation model IDs.

Translating text

The input text can be plain text or HTML. Translation API does not translate any HTML tags in the input, only text that appears between the tags. The output retains the (untranslated) HTML tags, with the translated text between the tags to the extent possible due to differences between the source and target languages. The order of HTML tags in the output may differ from the order in the input text due to word order changes in the translation.

Translating input strings

REST & CMD LINE

To detect the language of some text, make a POST request and provide JSON in the request body that identifies the language to translate from (source_language_code), the language to translate to (target_language_code), and the text to translate (contents). You can provide multiple strings of text to translate by including them in your JSON (see example). You identify your source and target languages by using their iso-639-1 codes.

The following shows an example of a POST request using curl or PowerShell. The example uses the access token for a service account set up for the project using the Google Cloud Platform Cloud SDK. For instructions on installing the Cloud SDK, setting up a project with a service account, and obtaining an access token, see the Quickstart.

Before using any of the request data below, make the following replacements:

  • project-number-or-id: your GCP project number or ID

HTTP method and URL:

POST https://translation.googleapis.com/v3/projects/project-number-or-id:translateText

Request JSON body:

{
  "sourceLanguageCode": "en",
  "targetLanguageCode": "ru",
  "contents": ["Dr. Watson, come here!", "Bring me some coffee!"]
}

To send your request, choose one of these options:

curl

Save the request body in a file called request.json, and execute the following command:

curl -X POST \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
https://translation.googleapis.com/v3/projects/project-number-or-id:translateText

PowerShell

Save the request body in a file called request.json, and execute the following command:

$cred = gcloud auth application-default print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://translation.googleapis.com/v3/projects/project-number-or-id:translateText " | Select-Object -Expand Content

You should receive a JSON response similar to the following:

{
  "translations": [
    {
      "translatedText": "Доктор Ватсон, иди сюда!",
    },
    {
      "translatedText": "Принеси мне кофе!",
    }
  ]
}

The translations array contains two translatedText fields with translations provided in the requested targetLanguageCode language (ru: Russian). The translations are listed in the same order as the corresponding source array in the request.

C#

Before trying this sample, follow the C# setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API C# API reference documentation .


using Google.Cloud.Translate.V3;
using System;

namespace GoogleCloudSamples
{
    public static class TranslateText
    {
        /// <summary>
        /// Translates a given text to a target language.
        /// </summary>
        /// <param name="text">The content to translate.</param>
        /// <param name="targetLanguage">Required. Target language code.</param>
        /// <param name="projectId">Your Google Cloud Project ID.</param>
        public static void TranslateTextSample(string text = "[TEXT_TO_TRANSLATE]",
            string targetLanguage = "ja",
            string projectId = "[Google Cloud Project ID]")
        {
            TranslationServiceClient translationServiceClient = TranslationServiceClient.Create();
            TranslateTextRequest request = new TranslateTextRequest
            {
                Contents =
                {
                    // The content to translate.
                    text,
                },
                TargetLanguageCode = targetLanguage,
                ParentAsLocationName = new LocationName(projectId, "global"),
            };
            TranslateTextResponse response = translationServiceClient.TranslateText(request);
            // Display the translation for each input text provided
            foreach (Translation translation in response.Translations)
            {
                Console.WriteLine($"Translated text: {translation.TranslatedText}");
            }
        }
    }

Go

Before trying this sample, follow the Go setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API Go API reference documentation .

import (
	"context"
	"fmt"
	"io"

	translate "cloud.google.com/go/translate/apiv3"
	translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3"
)

// translateText translates input text and returns translated text.
func translateText(w io.Writer, projectID string, sourceLang string, targetLang string, text string) error {
	// projectID := "my-project-id"
	// sourceLang := "en-US"
	// targetLang := "fr"
	// text := "Text you wish to translate"

	ctx := context.Background()
	client, err := translate.NewTranslationClient(ctx)
	if err != nil {
		return fmt.Errorf("NewTranslationClient: %v", err)
	}
	defer client.Close()

	req := &translatepb.TranslateTextRequest{
		Parent:             fmt.Sprintf("projects/%s/locations/global", projectID),
		SourceLanguageCode: sourceLang,
		TargetLanguageCode: targetLang,
		MimeType:           "text/plain", // Mime types: "text/plain", "text/html"
		Contents:           []string{text},
	}

	resp, err := client.TranslateText(ctx, req)
	if err != nil {
		return fmt.Errorf("TranslateText: %v", err)
	}

	// Display the translation for each input text provided
	for _, translation := range resp.GetTranslations() {
		fmt.Fprintf(w, "Translated text: %v\n", translation.GetTranslatedText())
	}

	return nil
}

Java

Before trying this sample, follow the Java setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API Java API reference documentation .

import com.google.cloud.translate.v3.LocationName;
import com.google.cloud.translate.v3.TranslateTextRequest;
import com.google.cloud.translate.v3.TranslateTextResponse;
import com.google.cloud.translate.v3.Translation;
import com.google.cloud.translate.v3.TranslationServiceClient;

import java.io.IOException;

public class TranslateText {

  public static void translateText() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "[Google Cloud Project ID]";
    String location = "global";
    String targetLanguage = "fr";
    String text = "Hello, world!";
    translateText(projectId, location, targetLanguage, text);
  }

  // Translating Text
  public static void translateText(
      String projectId, String location, String targetLanguage, String text) throws IOException {

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (TranslationServiceClient client = TranslationServiceClient.create()) {
      LocationName parent = LocationName.of(projectId, location);
      TranslateTextRequest request =
          TranslateTextRequest.newBuilder()
              .setParent(parent.toString())
              .setTargetLanguageCode(targetLanguage)
              .addContents(text)
              .build();

      TranslateTextResponse response = client.translateText(request);

      // Display the translation for each input text provided
      for (Translation translation : response.getTranslationsList()) {
        System.out.printf("Translated text: %s\n", translation.getTranslatedText());
      }
    }
  }
}

Node.js

Before trying this sample, follow the Node.js setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API 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');

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

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

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

translateText();

PHP

Before trying this sample, follow the PHP setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API PHP API reference documentation .

use Google\Cloud\Translate\V3\TranslationServiceClient;

$translationServiceClient = new TranslationServiceClient();

/** Uncomment and populate these variables in your code */
// $text = 'Hello, world!';
// $targetLanguage = 'fr';
// $projectId = '[Google Cloud Project ID]';
$contents = [$text];
$formattedParent = $translationServiceClient->locationName($projectId, 'global');

try {
    $response = $translationServiceClient->translateText(
        $contents,
        $targetLanguage,
        $formattedParent
    );
    // Display the translation for each input text provided
    foreach ($response->getTranslations() as $translation) {
        printf('Translated text: %s' . PHP_EOL, $translation->getTranslatedText());
    }
} finally {
    $translationServiceClient->close();
}

Python

Before trying this sample, follow the Python setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API Python API reference documentation .

from google.cloud import translate


def sample_translate_text(text, target_language, project_id):
    """
    Translating Text

    Args:
      text The content to translate in string format
      target_language Required. The BCP-47 language code to use for translation.
    """

    client = translate.TranslationServiceClient()

    # TODO(developer): Uncomment and set the following variables
    # text = 'Text you wish to translate'
    # target_language = 'fr'
    # project_id = '[Google Cloud Project ID]'
    contents = [text]
    parent = client.location_path(project_id, "global")

    response = client.translate_text(
        parent=parent,
        contents=contents,
        mime_type='text/plain',  # mime types: text/plain, text/html
        source_language_code='en-US',
        target_language_code=target_language)
    # Display the translation for each input text provided
    for translation in response.translations:
        print(u"Translated text: {}".format(translation.translated_text))

Ruby

Before trying this sample, follow the Ruby setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API Ruby API reference documentation .

require "google/cloud/translate"

client = Google::Cloud::Translate.new

project = "[Google Cloud Project ID]"

# The content to translate in string format
contents = ["Hello, world!"]
# Required. The BCP-47 language code to use for translation.
target_language = "fr"
parent = client.class.location_path project, "global"

response = client.translate_text contents, target_language, parent

# Display the translation for each input text provided
response.translations.each do |translation|
  puts "Translated text: #{translation.translated_text}"
end

Translating text using an AutoML Translation custom model

REST & CMD LINE

This example translates text using an AutoML Translation model whose model ID is TRL1395675701985363739. You can get the model ID for an AutoML Translation model from the list of models in the AutoML Translation UI or from the API response when you train the model.

Make sure you have enabled the Cloud AutoML API for your project. This is necessary when using AutoML models with Translation API. See this [Getting started](/apis/docs/getting-started#enabling_apis) document to enable the API.

Before using any of the request data below, make the following replacements:

  • project-number-or-id: your GCP project number or ID

HTTP method and URL:

POST https://translation.googleapis.com/v3/projects/project-number-or-id/locations/us-central1:translateText

Request JSON body:

{
  "model": "projects/project-number-or-id/locations/us-central1/models/TRL1395675701985363739",
  "sourceLanguageCode": "en",
  "targetLanguageCode": "ru",
  "contents": ["Dr. Watson, please discard your trash. You've shared unsolicited email with me.
  Let's talk about spam and importance ranking in a confidential mode."]
}

To send your request, choose one of these options:

curl

Save the request body in a file called request.json, and execute the following command:

curl -X POST \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
https://translation.googleapis.com/v3/projects/project-number-or-id/locations/us-central1:translateText

PowerShell

Save the request body in a file called request.json, and execute the following command:

$cred = gcloud auth application-default print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://translation.googleapis.com/v3/projects/project-number-or-id/locations/us-central1:translateText " | Select-Object -Expand Content

You should receive a JSON response similar to the following:

{
  "translation": {
    "translatedText": "Доктор Ватсон, пожалуйста, откажитесь от своего мусора.
    Вы поделились нежелательной электронной почтой со мной. Давайте поговорим о
    спаме и важности рейтинга в конфиденциальном режиме.",
    "model": "projects/project-number/locations/us-central1/models/TRL1395675701985363739"
  }
}

C#

Before trying this sample, follow the C# setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API C# API reference documentation .


using Google.Cloud.Translate.V3;
using System;

namespace GoogleCloudSamples
{
    public static class TranslateTextWithModel
    {
        /// <summary>
        /// Translates a given text to a target language with custom model.
        /// </summary>
        /// <param name="modelId">Translation Model ID.</param>
        /// <param name="text">The content to translate.t</param>
        /// <param name="targetLanguage">Required. Target language code.</param>
        /// <param name="sourceLanguage">Optional. Source language code.</param>
        /// <param name="projectId"> Google Project ID.</param>
        /// <param name="location"> Region.</param>
        public static void TranslateTextWithModelSample(
            string modelId = "[YOUR_MODEL_ID]",
            string text = "[TEXT_TO_TRANSLATE]",
            string targetLanguage = "ja",
            string sourceLanguage = "en",
            string projectId = "[Google Cloud Project ID]",
            string location = "us-central1")
        {
            TranslationServiceClient translationServiceClient = TranslationServiceClient.Create();
            string modelPath = $"projects/{projectId}/locations/{location}/models/{modelId}";

            TranslateTextRequest request = new TranslateTextRequest
            {
                Contents =
                {
                    // The content to translate.
                    text,
                },
                TargetLanguageCode = targetLanguage,
                ParentAsLocationName = new LocationName(projectId, location),
                Model = modelPath,
                SourceLanguageCode = sourceLanguage,
                MimeType = "text/plain",
            };
            TranslateTextResponse response = translationServiceClient.TranslateText(request);
            // Display the translation for each input text provided
            foreach (Translation translation in response.Translations)
            {
                Console.WriteLine($"Translated text: {translation.TranslatedText}");
            }
        }
    }

Go

Before trying this sample, follow the Go setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API Go API reference documentation .

import (
	"context"
	"fmt"
	"io"

	translate "cloud.google.com/go/translate/apiv3"
	translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3"
)

// translateTextWithModel translates input text and returns translated text.
func translateTextWithModel(w io.Writer, projectID string, location string, sourceLang string, targetLang string, text string, modelID string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// sourceLang := "en"
	// targetLang := "fr"
	// text := "Hello, world!"
	// modelID := "your-model-id"

	ctx := context.Background()
	client, err := translate.NewTranslationClient(ctx)
	if err != nil {
		return fmt.Errorf("NewTranslationClient: %v", err)
	}
	defer client.Close()

	req := &translatepb.TranslateTextRequest{
		Parent:             fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		SourceLanguageCode: sourceLang,
		TargetLanguageCode: targetLang,
		MimeType:           "text/plain", // Mime types: "text/plain", "text/html"
		Contents:           []string{text},
		Model:              fmt.Sprintf("projects/%s/locations/%s/models/%s", projectID, location, modelID),
	}

	resp, err := client.TranslateText(ctx, req)
	if err != nil {
		return fmt.Errorf("TranslateText: %v", err)
	}

	// Display the translation for each input text provided
	for _, translation := range resp.GetTranslations() {
		fmt.Fprintf(w, "Translated text: %v\n", translation.GetTranslatedText())
	}

	return nil
}

Java

Before trying this sample, follow the Java setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API Java API reference documentation .

import com.google.cloud.translate.v3.LocationName;
import com.google.cloud.translate.v3.TranslateTextRequest;
import com.google.cloud.translate.v3.TranslateTextResponse;
import com.google.cloud.translate.v3.Translation;
import com.google.cloud.translate.v3.TranslationServiceClient;

import java.io.IOException;

public class TranslateTextWithModel {

  public static void translateTextWithModel() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "[Google Cloud Project ID]";
    String location = "us-central1";
    String sourceLanguage = "en";
    String targetLanguage = "ja";
    String text = "Hello, world!";
    String modelId = "[Your Model ID]";
    translateTextWithModel(projectId, location, sourceLanguage, targetLanguage, text, modelId);
  }

  // Translating Text with Model
  public static void translateTextWithModel(
      String projectId,
      String location,
      String sourceLanguage,
      String targetLanguage,
      String text,
      String modelId)
      throws IOException {

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (TranslationServiceClient client = TranslationServiceClient.create()) {
      LocationName parent = LocationName.of(projectId, location);
      String modelPath =
          String.format("projects/%s/locations/%s/models/%s", projectId, location, modelId);
      TranslateTextRequest request =
          TranslateTextRequest.newBuilder()
              .setParent(parent.toString())
              .setMimeType("text/plain") // Optional. Can be "text/plain" or "text/html".
              .setSourceLanguageCode(sourceLanguage)
              .setTargetLanguageCode(targetLanguage)
              .addContents(text)
              .setModel(modelPath)
              .build();

      TranslateTextResponse response = client.translateText(request);

      // Display the translation for each input text provided
      for (Translation translation : response.getTranslationsList()) {
        System.out.printf("Translated text: %s\n", translation.getTranslatedText());
      }
    }
  }
}

Node.js

Before trying this sample, follow the Node.js setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API Node.js API reference documentation .

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

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

// Instantiates a client
const translationClient = new TranslationServiceClient();
async function translateTextWithModel() {
  // Construct request
  const request = {
    parent: `projects/${projectId}/locations/${location}`,
    contents: [text],
    mimeType: 'text/plain', // mime types: text/plain, text/html
    sourceLanguageCode: 'en',
    targetLanguageCode: 'ja',
    model: `projects/${projectId}/locations/${location}/models/${modelId}`,
  };

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

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

translateTextWithModel();

PHP

Before trying this sample, follow the PHP setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API PHP API reference documentation .

use Google\Cloud\Translate\V3\TranslationServiceClient;

$translationServiceClient = new TranslationServiceClient();

/** Uncomment and populate these variables in your code */
// $modelId = '[MODEL ID]';
// $text = 'Hello, world!';
// $targetLanguage = 'fr';
// $sourceLanguage = 'en';
// $projectId = '[Google Cloud Project ID]';
// $location = 'global';
$modelPath = sprintf(
    'projects/%s/locations/%s/models/%s',
    $projectId,
    $location,
    $modelId
);
$contents = [$text];
$formattedParent = $translationServiceClient->locationName(
    $projectId,
    $location
);

// Optional. Can be "text/plain" or "text/html".
$mimeType = 'text/plain';

try {
    $response = $translationServiceClient->translateText(
        $contents,
        $targetLanguage,
        $formattedParent,
        [
            'model' => $modelPath,
            'sourceLanguageCode' => $sourceLanguage,
            'mimeType' => $mimeType
        ]
    );
    // Display the translation for each input text provided
    foreach ($response->getTranslations() as $translation) {
        printf('Translated text: %s' . PHP_EOL, $translation->getTranslatedText());
    }
} finally {
    $translationServiceClient->close();
}

Python

Before trying this sample, follow the Python setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API Python API reference documentation .

from google.cloud import translate


def sample_translate_text_with_model(
    model_id, text, target_language, source_language, project_id, location
):
    """
    Translating Text with Model

    Args:
      model_id The `model` type requested for this translation.
      text The content to translate in string format
      target_language Required. The BCP-47 language code to use for translation.
      source_language Optional. The BCP-47 language code of the input text.
    """

    client = translate.TranslationServiceClient()

    # TODO(developer): Uncomment and set the following variables
    # model_id = '[MODEL ID]'
    # text = 'Hello, world!'
    # target_language = 'fr'
    # source_language = 'en'
    # project_id = '[Google Cloud Project ID]'
    # location = 'global'
    contents = [text]
    parent = client.location_path(project_id, location)
    model_path = 'projects/{}/locations/{}/models/{}'.format(project_id, 'us-central1', model_id)
    response = client.translate_text(
        contents,
        target_language,
        model=model_path,
        source_language_code=source_language,
        parent=parent,
        mime_type='text/plain'  # mime types: text/plain, text/html
    )
    # Display the translation for each input text provided
    for translation in response.translations:
        print(u"Translated text: {}".format(translation.translated_text))

Ruby

Before trying this sample, follow the Ruby setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API Ruby API reference documentation .

require "google/cloud/translate"

client = Google::Cloud::Translate.new

project_id = "[Google Cloud Project ID]"
location_id = "[LOCATION ID]"
model_id = "[MODEL ID]"

# The `model` type requested for this translation.
model = "projects/#{project_id}/locations/#{location_id}/models/#{model_id}"
# The content to translate in string format
contents = ["Hello, world!"]
# Required. The BCP-47 language code to use for translation.
target_language = "fr"
# Optional. The BCP-47 language code of the input text.
source_language = "en"
# Optional. Can be "text/plain" or "text/html".
mime_type = "text/plain"
parent = client.class.location_path project_id, location_id

response = client.translate_text(
  contents, target_language, parent,
  source_language_code: source_language,
  model:                model,
  mime_type:            mime_type
)

# Display the translation for each input text provided
response.translations.each do |translation|
  puts "Translated text: #{translation.translated_text}"
end

Using the model parameter

REST & CMD LINE

You can specify which model to use for translation by using the model query parameter. Specify base to use the PBMT model, and nmt to use the NMT model. If you specify the NMT model in your request and the requested language translation pair is not supported for the NMT model, then the PBMT model is used.

The following sample shows how to use the model parameter in a translate request, with the example showing the selection of base.

Before using any of the request data below, make the following replacements:

  • project-number-or-id: your GCP project number or ID

HTTP method and URL:

POST https://translation.googleapis.com/v3/projects/project-number-or-id/locations/global:translateText

Request JSON body:

{
  "model": "projects/project-number-or-id/locations/global/models/general/base",
  "sourceLanguageCode": "en",
  "targetLanguageCode": "de",
  "contents": ["Come here!"]
}

To send your request, choose one of these options:

curl

Save the request body in a file called request.json, and execute the following command:

curl -X POST \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
https://translation.googleapis.com/v3/projects/project-number-or-id/locations/global:translateText

PowerShell

Save the request body in a file called request.json, and execute the following command:

$cred = gcloud auth application-default print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://translation.googleapis.com/v3/projects/project-number-or-id/locations/global:translateText " | Select-Object -Expand Content

You should receive a JSON response similar to the following:

{
  "translations": [
    {
      "translatedText": "Komm her!",
      "model": "projects/project-number/locations/global/models/general/base"
    }
  ]
}

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

Send feedback about...

Cloud Translation
Need help? Visit our support page.