首页 > 技术文章 > 使用Google Cloud API进行开发

Asp1rant 2020-12-14 20:22 原文

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没有成功输出,则报错,检查前面的步骤


 

推荐阅读