Using Ruby + OAuth to access Yelp API - ruby

I just getting started with OAuth, and I tried to make a small client to connect to some webservices... I tried twitter and it worked like a charm, however, I also tried to access Yelp V2 API (following their Python example) but I always get back as an answers:
HTTP 400 Bad Request
Missing parameter: oauth_consumer_key
Here's my code:
require 'rubygems'
require 'oauth'
CONSUMER_KEY = "MY_CONSUMER_KEY"
SECRET = "MY_CONSUMER_SECRET"
TOKEN = "MY_TOKEN"
TOKEN_SECRET = "MY_TOKEN_SECRET"
consumer = OAuth::Consumer.new( CONSUMER_KEY,SECRET, {:site => "http://api.yelp.com", :signature_method => "HMAC-SHA1", :scheme => :header})
access_token = OAuth::AccessToken.new( consumer, TOKEN,TOKEN_SECRET)
p access_token.get("/v2/search?location=new+york").body
Regardless to say, that code works with twitter API without any problem (I actually followed twitter's example code)
Cheers and thanks in advance,
Ze

Use :query_string instead of :header and everything will work (at least for me).

Same code, using Signet:
require 'signet/oauth_1/client'
client = Signet::OAuth1::Client.new(
:consumer_key => 'MY_CONSUMER_KEY',
:consumer_secret => 'MY_CONSUMER_SECRET',
:access_token_key => 'MY_TOKEN_KEY',
:access_token_secret => 'MY_TOKEN_SECRET'
)
response = client.fetch_protected_resource(
:uri => 'http://api.yelp.com/v2/search?location=new+york'
)
# The Rack response format is used here
status, headers, body = response
p body
As per the Yelp documentation, the OAuth parameters do not have to be passed in the query string. The fact that the accepted answer resolved the issue indicates to me that there's probably a bug in the oauth gem causing this.

Related

Use GetTwitter 1.16.3 processor in Nifi gives error 403 Forbidden

I did read the comments on the similar questions, checked out what the answers propose, followed those in detail. Does not change anything.
As I tried to do exactly the same in Python using the Tweepy library, and that does work fine, I know for sure it must be something at Nifi's side.
I do have elevated access on Twitter, I checked multiple times my tokens, they are correctly filled in.
Anybody a usefull answer?
Python code:
import tweepy
consumer_key = 'xxx'
consumer_secret = 'xxx'
access_token = 'xxx'
access_token_secret = 'xxx'
auth = tweepy.OAuth1UserHandler( consumer_key, consumer_secret, access_token, access_token_secret )
api = tweepy.API(auth, wait_on_rate_limit=True)
for tweet in tweepy.Cursor(api.search_tweets, q="#twitter", count=100, tweet_mode='extended', until = '2022-07-09').items():
text = tweet._json["full_text"]
print(text)
print('\n\n')
Nifi code:
Processor GetTwitter (1.16.3) with consumer_key, consumer_secret, access_token, access_token_secret filled correctly in.
Other elements not changed. Added a wait processor connected with success relation.
!! I retested the same simple flow (getTwitter and Wait processor)in version 1.12.1: result is a 401 error instead of 403(?)

Ruby hipchat gem invalid send file

So this is related to an earlier post I made on this method. This is essentially what I am using to send files via hipchat:
#!/usr/bin/env ruby
require 'hipchat'
client = HipChat::Client.new('HIPCHAT_TOKEN', :api_version => 'v2', :server_url => 'HIPCHAT_URL')
client.user('some_username').send_file('message', File.open('./output/some-file.csv') )
client['some_hipchat_room'].send_file('some_user', 'message', File.open('./output/some-file.csv') )
Now for some reason the send_file method is invalid:
/path/to/gems/hipchat-1.5.4/lib/hipchat/errors.rb:40:in `response_code_to_exception_for': You requested an invalid method. path:https://hipchat.illum.io/v2/user/myuser#myemail/share/file?auth_token=asdfgibberishasdf method:Net::HTTP::Get (HipChat::MethodNotAllowed)
from /path/to/gems/gems/hipchat-1.5.4/lib/hipchat/user.rb:50:in `send_file'
I think this indicating that you should be using POST instead of GET, but I'm not sure because I haven't used this library nor Hipchat.
Looking at the question you referenced and the source posted by another user they're sending the request using self.class.post, and your debug output shows Net::HTTP::Get
To debug, could you try,
file = Tempfile.new('foo').tap do |f|
f.write("the content")
f.rewind
end
user = client.user(some_username)
user.send_file('some bytes', file)
The issue is that I was attempting to connect to the server via http instead of https. If the following client is causing issues:
client = HipChat::Client.new('HIPCHAT_TOKEN', :api_version => 'v2', :server_url => 'my.company.com')
Then try adding https:// to the beginning of your company's name.
client = HipChat::Client.new('HIPCHAT_TOKEN', :api_version => 'v2', :server_url => 'https://my.company.com')

Oauth2 token not working for gmail_xoauth gem

I'm currently getting a token via the omniauth-google-oauth2 gem per the following: https://github.com/zquestz/omniauth-google-oauth2
I store the token that comes back from the auth_hash.
I then try to use the token by calling:
require 'gmail_xoauth'
imap = Net::IMAP.new('imap.gmail.com', 993, usessl = true, certs = nil, verify = false)
imap.authenticate('XOAUTH2', 'myemail#gmail.com', Token.last)
Problem is that I get an error:
[8] pry(main)> imap.authenticate('XOAUTH2', 'myemail#gmail.com', Token.last)
Token Load (0.6ms) SELECT "tokens".* FROM "tokens" ORDER BY "tokens"."id" DESC LIMIT 1
Net::IMAP::NoResponseError: Invalid credentials (Failure)
from /Users/username/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/net/imap.rb:1171:in `get_tagged_response'
Ok I took a look at google-api-client and I started to use that a little more. Seems like the best solution at the moment is to do the following:
create an options hash that includes the gmail parameters and the gmail api_method
use the service you initialize with your access_token to create your query in the options hash
Below you can see a rough example that you can use
client = Google::APIClient.new
client.authorization.access_token = token
service = client.discovered_api 'gmail'
options = {parameters: {'userId' => 'email#gmail.com'}, api_method: service.users.messages.list}
client.execute(options)
I mean this is pretty clunky and should be DRY'd up. (Hopefully google creates a better gem around this)
The solution was to update the scope of omniauth for gmail.
Rails.application.config.middleware.use OmniAuth::Builder do
provider :google_oauth2, ENV['GOOGLE_CLIENT_ID'], ENV['GOOGLE_CLIENT_SECRET'],
{
scope: [
'https://mail.google.com/','https://www.googleapis.com/auth/userinfo.email'
]
}
end

Reading Withings API ruby

I have been trying for days to pull down activity data from the Withings API using the OAuth Ruby gem. Regardless of what method I try I consistently get back a 503 error response (not enough params) even though I copied the example URI from the documentation, having of course swapped out the userid. Has anybody had any luck with this in the past. I hope it is just something stupid I am doing.
class Withings
API_KEY = 'REMOVED'
API_SECRET = 'REMOVED'
CONFIGURATION = { site: 'https://oauth.withings.com', request_token_path: '/account/request_token',
access_token_path: '/account/access_token', authorize_path: '/account/authorize' }
before do
#consumer = OAuth::Consumer.new API_KEY, API_SECRET, CONFIGURATION
#base_url ||= "#{request.env['rack.url_scheme']}://#{request.env['HTTP_HOST']}#{request.env['SCRIPT_NAME']}"
end
get '/' do
#request_token = #consumer.get_request_token oauth_callback: "#{#base_url}/access_token"
session[:token] = #request_token.token
session[:secret] = #request_token.secret
redirect #request_token.authorize_url
end
get '/access_token' do
#request_token = OAuth::RequestToken.new #consumer, session[:token], session[:secret]
#access_token = #request_token.get_access_token oauth_verifier: params[:oauth_verifier]
session[:token] = #access_token.token
session[:secret] = #access_token.secret
session[:userid] = params[:userid]
redirect "#{#base_url}/activity"
end
get '/activity' do
#access_token = OAuth::AccessToken.new #consumer, session[:token], session[:secret]
response = #access_token.get("http://wbsapi.withings.net/v2/measure?action=getactivity&userid=#{session[:userid]}&startdateymd=2014-01-01&enddateymd=2014-05-09")
JSON.parse(response.body)
end
end
For other API endpoints I get an error response of 247 - The userid provided is absent, or incorrect. This is really frustrating. Thanks
So I figured out the answer after copious amount of Googleing and grasping a better understanding of both the Withings API and the OAuth library I was using. Basically Withings uses query strings to pass in API parameters. I though I was going about passing these parameters correctly when I was making API calls, but apparently I needed to explicitly set the OAuth library to use the query string scheme, like so
http_method: :get, scheme: :query_string
This is appended to my OAuth consumer configuration and all worked fine immediately.

Fetch friends count using Odnoklassniki API in Ruby

looking for working solution to Fetch friends count using Odnoklassniki API in Ruby
tried to use lemur and school_friend gems without success
require 'school_friend'
SchoolFriend.application_id = '193320768'
SchoolFriend.application_key = 'CBALsdsASDBA'
SchoolFriend.secret_key = 'A3AA9342CR47DA4BC315'
SchoolFriend.api_server = 'http://api.odnoklassniki.ru'
puts SchoolFriend.users.is_app_user(:uid => '571931088692')
{"error_code"=>100, "error_data"=>nil, "error_msg"=>"PARAM : Missed required parameter: access_token"}
even i specify access_token as mentioned in docs like that:
session = SchoolFriend.session(:access_token => 'token_from_oauth2_client')
session.friends.get
{"error_code"=>100, "error_data"=>nil, "error_msg"=>"PARAM : Missed required parameter: access_token"}
i still get same error
Becouse odnoklassniki api requires access token
your request to this api should be like
http://api.odnoklassniki.ru/fb.do?method=friends.get&application_key=[APPLICATION_KEY]&sig=[SIG]&access_token=[ACCESS_TOKEN]
I'm use lemur and for me it works fine
i'm initialize it like
odnoklassniki = Lemur::API.new(APP_SECRET, Public_key, Access_token, APP_ID)
where APP_SECRET, Public_key and APP_ID you have after registration your app
Access_token you have after use sign in to odnoklassniki via omniauth
and then i can call api method like
odnoklassniki.get(method: 'friends.get')
this returns something like that
["55726542234", "32131394541", "532139395874", "94691213891"]

Resources