I would like to call other Google APIs from my cloud function, for example, to write a file to Cloud Storage after receiving a message from Pubsub. How can I do this?
1 Answers
12
votes
You can use the google-cloud client library for Node.js to accomplish this. The same library is also available for Java, Python and Ruby.
For example in Node JS, you'll want to edit your package.json file accordingly:
{
"dependencies": {
"google-cloud": "*"
},
...
}
Then, in your code, you can simply invoke the relevant library. The following example just lists the buckets in the project:
var gcloud = require('google-cloud');
exports.helloworld = function(context, data) {
var gcs = gcloud.storage({projectId: '<PROJECT>'});
gcs.getBuckets(function(err, buckets) {
if (!err) {
buckets.forEach(function(bucket) {
console.log(bucket.name);
});
} else {
console.log('error: ' + err);
}
});
context.success();
}
You also shouldn't include the entire google-cloud npm module, but instead specify a specific sub-module, e.g. require('@google-cloud/storage') in the above example.