Translating text (Advanced)

Cloud Translation - Advanced is optimized for customization and long form contentuse cases. Beyond the Neural Machine Translation (NMT) model, Advanced gives youaccess to the Translation LLM (Google's newest highest qualityLLM-style translation model) and the ability tocreate custom models.

Cloud Translation - Advanced also provides advanced text translation capabilitiesliketranslating documentsandcreating glossaries to ensure that yourdomain-specific terminology is translated correctly.

Note: Refer toMigrating to Cloud Translation - Advancedfor details regarding differences between Basic and Advanced.

Before you begin

Before you can start using the Cloud Translation API, you must have a project that hasthe Cloud Translation API enabled, and you must have the appropriate credentials. You canalso install client libraries for common programming languages to help you makecalls to the API. For more information, see theSetup page.

For instructions on installing the Google Cloud CLI, setting up a project with aservice account, and obtaining an access token, see theSetup page. If you plan to use aglossary or the batch features, you also need to create aCloud Storagebucket and grant your service account access toit.

Translate text

For translations, the input can be plain text or HTML. Cloud Translation APIdoesn't translate any HTML tags in the input, only text that appears between thetags. The output retains the (untranslated) HTML tags, with the translated textbetween the tags to the extent possible due to differences between the sourceand target languages.

Note: Cloud Translation API does not support input text that uses other markuplanguages such as XML. The result when attempting to translate content withother forms of markup is undefined.

Translate input strings

Note: Your project-number or project-id can be found in theGoogle Cloud Console.

REST

To translate text, make aPOST request and provide JSON in the request bodythat identifies the language to translate from (source_language_code), thelanguage to translate to (target_language_code), and the text to translate(contents). You can provide multiple strings of text to translate by includingthem in your JSON (see example). You identify your source and target languagesby using theirISO-639codes.

The following shows an example of aPOST request usingcurl or PowerShell. The example uses the access token for a service accountset up for the project using the Google CloudGoogle Cloud CLI.For instructions on installing the Google Cloud CLI,setting up a project with a service account, and obtaining an access token,see theSetup page.

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

  • PROJECT_NUMBER_OR_ID: the numeric or alphanumeric ID of your Google Cloud project

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, expand one of these options:

curl (Linux, macOS, or Cloud Shell)

Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login , or by usingCloud Shell, which automatically logs you into thegcloud CLI . You can check the currently active account by runninggcloud auth list.

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

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

PowerShell (Windows)

Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login . You can check the currently active account by runninggcloud auth list.

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

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "PROJECT_NUMBER_OR_ID" }

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": "Принеси мне кофе!",    }  ]}

Thetranslations array contains twotranslatedText fields with translationsprovided in the requestedtargetLanguageCodelanguage (ru: Russian). The translations are listed in the same order as thecorresponding source array in the request.

Go

Before trying this sample, follow theGo setup instructions in theCloud Translation quickstart using client libraries. For more information, see theCloud TranslationGo API reference documentation.

To authenticate to Cloud Translation, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.

// Imports the Google Cloud Translation libraryimport("context""fmt""io"translate"cloud.google.com/go/translate/apiv3""cloud.google.com/go/translate/apiv3/translatepb")functranslateText(wio.Writer,projectIDstring,sourceLangstring,targetLangstring,textstring)error{// projectID := "your-project-id"// sourceLang := "en-US"// targetLang := "fr"// text := "Text you wish to translate"// Instantiates a clientctx:=context.Background()client,err:=translate.NewTranslationClient(ctx)iferr!=nil{returnfmt.Errorf("NewTranslationClient: %w",err)}deferclient.Close()// Construct requestreq:=&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)iferr!=nil{returnfmt.Errorf("TranslateText: %w",err)}// Display the translation for each input text providedfor_,translation:=rangeresp.GetTranslations(){fmt.Fprintf(w,"Translated text: %v\n",translation.GetTranslatedText())}returnnil}

Java

Before trying this sample, follow theJava setup instructions in theCloud Translation quickstart using client libraries. For more information, see theCloud TranslationJava API reference documentation.

To authenticate to Cloud Translation, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.

