Core Java

How to Use Google Translate API with Java

The Google Cloud Translation API is a powerful tool that enables developers to programmatically translate text between thousands of language pairs, detect languages, and customize translation behavior using glossaries. Let us delve into understanding how to use the Java Google Translate API for building multilingual applications.

1. Introduction

Google Cloud Translation API offers pre-trained models that provide fast and dynamic translation. It supports over a hundred languages and enables both simple and advanced use cases depending on your project requirements.

The API is available in two versions:

  • Basic: Provides essential features like real-time translation and automatic language detection. Ideal for quick implementations.
  • Advanced (v3): Offers extended capabilities such as glossary support, custom model selection, batch translation, and fine-grained control over translation behavior.

1.1 Common Pitfalls

While working with the Google Translate API using Java, developers might encounter some challenges. These include:

  • Invalid Credentials: Ensure the service account JSON file path is correctly set and permissions are enabled.
  • Missing Dependencies: The `google-cloud-translate` artifact may require additional dependencies depending on your environment. Use a BOM (`Bill of Materials`) or explicitly manage versions.
  • Region Mismatch: If you create resources like glossaries in a specific region (e.g., us-central1), ensure your translation requests also target the same region.
  • Rate Limits: Google Cloud imposes quota limits. These can result in HTTP 429 errors if your app sends too many requests.
  • Glossary Not Found: Always double-check your glossary ID and region. The glossary must exist before referencing it in requests.

1.2 Best Practices

To get the most out of the Google Cloud Translation API, consider the following practices:

  • Use Glossaries Strategically: Use custom glossaries for product names, brand terms, or domain-specific jargon to maintain consistency.
  • Batch Requests: For cost and speed efficiency, batch multiple strings into a single API call instead of sending them one at a time.
  • Handle Failures Gracefully: Implement retries with exponential backoff when dealing with network errors or quota limitations.
  • Monitor Quotas: Set up alerts on your GCP dashboard to monitor usage and avoid unexpected limits.
  • Security First: Never hardcode credentials in source code. Use environment variables and Google Cloud IAM roles for secure access control.

1.3 Use Cases

  • Multilingual support in websites and applications to enhance user experience for global audiences
  • Translating customer support tickets or live chat messages in real-time for international support teams
  • Automatically translating product descriptions, reviews, and user-generated content in e-commerce platforms
  • Localizing mobile apps and games for multiple regions with minimal manual effort
  • Enabling content creators and bloggers to reach wider audiences by translating blog posts or articles
  • Converting internal company documentation into multiple languages for global teams
  • Powering real-time translation features in video conferencing and collaboration tools
  • Integrating language detection and translation in AI chatbots and virtual assistants
  • Translating survey responses or feedback forms from users around the world
  • Processing and translating text data at scale in data analytics and natural language processing workflows

1.4 Pricing Overview

Google Cloud Translation API follows a pay-as-you-go model. Charges are typically based on:

  • Number of characters translated
  • Batch vs. real-time translation
  • Glossary usage (Advanced tier)

You can review pricing details on the official pricing page. It’s recommended to estimate your monthly costs using Google Cloud’s Pricing Calculator.

2. Implementing Google Translate API

In the following sections, we will explore how to set up the Google Cloud project, authenticate API requests, and implement translation features using Java.

2.1 Setup and Dependencies

To get started with the Java Google Translate API, make sure your project is set up with the necessary dependencies and authentication. Add the following dependency to your pom.xml if you’re using Maven:

1
2
3
4
5
<dependency>
  <groupId>com.google.cloud</groupId>
  <artifactId>google-cloud-translate</artifactId>
  <version>use__latest__jar__version</version>
</dependency>

Set your credentials path as an environment variable to allow the SDK to authenticate:

1
export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/service-account-key.json"

2.2 Code Example – Translating Text

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import com.google.cloud.translate.v3.*;
import java.io.IOException;
 
public class GoogleTranslateFullExample {
 
