1. 程式人生 > 實用技巧 >使用Google Cloud API進行開發

使用Google Cloud API進行開發

Google提供的api現已全部整合到了google clouds,使用起來比較麻煩。本文介紹如何使用Google的api進行開發

以Google Translation 谷歌翻譯為例

第一步

建立一個Google賬號,然後登陸https://console.cloud.google.com/

點建立專案

然後,選擇你的建立專案

第二步

點選導航選單,選擇API和服務 -> 庫

然後搜尋google translate,啟用它。

第三步

選擇API和服務 -> 憑據

  1. 在 Cloud Console 中,轉到建立服務帳號金鑰頁面。

    轉到“建立服務帳號金鑰”頁面
  2. 從服務帳號列表中,選擇新的服務帳號。
  3. 在服務帳號名稱欄位中,輸入一個名稱。
  4. 從角色列表中,選擇Project>Owner。

  5. 點選建立。包含金鑰的 JSON 檔案就會下載到計算機。

第四步

設定google app環境變數

Google api每次呼叫會檢驗憑證,需要在環境變數中設定目錄到第三步所下載的Json檔案

mac/linux:

$export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/my-key.json"

windows:

env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\my-key.json
"

windows需要重啟生效

第五步

測試API是否可以使用

本文用Nodejs測試

npm安裝googletrans

npm install @google-cloud/translate

測試程式碼

 1 // Imports the Google Cloud client library
 2 const {Translate} = require('@google-cloud/translate').v2;
 3 
 4 // Instantiates a client
 5 const translate = new Translate();
 6 
 7 async function quickStart() {
8 // The text to translate 9 const text = 'Hello, world!'; 10 11 // The target language 12 const target = 'ru'; 13 14 // Translates some text into Russian 15 const [translation] = await translate.translate(text, target); 16 console.log(`Text: ${text}`); 17 console.log(`Translation: ${translation}`); 18 } 19 20 quickStart();

如果googletrans沒有成功輸出,則報錯,檢查前面的步驟