// Imports the Google Cloud Translation library.importcom.google.cloud.translate.v3.LocationName;importcom.google.cloud.translate.v3.TranslateTextRequest;importcom.google.cloud.translate.v3.TranslateTextResponse;importcom.google.cloud.translate.v3.Translation;importcom.google.cloud.translate.v3.TranslationServiceClient;importjava.io.IOException;publicclassTranslateText{// Set and pass variables to overloaded translateText() method for translation.publicstaticvoidtranslateText()throwsIOException{// TODO(developer): Replace these variables before running the sample.StringprojectId="YOUR-PROJECT-ID";// Supported Languages: https://cloud.google.com/translate/docs/languagesStringtargetLanguage="your-target-language";Stringtext="your-text";translateText(projectId,targetLanguage,text);}// Translate text to target language.publicstaticvoidtranslateText(StringprojectId,StringtargetLanguage,Stringtext)throwsIOException{// 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(TranslationServiceClientclient=TranslationServiceClient.create()){// Supported Locations: `global`, [glossary location], or [model location]// Glossaries must be hosted in `us-central1`// Custom Models must use the same location as your model. (us-central1)LocationNameparent=LocationName.of(projectId,"global");// Supported Mime Types: https://cloud.google.com/translate/docs/supported-formatsTranslateTextRequestrequest=TranslateTextRequest.newBuilder().setParent(parent.toString()).setMimeType("text/plain").setTargetLanguageCode(targetLanguage).addContents(text).build();TranslateTextResponseresponse=client.translateText(request);// Display the translation for each input text providedfor(Translationtranslation:response.getTranslationsList()){System.out.printf("Translated text: %s\n",translation.getTranslatedText());}}}}

Node.js

Before trying this sample, follow theNode.js setup instructions in theCloud Translation quickstart using client libraries. For more information, see theCloud TranslationNode.js API reference documentation.

To authenticate to Cloud Translation, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.

