跳到主要內容

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: http://nodejs.org/
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 = 'https://www.googleapis.com/auth/bigquery https://www.googleapis.com/auth/cloud-platform';
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 = 'https://www.googleapis.com/bigquery/v2/projects/%s/queries'; //Query api url
    request({
      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
      console.log(JSON.stringify(d));
    });

  });
});

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. 

留言

這個網誌中的熱門文章

透過Google Apps Script結合Google Form做即時郵件通知

體驗過Google Apps Script的功能後,也發現他結合GmailApps的模組 GmailApps的應用可以用在表單填寫完成後,做發信的通知 例如您開立了一個訂購的表單,為了要在第一時間通知商家有訂單進入 就可以直接呼叫Gmail做發信的通知,讓手持Smart Phone的我們可以很快的知道生意上門了! 下面規劃三個function,其中: onCommit():為form commit時候觸發的function,需要掛載於form commit trigger上 jsonArrToTable():目的將json array解析成為一個Table getLastRowTable():目的將整個table的回傳過濾為剩下第一筆(表頭,含有Form的欄位說明)與最後一筆(原則上就是剛剛送出的那一筆表單) 完整程式碼如下: function onCommit(){   var sheet = SpreadsheetApp.getActiveSheet();   var rows = sheet.getDataRange();   var numRows = rows.getNumRows();   var values = rows.getValues();   var content = getLastRowTable(values);   var htmlBody = "Hi Admin: <br/><br/>有訂單拉,檢查一下吧! <br/><br/>" + content + '<br/><br/>Send by Google Apps';   GmailApp.sendEmail(     " your-email-address@gmail.com ",      "Order Confirm Notice",      htmlBody,      {from: ' from-email-...

Share a chrome plugin for manage google cloud platform

好玩意兒報報.... 同事的新作,把Google Project List在Chrome Plugin中! 對一次管理多個專案的人來說,真得超方便的拉! 下載: https://chrome.google.com/webstore/detail/gdclauncher/bicgkglnnilldakpenngnblekooejnpg 使用說明: 1. Use browser url bar to quick search: Type "gdcl" in browser Press "TAB" to start search Type the project id key word then select the search result... 2. Using quick launch bar... You can search by keyword or click project name to go to the project or gae link to go to gae or go to billing page....

Cloud Monitor嚐鮮

GCP上,我們非常想要的一個功能,終於問世.... Cloud Monitor來了!