the code below is only getting the results from the first page of the google pagination... how to get more results?
require 'google/api_client'
# autenticação
client = Google::APIClient.new(:application_name => 'Ruby Drive sample',
:application_version => '1.0.0',
:client_id => 'xxxxxxxxxxxxxxxx',
:client_secret => 'xxxxxxxxxxxxxx',
:authorization => nil)
search = client.discovered_api('customsearch')
# chama a API
response = client.execute(
:api_method => search.cse.list,
:parameters => {
'q' => 'cafe',
'key' => 'xxxxxxxxxxxx',
'cx' => 'xxxxxxxxxxxxxxxx'
}
)
# recebe a resposta em json
body = JSON.parse(response.body)
items = body['items']
# printa algumas informações...
items.each do |item|
puts "#{item['formattedUrl']}"
end
Simply use the nextPageToken as a parameter in the next request until you get back a result without a nextPageToken key
next_page_token = body['nextPageToken']
response_page2 = client.execute(
:api_method => search.cse.list,
:parameters => {
'nextPageToken' => next_page_token,
'key' => 'xxxxxxxxxxxx',
'cx' => 'xxxxxxxxxxxxxxxx'
}
)
Related
Following a sample which is here: https://gist.github.com/joost/5344705
The latest version of the google-api-client gem throws an error on:
key = Google::APIClient::PKCS12.load_key(key_file, 'notasecret')
#=> Uninitialized constant Google::APIClient(name error)
What is the new method for loading the P12/JSON file?
FYI, refactored error-prone code:
# you need to set this according to your situation/needs
SERVICE_ACCOUNT_EMAIL_ADDRESS = 'xxx#developer.gserviceaccount.com' # looks like 12345#developer.gserviceaccount.com
PATH_TO_KEY_FILE = '/home/arjun/rails/learn/xxx.p12' # the path to the downloaded .p12 key file
PROFILE = 'ga:xxx' # your GA profile id, looks like 'ga:12345'
require 'google/apis/analytics_v3'
require 'googleauth/stores/file_token_store'
Analytics = Google::Apis::AnalyticsV3
# set up a client instance
client = Analytics::AnalyticsService.new
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/analytics.readonly',
:issuer => SERVICE_ACCOUNT_EMAIL_ADDRESS,
# :signing_key => OpenSSL::PKey.load_key(PATH_TO_KEY_FILE, 'notasecret')
# Not working = throws []': no implicit conversion of Symbol into Integer (TypeError)
:signing_key => Google::Auth::Stores::FileTokenStore.new(PATH_TO_KEY_FILE.to_i)
).tap { |auth| auth.fetch_access_token! }
api_method = client.discovered_api('analytics','v3').data.ga.get
# make queries
result = client.execute(:api_method => api_method, :parameters => {
'ids' => PROILE,
'start-date' => Date.new(1970,1,1).to_s,
'end-date' => Date.today.to_s,
'dimensions' => 'ga:pagePath',
'metrics' => 'ga:pageviews',
'filters' => 'ga:pagePath==/url/to/user'
})
puts result.data.rows.inspect
for version 0.9.18 of the google-api-client gem, the signing_key part should change to:
require 'google/api_client/auth/key_utils'
signing_key: Google::APIClient::KeyUtils::load_from_pkcs12(keypath, 'notasecret')
I want to use Yahoo Fantasy sport API in my web application, For that I am using OAuth for Yahoo login. I have consumer key and secret key and i passed the keys successfully, When I run the following code. It redirects to Yahoo login, It asks permission for accessing the user's credentials. If i give AGREE the page Redirects to https://api.login.yahoo.com/oauth/v2/request_auth and It shows the Verifying code. If i press the close button in verification code page, it's not callback to my URL.
#ts=Time.now.to_i
#callback_url = "http://localhost:3000/callback"
#nonce = SecureRandom.hex()
consumer = OAuth::Consumer.new("my consumerkey","secret key",
{ :site => 'https://api.login.yahoo.com',
:http_method => :post,
:scheme => :header,
:oauth_nonce => #nonce,
:request_token_path => '/oauth/v2/get_request_token',
:authorize_path => '/oauth/v2/request_auth',
:access_token_path => '/oauth/v2/get_token',
:oauth_callback => "http://localhost:3000/callback",
:oauth_timestamp => Time.now.to_i,
:oauth_signature_method => "HMAC-SHA-1",
:oauth_version => "1.0",
:oauth_callback_confirmed => true,
})
request_token = consumer.get_request_token
session[:request_token]=request_token
redirect_to request_token.authorize_url
access_token=request_token.get_access_token
access = ActiveSupport::JSON.decode(access_token.to_json)
if !(access.present?)
#response = "Response failed"
else
#response = access
end
Can you please tell me What changes to be made to get the callback for to get access_token.
I think you got confused while getting callback. change your code as follows, You will surely get access token to make Yahoo API call.
##access_token = nil
##request_token = nil
def get_request_token
##consumer = OAuth::Consumer.new('consumer key',
'secret key',
{
:site => 'https://api.login.yahoo.com',
:scheme => :query_string,
:http_method => :get,
:request_token_path => '/oauth/v2/get_request_token',
:access_token_path => '/oauth/v2/get_token',
:authorize_path => '/oauth/v2/request_auth'
})
##request_token = ##consumer.get_request_token( { :oauth_callback => 'http://localhost:3000/callback' } )
session[:request_token]=##request_token
redirect_to ##request_token.authorize_url
#redirect_to ##request_token.authorize_url( { :oauth_callback => 'http://localhost:3000/success' } )
end
def callback
request_token = ActiveSupport::JSON.decode(##request_token.to_json)
if !(request_token.present?)
$request_token_value = "Response failed"
else
$request_token_value = request_token
end
# access_token = ##request_token.get_access_token({:oauth_verifier=>params[:oauth_verifier],:oauth_token=>params[:oauth_token]})
##access_token = ##request_token.get_access_token(:oauth_verifier=>params[:oauth_verifier])
access_json = ActiveSupport::JSON.decode(##access_token.to_json)
puts "****************************"
puts $access_json
puts "****************************"
end
I am running rails 4 with the rbing gem installed (version 1.1.0)
require 'rbing'
bing = RBing.new("YOURAPPID")
rsp = bing.web("ruby", :site => "github.com")
puts rsp.web.results[0].url
Just like the example here:
https://github.com/mikedemers/rbing
when I run it I get this error:
undefined method `web' for # RBing::ResponseData:0x007f42500bb190
I ended up using google instead
client = Google::APIClient.new(:authorization => nil)
google_search = client.discovered_api('customsearch', 'v1')
google_result = client.execute(
:api_method => google_search.cse.list,
:authenticated => false,
:parameters => {
'q' => query,
'key' => key, # your key received from google
'siteSearch' => query_params[1],
'cx' => cx, # your cx code received from google
'num' => 1
}
)
I have took the sample code from
http://code.google.com/p/google-api-ruby-client/source/browse/service_account/analytics.rb?repo=samples
however, I have been trying to get it working but it just keeps on giving, no matter how hard I try ! Here is the error I keep on getting
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/signet-0.4.5/lib/signet/oauth_2/client.rb:875:in `fetch_access_token': Authorization failed. Server message: (Signet::Authorization
Error)
{
"error" : "invalid_grant"
}
from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/signet-0.4.5/lib/signet/oauth_2/client.rb:888:in `fetch_access_token!'
How Do I solve this ?
Here is my complete code
require 'google/api_client'
require 'date'
require 'openssl'
OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE
# Update these to match your own apps credentials
service_account_email = 'xxxxxx' # Email of service account
key_file = 'privatekey.p12' # File containing your private key
key_secret = 'notasecret' # Password to unlock private key
profileID = 'xxxxx' # Analytics profile ID.
client = Google::APIClient.new()
# Load our credentials for the service account
key = Google::APIClient::KeyUtils.load_from_pkcs12(key_file, key_secret)
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/analytics.readonly',
:issuer => service_account_email,
:signing_key => key)
# Request a token for our service account
client.authorization.fetch_access_token!
analytics = client.discovered_api('analytics','v3')
startDate = DateTime.now.prev_month.strftime("%Y-%m-%d")
endDate = DateTime.now.strftime("%Y-%m-%d")
visitCount = client.execute(:api_method => analytics.data.ga.get, :parameters => {
'ids' => "ga:" + profileID,
'start-date' => startDate,
'end-date' => endDate,
'dimensions' => "ga:day,ga:month",
'metrics' => "ga:visits",
'sort' => "ga:month,ga:day"
})
print visitCount.data.column_headers.map { |c|
c.name
}.join("\t")
visitCount.data.rows.each do |r|
print r.join("\t"), "\n"
end
I have spent whole day to get this working. Please help. Thanks for your time.
Solved it !
My Computer clock was for some reason 4 hours late ! Corrected System Time, it lead to no error.
1 - Make Your you solve the SSL Error if you have any by using the Google API Faq.
It took me whole day, so I'm going to leave my solutions so in future no one has to go crazy like I did.
account_email = '#developer.gserviceaccount.com'
key_file = 'privatekey.p12'
key_secret = 'notasecret'
client = Google::APIClient.new()
key = Google::APIClient::KeyUtils.load_from_pkcs12(key_file, key_secret)
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/calendar',
:issuer => account_email,
:signing_key => key)
# # Request a token for our service account
client.authorization.fetch_access_token!
service = client.discovered_api('calendar', 'v3')
Example to execute something shall be like in similar fashion.
#event = {
'summary' => '',
'location' => 'this is where the location goes',
'description' => 'desc',
'start' => {
'dateTime' => '2013-02-08T10:00:00.000-07:00' # Date with :- offset so (yyyy-mm-dd T hh:mm:ss.000-offset)
},
'end' => {
'dateTime' => '2013-02-08T10:25:00.000-07:00' # Date with :- offset so (yyyy-mm-dd T hh:mm:ss.000-offset)
}
}
# Create event using the json structure
result = client.execute(:api_method => service.events.insert,
:parameters => {'calendarId' => '**'},
:body => JSON.dump(#event),
:headers => {'Content-Type' => 'application/json'})
I know we can sync data using rhodes without Rhosync or Rhoconnect by using direct web service, but I'm here little bit confuse where to place that code for webservice call and how do we initialize it. Can anyone help me with small example?
Thanks in Advance.
I got it and it works for me.
class ProductController < Rho::RhoController
include BrowserHelper
# GET /product
def index
response = Rho::AsyncHttp.get(:url => "example.com/products.json",
:headers => {"Content-Type" => "application/json"})
#result = response["body"]
render :back => '/app'
end
# GET /product/{1}
def show
id =#params['id']
response = Rho::AsyncHttp.get(:url => "example.com/products/"+ id +".json",
:headers => {"Content-Type" => "application/json"})
#result = response["body"]
end
# GET /product/new
def new
#product = product.new
render :action => :new, :back => url_for(:action => :index)
end
# GET /product/{1}/edit
def edit
id =#params['product_id'].to_s
response = Rho::AsyncHttp.get(:url => "example.com/products/#{id}.json",
:headers => {"Content-Type" => "application/json"})
#result = response["body"]
end
# POST /product/create
def create
name = #params['product']['name']
price = #params['product']['price']
body = '{"product" : {"name" : "'+ name +'","price" :"'+ price +'" } }'
#result = Rho::AsyncHttp.post(:url => "example.com/products.json",
:body => body, :http_command => "POST", :headers => {"Content-Type" => "application/json"})
redirect :action => :index
end
# POST /product/{1}/update
def update
name=#params['product']['name']
price=#params['product']['price']
body = '{"product" : {"name" : "' + name + '","price" :"' + price + '" } }'
id = #params["product_id"].to_s
response = Rho::AsyncHttp.post(:url => "example.com/products/#{id}.json",
:body => body, :http_command => "PUT",:headers => {"Content-Type" => "application/json"})
redirect :action => :index
end
# POST /product/{1}/delete
def delete
id = #params["product_id"].to_s
response = Rho::AsyncHttp.post(:url => "example.com/products/#{id}.json",
:http_command => "DELETE",
:headers => {"Content-Type" => "application/json"})
redirect :action => :index
end
end
Most easy form of http server request is next:
Rho::AsyncHttp.get(
:url => "http://www.example.com",
:callback => (url_for :action => :httpget_callback)
)
where httpget_callback is name of the controller callback method.
See more details at official Rhodes docs.