Using the Google Cloud Vision API with a simple API key
Asked Answered
S

1

9

I am using the Google Cloud Vision Java API client documented here: https://cloud.google.com/vision/docs/reference/libraries.

The following quickstart code works fine if I use the implicit default credentials by setting the GOOGLE_APPLICATION_CREDENTIALS environment variable to reference a json file for the right "service account".

// Imports the Google Cloud client library
import com.google.cloud.vision.spi.v1.ImageAnnotatorClient;
import com.google.cloud.vision.v1.AnnotateImageRequest;
import com.google.cloud.vision.v1.AnnotateImageResponse;
import com.google.cloud.vision.v1.BatchAnnotateImagesResponse;

...


public class QuickstartSample {
  public static void main(String... args) throws Exception {
    // Instantiates a client
    ImageAnnotatorClient vision = ImageAnnotatorClient.create();

    ...

    BatchAnnotateImagesResponse response = vision.batchAnnotateImages(requests);
    List<AnnotateImageResponse> responses = response.getResponsesList();

    ...
  }
}

However, I want to authenticate to the API using a simple (single-string) API key rather than a service account, and I cannot find documentation explaining how to do that through this java library. Is it possible?

Slagle answered 2/5, 2017 at 23:3 Comment(4)
same problem here, did you found a solution?Hereafter
@JohnnyAW: I don't think it can be done. My work-around has been to use the REST API (cloud.google.com/vision/docs/reference/rest/v1/images/annotate) instead of the RPC API. It's not so hard to build the JSON fragments using a StringBuilder and then parse the response using GSON or whatever.Slagle
I'm also looking for this. Is strange that it's so simple using REST calls but not with the Java library.Fanestil
maybe this might help: it's a code sample for Android (which uses Java), and uses a simple API key: github.com/GoogleCloudPlatform/cloud-vision/tree/master/androidGittern
R
0

It's possible: Create an ImageAnnotatorSettings like:

ImageAnnotatorSettings ias = ImageAnnotatorSettings.newBuilder()
        .setCredentialsProvider(
                FixedCredentialsProvider.create(#InputStream of your json key#)
        )
        .build();

replace your line

ImageAnnotatorClient vision = ImageAnnotatorClient.create();

with

ImageAnnotatorClient vision = ImageAnnotatorClient.create(ias);

Give it a try!

Rebuke answered 25/2, 2019 at 1:9 Comment(2)
Unfortunately, this code no longer works with the latest version e.g. newBuilder() no longer existsSchoolman
Not possible anymore according to github.com/googleapis/google-cloud-java/issues/3763Clayton

© 2022 - 2024 — McMap. All rights reserved.