/** * 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 libraryconst{TranslationServiceClient}=require('@google-cloud/translate');// Instantiates a clientconsttranslationClient=newTranslationServiceClient();asyncfunctiontranslateText(){// MIME type of the content to translate// Supported MIME types:// https://cloud.google.com/translate/docs/supported-formatsconstmimeType='text/plain';// Construct requestconstrequest={parent:`projects/${projectId}/locations/${location}`,contents:[text],mimeType:mimeType,sourceLanguageCode:'en',targetLanguageCode:'sr-Latn',};// Run requestconst[response]=awaittranslationClient.translateText(request);for(consttranslationofresponse.translations){console.log(`Translation:${translation.translatedText}`);}}translateText();

Python

Before trying this sample, follow thePython setup instructions in theCloud Translation quickstart using client libraries. For more information, see theCloud TranslationPython API reference documentation.

To authenticate to Cloud Translation, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.

importos# Import the Google Cloud Translation library.fromgoogle.cloudimporttranslate_v3PROJECT_ID=os.environ.get("GOOGLE_CLOUD_PROJECT")deftranslate_text(text:str="YOUR_TEXT_TO_TRANSLATE",source_language_code:str="en-US",target_language_code:str="fr",)->translate_v3.TranslationServiceClient:"""Translate Text from a Source language to a Target language.    Args:        text: The content to translate.        source_language_code: The code of the source language.        target_language_code: The code of the target language.            For example: "fr" for French, "es" for Spanish, etc.            Find available languages and codes here:            https://cloud.google.com/translate/docs/languages#neural_machine_translation_model    """# Initialize Translation client.client=translate_v3.TranslationServiceClient()parent=f"projects/{PROJECT_ID}/locations/global"# MIME type of the content to translate.# Supported MIME types:# https://cloud.google.com/translate/docs/supported-formatsmime_type="text/plain"# Translate text from the source to the target language.response=client.translate_text(contents=[text],parent=parent,mime_type=mime_type,source_language_code=source_language_code,target_language_code=target_language_code,)# Display the translation for the text.# For example, for "Hello! How are you doing today?":# Translated text: Bonjour comment vas-tu aujourd'hui?fortranslationinresponse.translations:print(f"Translated text:{translation.translated_text}")returnresponse

Additional languages

C#: Please follow theC# setup instructions on the client libraries page and then visit theCloud Translation reference documentation for .NET.

PHP: Please follow thePHP setup instructions on the client libraries page and then visit theCloud Translation reference documentation for PHP.

Ruby: Please follow theRuby setup instructions on the client libraries page and then visit theCloud Translation reference documentation for Ruby.

Translate text using a specific model

REST

You can specify which model to use for translation by using themodelquery parameter.

The following example translates text by using a custom model with a model ID of1395675701985363739. You can get the model ID for a custom model from the listof models in the Google Cloud console or from the API response or thecorresponding pantheon page when you train the model. To use the translationLLM, specifygeneral/translation-llm as the model ID. To use the customTranslation LLM (Public Preview), specifymodel/translation-llm-custom/{model-id}as the model ID.

Note: If you're specifying a custom model, the model must exist in the projectyou're using.

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

  • PROJECT_ID: Your Google Cloud project ID.
  • LOCATION: The region where the custom model is located, such asus-central1.

HTTP method and URL:

POST https://translation.googleapis.com/v3/projects/PROJECT_ID/locations/LOCATION:translateText

Request JSON body:

{  "model": "projects/PROJECT_ID/locations/LOCATION/models/1395675701985363739",  "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

Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login , or by usingCloud Shell, which automatically logs you into thegcloud CLI . You can check the currently active account by runninggcloud auth list.

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

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

PowerShell

Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login . You can check the currently active account by runninggcloud auth list.

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

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "PROJECT_ID" }

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

You should receive a JSON response similar to the following:

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

Go

Before trying this sample, follow theGo setup instructions in theCloud Translation quickstart using client libraries. For more information, see theCloud TranslationGo API reference documentation.

To authenticate to Cloud Translation, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.

import("context""fmt""io"translate"cloud.google.com/go/translate/apiv3""cloud.google.com/go/translate/apiv3/translatepb")// translateTextWithModel translates input text and returns translated text.functranslateTextWithModel(wio.Writer,projectIDstring,locationstring,sourceLangstring,targetLangstring,textstring,modelIDstring)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)iferr!=nil{returnfmt.Errorf("NewTranslationClient: %w",err)}deferclient.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)iferr!=nil{returnfmt.Errorf("TranslateText: %w",err)}// Display the translation for each input text providedfor_,translation:=rangeresp.GetTranslations(){fmt.Fprintf(w,"Translated text: %v\n",translation.GetTranslatedText())}returnnil}

Java

Before trying this sample, follow theJava setup instructions in theCloud Translation quickstart using client libraries. For more information, see theCloud TranslationJava API reference documentation.

To authenticate to Cloud Translation, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.

importcom.google.cloud.translate.v3.LocationName;importcom.google.cloud.translate.v3.TranslateTextRequest;importcom.google.cloud.translate.v3.TranslateTextResponse;importcom.google.cloud.translate.v3.Translation;importcom.google.cloud.translate.v3.TranslationServiceClient;importjava.io.IOException;publicclassTranslateTextWithModel{publicstaticvoidtranslateTextWithModel()throwsIOException{// TODO(developer): Replace these variables before running the sample.StringprojectId="YOUR-PROJECT-ID";// Supported Languages: https://cloud.google.com/translate/docs/languagesStringsourceLanguage="your-source-language";StringtargetLanguage="your-target-language";Stringtext="your-text";StringmodelId="YOUR-MODEL-ID";translateTextWithModel(projectId,sourceLanguage,targetLanguage,text,modelId);}// Translating Text with ModelpublicstaticvoidtranslateTextWithModel(StringprojectId,StringsourceLanguage,StringtargetLanguage,Stringtext,StringmodelId)throwsIOException{// 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(TranslationServiceClientclient=TranslationServiceClient.create()){// Supported Locations: `global`, [glossary location], or [model location]// Glossaries must be hosted in `us-central1`// Custom Models must use the same location as your model. (us-central1)Stringlocation="us-central1";LocationNameparent=LocationName.of(projectId,location);StringmodelPath=String.format("projects/%s/locations/%s/models/%s",projectId,location,modelId);// Supported Mime Types: https://cloud.google.com/translate/docs/supported-formatsTranslateTextRequestrequest=TranslateTextRequest.newBuilder().setParent(parent.toString()).setMimeType("text/plain").setSourceLanguageCode(sourceLanguage).setTargetLanguageCode(targetLanguage).addContents(text).setModel(modelPath).build();TranslateTextResponseresponse=client.translateText(request);// Display the translation for each input text providedfor(Translationtranslation:response.getTranslationsList()){System.out.printf("Translated text: %s\n",translation.getTranslatedText());}}}}

Node.js

Before trying this sample, follow theNode.js setup instructions in theCloud Translation quickstart using client libraries. For more information, see theCloud TranslationNode.js API reference documentation.

To authenticate to Cloud Translation, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.

/** * 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 libraryconst{TranslationServiceClient}=require('@google-cloud/translate');// Instantiates a clientconsttranslationClient=newTranslationServiceClient();asyncfunctiontranslateTextWithModel(){// Construct requestconstrequest={parent:`projects/${projectId}/locations/${location}`,contents:[text],mimeType:'text/plain',// mime types: text/plain, text/htmlsourceLanguageCode:'en',targetLanguageCode:'ja',model:`projects/${projectId}/locations/${location}/models/${modelId}`,};// Run requestconst[response]=awaittranslationClient.translateText(request);for(consttranslationofresponse.translations){console.log(`Translated Content:${translation.translatedText}`);}}translateTextWithModel();

Python

Before trying this sample, follow thePython setup instructions in theCloud Translation quickstart using client libraries. For more information, see theCloud TranslationPython API reference documentation.

To authenticate to Cloud Translation, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.

fromgoogle.cloudimporttranslatedeftranslate_text_with_model(text:str="YOUR_TEXT_TO_TRANSLATE",project_id:str="YOUR_PROJECT_ID",model_id:str="YOUR_MODEL_ID",)->translate.TranslationServiceClient:"""Translates a given text using Translation custom model."""client=translate.TranslationServiceClient()location="us-central1"parent=f"projects/{project_id}/locations/{location}"model_path=f"{parent}/models/{model_id}"# Supported language codes: https://cloud.google.com/translate/docs/languagesresponse=client.translate_text(request={"contents":[text],"target_language_code":"ja","model":model_path,"source_language_code":"en","parent":parent,"mime_type":"text/plain",# mime types: text/plain, text/html})# Display the translation for each input text providedfortranslationinresponse.translations:print(f"Translated text:{translation.translated_text}")returnresponse

Additional languages

C#: Please follow theC# setup instructions on the client libraries page and then visit theCloud Translation reference documentation for .NET.

PHP: Please follow thePHP setup instructions on the client libraries page and then visit theCloud Translation reference documentation for PHP.

Ruby: Please follow theRuby setup instructions on the client libraries page and then visit theCloud Translation reference documentation for Ruby.

Transliteration

Preview

This feature is subject to the "Pre-GA Offerings Terms" in the General Service Terms section of theService Specific Terms. Pre-GA features are available "as is" and might have limited support. For more information, see thelaunch stage descriptions.

Transliteration is a configuration setting in thetranslateText method. Whenyou enable transliteration, you translate romanized text (Latin script) directlyto a target language. For example, you can translate romanized Japanese textdirectly to English, Spanish, or Chinese. The resulting translations are in thetarget language's writing system.

In your transliteration requests, include only romanized text. If you mixromanized text with non-romanized text, Cloud Translation can't ensure consistentand proper translations.

Considerations

Transliteration differs from standard text translations in the following ways:

  • Transliteration supports a limited number of languages. For more information,see theTransliteration column on theSupportedlanguages page.
  • The MIME type must betext/plain. HTML is not supported.
  • Transliteration is supported by the default standard model only. Custom modelsaren't supported.
  • Transliteration has a lower default content quota. For more information, seeQuotas and limits.

REST

Set thetransliteration_config field on thetranslateTextmethod.

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

  • PROJECT_NUMBER_OR_ID: The numeric or alphanumeric ID of your Google Cloud project.
  • LOCATION: Region where you want to run this operation. For example,us-central1.
  • SOURCE_LANGUAGE: (Optional) The language code of the input text. If known, set to one of the language codes listed inLanguage support.
  • TARGET_LANGUAGE: The target language to translate the input text to. Set to one of the language codes listed inLanguage support.
  • SOURCE_TEXT: Romanized text in the source language to translate.

HTTP method and URL:

POST https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID/locations/LOCATION:translateText

Request JSON body:

{  "source_language_code": "SOURCE_LANGUAGE",  "target_language_code": "TARGET_LANGUAGE",  "contents": "SOURCE_TEXT",  "mime_type": "text/plain",  "transliteration_config": { "enable_transliteration": true}}

To send your request, expand one of these options:

curl (Linux, macOS, or Cloud Shell)

Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login , or by usingCloud Shell, which automatically logs you into thegcloud CLI . You can check the currently active account by runninggcloud auth list.

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

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

PowerShell (Windows)

Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login . You can check the currently active account by runninggcloud auth list.

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

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "PROJECT_NUMBER_OR_ID" }

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/LOCATION:translateText" | Select-Object -Expand Content

You should receive a JSON response similar to the following:

{  "translations": [    {      "translatedText": "TRANSLATED_TEXT",    }  ]}

Additional resources

  • For help on resolving common issues or errors, see theTroubleshooting page.

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-10-30 UTC.