Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass an api key to the Google Cloud Vision NodeJS API

const vision = require('@google-cloud/vision');

All examples I can find for the NodeJS Cloud Vision API either use credentials they get from environment variables, or use a JSON credentials file, but I'd like to call the API using an api key. How do I do that?

like image 994
bigblind Avatar asked Oct 11 '18 19:10

bigblind


2 Answers

I had the same problem to solve. After a bit of digging, I got a bellow solution worked in singe gunfire.

Make sure the required node module is installed :

npm install @google-cloud/vision



const vision = require('@google-cloud/vision');
const {GoogleAuth, grpc} = require('google-gax');

const apiKey = '**********';

function getApiKeyCredentials() {
  const sslCreds = grpc.credentials.createSsl();
  const googleAuth = new GoogleAuth();
  const authClient = googleAuth.fromAPIKey(apiKey);
  const credentials = grpc.credentials.combineChannelCredentials(
    sslCreds,
    grpc.credentials.createFromGoogleCredential(authClient)
  );
  return credentials;
}


async function main(fileName) {
  const sslCreds = getApiKeyCredentials();
  const client = new vision.ImageAnnotatorClient({sslCreds});
  const [result] = await client.faceDetection(fileName); 
  const faces = result.faceAnnotations;

  //your custom code 

}

Code Sample

Question originally answered here

NodeJS Reference for Vision API

like image 168
Asraful Avatar answered Nov 15 '22 08:11

Asraful


If you are using the client library, you will have to authenticate using the credentials from the JSON file or the environment variable. If you would like to use the API key, you would have to send a POST request to the API directly (read more about authenticating Vision API here). An example cURL command would look like this:

curl -s -H 'Content-Type: application/json'   'https://vision.googleapis.com/v1/images:annotate?key=XXXXXXX_MY_API_KEYXXXXXXXXXXXXXXX'   -d ' {
  "requests": [
    {
      "image": {
        "source": {
          "imageUri": "gs://bucketname/objectname.jpg"
        }
      },
      "features": [
        {
          "type": "LABEL_DETECTION",
          "maxResults": 1
        }
      ]
    }
  ]
} '
like image 3
Philipp Sh Avatar answered Nov 15 '22 08:11

Philipp Sh