如何使用OAuth 2.0为Ruby中的google预测API进行授权?

我试图简单地向谷歌的托管模型sample.sentiment发送请求。 我无法弄清楚如何通过谷歌使用Oauth 2.0进行授权,而且我将获得无穷无尽的时间。 如果你可以提供我的代码,这将是有帮助的。 这就是我的工作方式。

client = Google::APIClient.new({:application_name => "CCE",:application_version => "1.0"} ) plus = client.discovered_api('prediction') # Initialize OAuth 2.0 client client.authorization.client_id = 'my client id' client.authorization.client_secret = 'my client secret' client.authorization.redirect_uri = 'my callback url' client.authorization.scope = 'https://www.googleapis.com/auth/prediction' # Request authorization redirect_uri = client.authorization.authorization_uri # Wait for authorization code then exchange for token client.authorization.code = '....' client.authorization.fetch_access_token! # Make an API call result = client.execute( :api_method => plus.activities.list, :parameters => {'hostedModelName' => 'sample.sentiment', 'userId' => ''}) 

`

好吧,Web上的示例可能有点令人困惑,但是如果您想利用服务器 – 服务器通信 – 意味着没有最终用户而不涉及浏览器,那么以下代码应该适合您:

先决条件:

  • 您应该在Google API控制台中生成“服务帐户”密钥。 它会提示您下载一个私钥,您应将其存储在磁盘上的某个位置,例如client.p12 (或使用原始名称,但为了清楚起见,我将使用较短的一个)。
 client = Google::APIClient.new( :application_name => "CCE", :application_version => "1.0" ) prediction = client.discovered_api('prediction', 'v1.5') key = Google::APIClient::KeyUtils.load_from_pkcs12('client.p12', 'notasecret') client.authorization = Signet::OAuth2::Client.new( :token_credential_uri => 'https://accounts.google.com/o/oauth2/token', :audience => 'https://accounts.google.com/o/oauth2/token', :scope => 'https://www.googleapis.com/auth/prediction', :issuer => '..put here your developer email address from Google API Console..', :signing_key => key, ) client.authorization.fetch_access_token! # Now you can make the API calls result = client.execute(... 

值得注意的是client.discovered_api调用似乎需要版本号。 否则可能会抛出exception’NotFound’。

密码短语实际上是字符串’ notasecret ‘!

另一件事:在API调用中确保您调用正确的方法 – 对于托管模型,我相信您可以调用的唯一方法是:api_method => prediction.hostedmodels.predict或类似的东西。 我还没有使用托管模型。 (有关详细信息,请参阅API文档)

client.execute调用返回的result可能有趣的字段是:

 result.status result.data['error']['errors'].map{|e| e['message']} # if they exist JSON.parse(result.body) 

如果您检查它们,它们可能会帮助您显着调试任何问题。