Translates

How to say it in other languages, and what words mean

Spanish

Google Cloud Translation API in Java: Step-by-Step

· 5 min read · Spanish

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

This guide shows you how to call the Google Cloud Translation API from a Java application. You'll be able to translate text between dozens of languages with a few lines of code. Before starting, you need a Google Cloud project with billing enabled, the Cloud Translation API activated, and a service account key file for authentication. If you haven't done that yet, the steps below include where to get each piece.

What You'll Need

  • Java 8 or later installed (check with java -version)
  • Maven or Gradle for dependency management
  • A Google Cloud project with billing enabled
  • The Cloud Translation API enabled in that project
  • A service account JSON key file (download from Google Cloud Console)
  • Google Cloud SDK (optional, but helpful for authentication)

Step-by-Step

  1. Set up your Google Cloud project. Go to the Google Cloud Console, create a new project or select an existing one. Make sure billing is enabled for the project.
  2. Enable the Cloud Translation API. In the Console, navigate to "APIs & Services" > "Library", search for "Cloud Translation API", and click "Enable".
  3. Create a service account and download the key. Go to "APIs & Services" > "Credentials", click "Create Credentials" > "Service Account". Give it a name (e.g., "translation-app"), assign the role "Cloud Translation API User" (or a custom role with translation permissions), and click "Done". Then click on the service account, go to the "Keys" tab, click "Add Key" > "Create New Key", choose JSON, and download the file. Keep it secure—never commit it to version control.
  4. Set the environment variable for authentication. In your terminal, export the path to your key file: export GOOGLE_APPLICATION_CREDENTIALS="/path/to/your-key.json". On Windows, use set GOOGLE_APPLICATION_CREDENTIALS=C:\path\to\your-key.json in Command Prompt or $env:GOOGLE_APPLICATION_CREDENTIALS="C:\path\to\your-key.json" in PowerShell.
  5. Create a new Java project. If using Maven, create a pom.xml file. If using Gradle, create a build.gradle file. Add the necessary dependencies (see next step).
  6. Add the Google Cloud Translation dependency. For Maven, add to pom.xml:
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>google-cloud-translate</artifactId>
      <version>2.4.0</version>
    </dependency>
    For Gradle, add to build.gradle: implementation 'com.google.cloud:google-cloud-translate:2.4.0'.
  7. Write a simple Java class to translate text. Create a file named TranslateText.java with the following code:
    import com.google.cloud.translate.Translate;
    import com.google.cloud.translate.TranslateOptions;
    import com.google.cloud.translate.Translation;
    
    public class TranslateText {
        public static void main(String[] args) {
            // Instantiates a client
            Translate translate = TranslateOptions.getDefaultInstance().getService();
    
            // The text to translate
            String text = "Hello, world!";
    
            // Translates the text into French
            Translation translation = translate.translate(text,
                Translate.TranslateOption.targetLanguage("fr"));
    
            System.out.printf("Text: %s%n", text);
            System.out.printf("Translation: %s%n", translation.getTranslatedText());
        }
    }
  8. Run the code. If using Maven, run mvn compile exec:java -Dexec.mainClass=TranslateText. If using Gradle, run gradle run (make sure you have the application plugin configured). You should see the French translation "Bonjour le monde !" printed.
  9. Handle multiple languages and options. You can specify source and target languages using language codes like "en", "es", "ja", etc. Use Translate.TranslateOption.sourceLanguage("en") and targetLanguage("es"). You can also set the MIME type (text/plain or text/html) with Translate.TranslateOption.format("text").
  10. Batch translation. To translate multiple strings at once, pass a list to translate.translate(List<String>, options). The method returns a list of Translation objects.

Common Mistakes

  • Forgetting to set the environment variable. Without GOOGLE_APPLICATION_CREDENTIALS, the client library will fail with authentication errors.
  • Using the wrong language code. For example, "fr" for French, not "fra". Check the list of supported languages in the documentation.
  • Not enabling billing. The API requires billing to be enabled on the project; otherwise you'll get a 403 or 429 error.
  • Hardcoding the key file path in code. This is insecure and breaks when deployed. Always use the environment variable or a secure secret manager.
  • Using an outdated dependency version. Check the latest version of google-cloud-translate on Maven Central to avoid bugs.

Tips

  • Use the Translate.TranslateOption.format("html") if you're translating HTML content to preserve tags.
  • For production, consider using the TranslateOptions.Builder() to set a custom project ID or credentials explicitly.
  • Handle exceptions like com.google.api.gax.rpc.PermissionDeniedException gracefully in your code.
  • Test with small text first to verify your setup, then scale up.
  • Use the detectLanguage method if you don't know the source language.

Troubleshooting

  • Authentication error (401/403): Make sure the environment variable is set correctly and the service account has the right permissions. Try running gcloud auth application-default login for local testing.
  • Quota exceeded (429): You might have hit the free tier limit. Check your usage in the Cloud Console and consider upgrading or waiting.
  • Dependency issues: If you get NoClassDefFoundError, run mvn clean install or gradle clean build to refresh dependencies.
  • Invalid argument (400): Check that your language codes are correct and that the text is not empty.
  • Slow response: If you're translating large batches, consider using the async client or splitting into smaller chunks.

Frequently Asked Questions

How much does the Cloud Translation API cost?

The first 500,000 characters per month are free for the standard edition. After that, it's $20 per million characters. Check the official pricing page for the latest details.

Can I translate PDF or Word documents directly?

No, the API accepts plain text or HTML. You'd need to extract text from those documents first using a separate library.

How many languages are supported?

As of this writing, over 100 languages are supported. You can get the full list by calling the getSupportedLanguages() method.

Is the translation accurate?

The API uses Google's neural machine translation, which is quite accurate for common language pairs, but it's not perfect. For professional content, consider human review.

Can I use this API offline?

No, it requires an internet connection because the translation is processed on Google's servers.

How do I set a custom timeout for requests?

You can configure the TranslateOptions with a custom RetrySettings or use the underlying gRPC channel configuration.