    private static final String PROJECT_ID = "your-project-id"; // Replace with your actual Project ID
    private static final String LOCATION = "global";
 
    public static void main(String[] args) throws IOException {
        try (TranslationServiceClient client = TranslationServiceClient.create()) {
            LocationName parent = LocationName.of(PROJECT_ID, LOCATION);
 
            // 1. Detect Language
            String textToDetect = "Bonjour tout le monde";
            DetectLanguageRequest detectRequest = DetectLanguageRequest.newBuilder()
                .setParent(parent.toString())
                .setMimeType("text/plain")
                .setContent(textToDetect)
                .build();
            DetectLanguageResponse detectResponse = client.detectLanguage(detectRequest);
            String detectedLang = detectResponse.getLanguages(0).getLanguageCode();
            System.out.println("Detected Language: " + detectedLang);
 
            // 2. Translate Single Sentence
            String singleText = "Hello, how are you?";
            TranslateTextRequest singleTranslateRequest = TranslateTextRequest.newBuilder()
                .setParent(parent.toString())
                .addContents(singleText)
                .setMimeType("text/plain")
                .setSourceLanguageCode("en")
                .setTargetLanguageCode("es") // English to Spanish
                .build();
            TranslateTextResponse singleTranslateResponse = client.translateText(singleTranslateRequest);
            System.out.println("Translated: " + singleTranslateResponse.getTranslations(0).getTranslatedText());
 
            // 3. Translate Multiple Sentences
            TranslateTextRequest multiRequest = TranslateTextRequest.newBuilder()
                .setParent(parent.toString())
                .addContents("Good morning")
                .addContents("What is your name?")
                .setMimeType("text/plain")
                .setSourceLanguageCode("en")
                .setTargetLanguageCode("fr")
                .build();
            TranslateTextResponse multiResponse = client.translateText(multiRequest);
            System.out.println("Multiple Translations:");
            for (Translation translation : multiResponse.getTranslationsList()) {
                System.out.println("- " + translation.getTranslatedText());
            }
 
            // 4. List Supported Languages
            GetSupportedLanguagesRequest langRequest = GetSupportedLanguagesRequest.newBuilder()
                .setParent(parent.toString())
                .setDisplayLanguageCode("en")
                .build();
            SupportedLanguages languages = client.getSupportedLanguages(langRequest);
            System.out.println("\nSupported Languages:");
            for (SupportedLanguage lang : languages.getLanguagesList().subList(0, 5)) { // Show first 5
                System.out.printf("- %s (%s)%n", lang.getDisplayName(), lang.getLanguageCode());
            }
        }
    }
}

2.2.1 Code Explanation

The program begins by importing required classes from the com.google.cloud.translate.v3 package and defining two constants: PROJECT_ID (your Google Cloud project ID) and LOCATION (typically set to global). Inside the main method, a TranslationServiceClient is created using a try-with-resources block, ensuring it is properly closed after use. This client is responsible for sending translation-related requests to the Google Cloud Translation service. To detect the language of a given text (e.g., “Bonjour tout le monde”), the code constructs a DetectLanguageRequest by setting the parent path, MIME type (plain text), and the content to analyze. The client.detectLanguage() method is then used to send the request. The response returns a list of detected languages ranked by confidence. The top language’s code (like fr for French) is printed to the console. To perform translation, the code builds a TranslateTextRequest by specifying the parent path, source language (en), target language (es), MIME type, and the content to translate (e.g., “Hello, how are you?”). The request is sent using client.translateText(). The translated result is extracted from the response and printed. This shows how to translate individual strings from English to another language. This part demonstrates translating multiple phrases at once. The TranslateTextRequest is built with multiple addContents() calls, each adding a different English phrase (e.g., “Good morning”, “What is your name?”). The source and target languages are again set (English to French). The API responds with a list of translated phrases, which are iterated and printed. This method is useful for batch translation scenarios. Finally, the code lists the languages supported by the Translation API. It creates a GetSupportedLanguagesRequest with the display language set to English. The client retrieves a list of SupportedLanguage objects, which contain both the display name and language code. The sample prints the first five languages to showcase the multilingual capabilities of the API. This can be used to dynamically populate language dropdowns in applications.

