Rails - Sending a GET Request - ruby-on-rails

I'm trying to retrieve a user's Google account information when a form is submitted. In order to do so, I have to make a GET request to an url. Here's what it says in the YouTube API documentation
To request the currently logged-in user's profile, send a GET request
to the following URL. Note: For this request, you must provide an
authentication token, which enables YouTube to identify the user.
https://gdata.youtube.com/feeds/api/users/default
https://developers.google.com/youtube/2.0/developers_guide_protocol_profiles?hl=en
How do I make it so a custom (or specificall this) GET request happens when the form is submitted, and how do I provide the authentication token? Information that might help: When the form is submitted, it will go to the VideoController's new method.
Also after making the request, how do I access the information? I need to see whether <yt:relationship> is present or not in the given information.
Thanks!

I find HTTParty gem as very useful for working with external APIs in rails.
You can make requests as
response = HTTParty.post("http://www.example.com", :timeout => 5, :body => "my body content", :query => { hash_of_params_here } ,:headers => {'Content-Type' => 'application/json', 'AuthKey' => "your_key_here"})
response object will have 'statuscode', 'headers', 'body' etc (whatever youtube send back in your case). You can access its content using
response.parsed_response
same for get requests too
Please do read more about it for better understanding before getting started.
Sources : Documentation & Tutorial

Yuo can use excon gem to make specific CRUD or only get requests to external resources, for example, it should be something like this:
Excon.post('http://youtube.com', :body => 'token=sjdlsdjasdljsdlasjda')
PS: But seem you not requied the direct gems, tru useing google-api gem, as it described here in the documentation.

Related

Streaming API with Rails not able to get streamed data

I am trying to fetch data from Twitter Streaming API in my rails app and i have created my own module which gives me twitter Authorization Head. I am able to get authorized but i am not getting the response back... all i see is the request in pending state (i am guessing as its streaming and connection not being closed). What can i do to my below code so that i can start printing the response as i get from Streaming API ?
class MainController < ApplicationController
include Oauth::Keys
def show
#oauth_signature_string = Oauth::Signature.generate(signature_params)
#header = Oauth::HeaderString.create(header_params)
RestClient::Request.execute(method: :GET, url: 'https://stream.twitter.com/1.1/statuses/sample.json', :headers => {:Authorization => %Q(OAuth ****************************)} )
end
end
Because Twitter is "streaming" the data and not closing the connection, your RestClient request is not being ended and your show action is hanging there and not "finishing". So, rails can't continue and render the default main/show.html.erb page.
So, you might want to look into ActionController::Streaming class and see if you can rewrite you views and HTTP call to utilize it. Or, it would be much easier to use a non-streaming API edge.
Also, what you are doing seems to be a better fit for javascript. You might want to use Twitter's official Javascript api to do all authentications and status streams.

What is Facebook callback_url and how to use it in rails?

I am using the Facebook Graph API in my rails projects, no matter I use oauth2 gem or koala, It need callback_url
Oauth2
token = client.auth_code.get_token('code_value', :redirect_uri => 'http://localhost:8080/oauth/callback')
Koala
#oauth = Koala::Facebook::OAuth.new(app_id, app_secret, callback_url)
I try to use http://localhost:3000/callback in my project, but it's not working.
Should I develop a routes for that?
like: get 'callback' => 'oauth#callback'?
What should I write in the callback method in OauthController, what does it use for? Thanks
Yes, you should.
Basically, OAuth uses callback data to provide tokens for authenticating users.
For example
user clicks on "sign in" (or whatever) link and your app redirects they to the OAuth provider (or open it in the iframe).
user permits to your app to use they profile details
OAuth provider send callback to your app with unique code
app uses that code to get secure access token for API communications
That's just a basic example.
In your case you need to implement controller that will parse callback data.
Here is the code example
#oauth = Koala::Facebook::OAuth.new(api_key, app_secret, callback_url)
=> #<Koala::Facebook::OAuth:0x007fc919d014e0 #app_id=1234567890, #app_secret="FaKeAppSecretKey", #oauth_callback_url="http://localhost:3000/callback">
#oauth.url_for_oauth_code
=> "https://www.facebook.com/dialog/oauth?client_id=893637180663238&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fcallback"
And when you go to https://www.facebook.com/dialog/oauth?client_id=893637180663238&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fcallback FB will redirect you to
http://localhost:3000/callback?code=CODE_FROM_CALLBACK
Then you should use implement controller that uses code to get access token
access_token = #oauth.get_access_token(params[:code])
=> "ACCESS_TOKEN"
#graph = Koala::Facebook::API.new(access_token)
=> #<Koala::Facebook::API:0x007fc91a903ae0 #access_token="ACCESS_TOKEN", #app_secret=nil>
profile = #graph.get_object("me")
=> {"id"=>"4492344324865", "email"=>"my_fake_email_address#gmail.com", "first_name"=>"Roman", "gender"=>"male", "last_name"=>"Sotnikov", "link"=>"https://www.facebook.com/app_scoped_user_id/4492344324865/", "locale"=>"en_US", "name"=>"Roman Sotnikov", "timezone"=>6, "updated_time"=>"2015-05-18T05:19:54+0000", "verified"=>true}
Please check https://github.com/arsduo/koala/wiki/OAuth for additional info.
Callback Url is yours applications url -- a GET route -- you want the third party application to redirect to, after its done its work.
So in your routes.rb file simply create a get route
get 'facebook_graph_callback', to: 'controller_name#action'
#A get route which is connected to a controller action
Usually the third party will give you some sort of information back. Quite often its some sort of code. In your controller action you can use find them in params hash.

