Rob*_*yle 2 ruby api google-api
我试图简单地向google的托管模型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' => ''})
Run Code Online (Sandbox Code Playgroud)
`
好吧,Web上的示例可能有点令人困惑,但是如果您想利用服务器 - 服务器通信 - 这意味着没有最终用户且没有涉及浏览器,那么以下代码应该适合您:
先决条件:
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(...
Run Code Online (Sandbox Code Playgroud)
值得注意的是,client.discovered_api呼叫似乎需要版本号.否则它可能会抛出异常'NotFound'.
密码短语真是字符串' notasecret '!
另一件事:在API调用中确保您调用正确的方法 - 对于托管模型,我相信您可以调用的唯一方法是:api_method => prediction.hostedmodels.predict这样的.我还没有使用托管模型.(有关详细信息,请参阅API文档)
呼叫result返回的可能有趣的字段client.execute是:
result.status
result.data['error']['errors'].map{|e| e['message']} # if they exist
JSON.parse(result.body)
Run Code Online (Sandbox Code Playgroud)
如果您检查它们,它们可能会帮助您显着调试任何问题.
| 归档时间: |
|
| 查看次数: |
1847 次 |
| 最近记录: |