2.2.2 Code Output

Upon execution, the code produces the following output:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
Detected Language: fr
 
Translated: Hola, ¿cómo estás?
 
Multiple Translations:
- Bonjour
- Quel est ton nom ?
 
Supported Languages:
- Afrikaans (af)
- Albanian (sq)
- Amharic (am)
- Arabic (ar)
- Armenian (hy)

2.3 Code Example – Translate Using Custom Glossary

A Custom Glossary helps override default translation behavior for domain-specific terminology.

Start by creating a glossary using the Google Cloud Console or CLI, and then integrate it into your project by following these steps:

01
02
03
04
05
06
07
08
09
10
11
12
-- Step 1: Use the following glossary file (csv)
CPU,シーピーユー
RAM,ラム
 
-- Step 2: Place it in a bucket like `gs://your-bucket-name/glossaries/tech_terms.csv`
 
-- Step 3: Create Glossary via CLI
gcloud translation glossaries create your-glossary-id \
  --source-language=en --target-language=ja \
  --input-uri=gs://your-bucket-name/glossaries/tech_terms.csv \
  --project=your-project-id \
  --location=us-central1

Next, we’ll include the glossary ID in the translation request.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public static void translateUsingGlossary(TranslationServiceClient client, String projectId, String location, String glossaryId) {
    String glossaryInput = "CPU"; // This term should exist in the glossary
 
    try {
        LocationName parent = LocationName.of(projectId, location);
 
        // Build glossary config
        TranslateTextGlossaryConfig glossaryConfig = TranslateTextGlossaryConfig.newBuilder()
            .setGlossary(GlossaryName.of(projectId, location, glossaryId).toString())
            .build();
 
        // Build request with glossary
        TranslateTextRequest glossaryRequest = TranslateTextRequest.newBuilder()
            .setParent(parent.toString())
            .addContents(glossaryInput)
            .setMimeType("text/plain")
            .setSourceLanguageCode("en")
            .setTargetLanguageCode("ja") // English to Japanese
            .setGlossaryConfig(glossaryConfig)
            .build();
 
        // Send request
        TranslateTextResponse glossaryResponse = client.translateText(glossaryRequest);
 
        // Print results
        System.out.println("\nGlossary Translation:");
        for (Translation translation : glossaryResponse.getGlossaryTranslationsList()) {
            System.out.println("- Glossary term translated: " + translation.getTranslatedText());
        }
 
    } catch (Exception e) {
        System.err.println("Glossary translation failed: " + e.getMessage());
    }
}

2.3.1 Code Explanation and Output

The translateUsingGlossary method demonstrates how to use a custom glossary with the Google Cloud Translate API in a Java application. This method accepts a pre-configured TranslationServiceClient, project ID, location (e.g., us-central1), and a glossary ID. The input term "CPU" is assumed to be defined in the glossary file (e.g., mapped to "シーピーユー" in Japanese). The method constructs the glossary resource path using GlossaryName.of() and sets it into a TranslateTextGlossaryConfig. A TranslateTextRequest is built with source language en and target language ja, along with the glossary configuration. The client then calls translateText(), and the translated result is printed using the getGlossaryTranslationsList() method from the response. This allows developers to enforce consistent translations for domain-specific terminology across applications. If the glossary is properly set up in Google Cloud Console and the term exists, the output would be: Glossary Translation:- Glossary term translated: シーピーユー.

3. Conclusion

Google Translate API offers a powerful suite of tools for translating and detecting language in your Java applications. From single-line translations to using custom glossaries for domain-specific accuracy, it is ideal for enterprise-grade language solutions. With just a few lines of code and proper setup, your application can support users across the globe.

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest


This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button