Preventing calls to my JSON api outside the html app

I've separated my front-end from my back-end, so that they communicate via JSON calls (generated by rails back-end).
i.e, my app calls get_info.json which runs a controller that returns ajax information to the front end.
How do I prevent a random user from directly running the get_info.json script, and thus directly accessing the JSON information?
You need to implement authentication for the json api.
It can be as simple as passing an api_key param to every request.
Or you can restrict the access to the route to a specific IP.
get "/posts" => "posts#show", :constraints => {:ip => '127.0.0.1'}
If front-end and back-end are in the same RoR application, then you can use CSRF token.
just pass a param to json call like get_info.json?token=<%= form_authenticity_token.html_safe %>, then in your back-end controller check if if params[:token] == form_authenticity_token.
hope this helps you.

Rspec using post request to get response

I am trying to make a post request to an action in my controller using rspec, which should return a JSON response. This is my current test code which uses the Facebook Graph Gem. I am unsure of my code:
it "creates JSON format metadata with facebook post social message info about social account" do
stub_request(:post, "https://graph.facebook.com/test_fixed_origin_id_str/likes").with(:body => {"access_token"=>"this_is_a_test_token"}, :headers => {'Content-Type'=>'application/x-www-form-urlencoded'}).to_return(:status => 200, :body => "", :headers => {})
post :like, id: combined_id, format: :json
end
What would be the best way to make a post request to an API? I apologize if my question is not too clear but I have little experience with making requests in tests.
Thanks
One thing I can recommend is to just use the VCR gem (https://github.com/vcr/vcr). Essentially, the main idea behind this is that when your tests run the first time, the vcr will "record" the JSON response from the API endpoint.
In next iterations of the test, it will simply "play back" this response instead of making a live call to the server everytime. This has its benefits (speed, simplicity), but also you have to keep in mind that if the API response does change over time (ie. if FB changed their response), you would have to make sure to re-record what is coming back.

Facebook app: within Canvas, Facebook treats GETs as POSTs?

In my Rails FB app, when running in the canvas, if I go to "/users", instead of GETting the index page, it POSTs and creates a new user.
That only happens when I try to access the URL directly. When I use the "List of users" link on the app, it works as expected.
Why is that?
that's just how FB does it. They post data with each query as well.
Facebook sends everything as POST which brakes RESTful routes. There is a way to fix it though. If incoming POST request contains signed_request parameter you can assume it was converted from GET to POST by Facebook.
Rack::Facebook::MethodFix middleware fixes the problem automagically. You can use it with something like:
# Basic usage
use Rack::Facebook::MethodFix
# Also validate signed_request
use Rack::Facebook::MethodFix, :secret_id => "c561df165eacdd6e32672c9eaee10318"
# Do not apply request method fix to admin urls.
use Rack::Facebook::MethodFix, :exclude => proc { |env| env["PATH_INFO"].match(/^\/admin/) }
or if you are using Rails then
config.middleware.use Rack::Facebook::MethodFix

Resources