Connect Cloud Platform BigQuery using Node.js

This is a demo for using Node.js to query BitQuery API. We know Node.js has fast way to connect to RESTful API. In this example, we use gapitoken module to retrieve the auth token, and use request module to connect the RESTful API. Auth is the important thing in Google's API... If you pass this gate, you can access almost all Google API!

Step 1: Create a service account from Google API console

Save the client_secrets.json to project folder

Step 2: Generate PEM key from P12 key

$ openssl pkcs12 -in privatekey.p12 -out privatekey.pem -nocerts
$ openssl rsa -in privatekey.pem -out key.pem

Put the pem key to your project

Step 3: Prepare Node.js environment
a. Download and install Node.js runtime:
b. Install project dependency

$ npm install gapitoken request

Step 4: Sample Code (sample.js)

var GAPI = require('gapitoken')
  , request = require('request')
  , fs = require('fs')
  , util = require('util')
//From admin console, create a service account, save the client_secrets.json and it's key
var client_secrets = JSON.parse(fs.readFileSync(__dirname + '/client_secrets.json','utf8'));
//Project setting
var iss = client_secrets.web.client_email; 
//BigQuery scopes list
var bq_scope = '';
var project = 'mitac-cp300';
var opts = {
    iss: iss,
    scope: bq_scope,
    keyFile: __dirname + '/key.pem'  //pem key path
 * Translate p12 to pem
var _token = '';
var gapi = new GAPI(opts, function(err) {
  if (err) return console.log(err);
  gapi.getToken(function(err, token) {
    if (err)  return console.log(err);
    _token = token;
    var bqurl = ''; //Query api url
      url: util.format(bqurl,project),
      method: 'POST',
      headers: {
        "Authorization": "Bearer " + _token
      json: {
        query: 'select * from cp300.GetAnimals' //Here, you can put your query here...
    }, function(e,r,d){
      if(e) console.log(e);
      //Print the query result


Step 5: Run it..

$ node  sample.js

In this case, result will in a json string format. This is the default output of query api using json format.