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

2

6

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?

Straightedge answered 11/10, 2018 at 19:49 Comment(0)
M
8

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

Marlinemarlinespike answered 1/10, 2020 at 21:50 Comment(0)
P
4

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
        }
      ]
    }
  ]
} '
Plumber answered 17/10, 2018 at 13:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.