javagoogle-apigoogle-translategoogle-api-java-clientgoogle-translator-toolkit

Missing a valid API key about Google Translation API Client issue?


I follow the https://cloud.google.com/translate/docs/reference/libraries#client-libraries-usage-java to get started java client demo. I have already set authentication json file to the environment variable GOOGLE_APPLICATION_CREDENTIALS. However, I got the translateException when I run java sample code.

Exception in thread "main" com.google.cloud.translate.TranslateException: The request is missing a valid API key.
at com.google.cloud.translate.spi.v2.HttpTranslateRpc.translate(HttpTranslateRpc.java:61)
at com.google.cloud.translate.spi.v2.HttpTranslateRpc.translate(HttpTranslateRpc.java:144)
at com.google.cloud.translate.TranslateImpl$4.call(TranslateImpl.java:113)
at com.google.cloud.translate.TranslateImpl$4.call(TranslateImpl.java:110)
Caused by: 
com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 
Forbidden
{
  "code" : 403,
  "errors" : [ {
  "domain" : "global",
  "message" : "The request is missing a valid API key.",
  "reason" : "forbidden"
} ],
  "message" : "The request is missing a valid API key.",
  "status" : "PERMISSION_DENIED"
}

The doc shows that this JSON file contains key infomation.

The sample code is shown

    // Instantiates a client
    Translate translate = TranslateOptions.getDefaultInstance().getService();
    // The text to translate
    String text = "Hello, world!";
    // Translates some text into Russian
    Translation translation =
        translate.translate(
            text,
            TranslateOption.sourceLanguage("en"),
            TranslateOption.targetLanguage("ru"));
    System.out.printf("Text: %s%n", text);
    System.out.printf("Translation: %s%n", translation.getTranslatedText());

I have no idea how to set api-key. It still doesn't work after I set environment variable for key and credentials.

enter image description here


Solution

  • To make authenticated requests to Google Translation, you must create a service object with credentials or use an API key. The simplest way to authenticate is to use Application Default Credentials. These credentials are automatically inferred from your environment, so you only need the following code to create your service object:

    Translate translate = TranslateOptions.getDefaultInstance().getService();
    

    I have personally never gotten that to work.

    This code can be also used with an API key. By default, an API key is looked for in the GOOGLE_API_KEY environment variable. Once the API key is set, you can make API calls by invoking methods on the Translation service created via TranslateOptions.getDefaultInstance().getService().

    Sample project here