Google Vision API java client: how to set API credentials explicitly in code(without using environment variable)

809 views Asked by At

I'm trying to integrate my project with Google Vision API

Here is the maven dependency for you to check the client version I'm trying to integrate with:

<dependency>
   <groupId>com.google.cloud</groupId>
   <artifactId>google-cloud-vision</artifactId>
   <version>1.51.0</version>
</dependency>

The way the documentation offers to set the API authentication credentials is the following:

Set the environment variable GOOGLE_APPLICATION_CREDENTIALS to the 
file path of the JSON file that contains your service account key

I'm wondering if there is a way to set the credentials explicitly in code as that is more convenient than setting environment variables in each and every environment we are running our project on.

As I know for a former client version 1.22 that was possible doing the following:

def credentialFile = this.class.classLoader
.getResource(grailsApplication.config.credentialsFile)
GoogleCredential credential = 
GoogleCredential.fromStream(credentialFile.openStream())
        .createScoped(grailsApplication.config.googleScope)

Vision vision = new 
Vision.Builder(GoogleNetHttpTransport.newTrustedTransport(), 
jsonFactory, credential).build()

But for the new client API I was not able to find the way and documentation doesn't say anything in that regards.

1

There are 1 answers

0
Sérgio Sousa On

It's possible: Create an ImageAnnotatorSettings like:

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

Add this to your client and voilá!