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?
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
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
}
]
}
]
} '
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With