Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call other Google APIs from a Cloud Function?

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?

like image 298
Sam McVeety Avatar asked Feb 11 '16 22:02

Sam McVeety


People also ask

Can a cloud function have multiple triggers?

You specify triggers as part of function deployment. You cannot bind the same function to more than one trigger at a time, but you can have the same event cause multiple functions to execute by deploying multiple functions with the same trigger settings.


1 Answers

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.

like image 183
Sam McVeety Avatar answered Sep 23 '22 13:09

Sam McVeety