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.
Related
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.
I wanna process soap data in my rails app, requirements is like this: 3rd party app connect to my app and post the soap data using http protocol, then in my controller, my app has to parse these soap data, store them and then send the result to the requestor using soap format. Now the problem is I do not know how to deal these in my controller. Which gem shoud I used? wash_out or sovan?? Could someone give a detail example? Thanks for helping.
I'm not a fan of using SOAP, but there are a lot of documentation on internet, like this
Basically you need to include the next code in your model
def initialize(zip)
client = Savon::Client.new("http://theserver.com?WSDL")
response = client.request :web, :info, body:{"foo" => foo}
if response.success?
#do code
end
end
This railscast haves a good explanation too.
I am getting familiarised with APIs. As a start, I am using the Forecast API.
In the docs, you will find a section entitled "Response Headers". What are they, and how can I use them?
Also, to get a response, it says you need to pass an API key, along with lat and long data. But aren't API keys supposed to be kept secret? Will anyone find out the contents of the request?
This is the code I have:
Forecast model
require 'json'
class Forecast
include HTTParty
debug_output $stdout
default_params :apiKey => 'xxxxxxxxxxxxxxxxxxxxxxxxx'
base_uri "api.forecast.io"
format :json
def self.get_weather(api,lat,long)
#response = get("/forecast/#{apiKey}/#{lat},#{long}")
end
def self.show_weather
JSON.parse(#response.body)
end
end
Forecast controller
def index
#weather = Forecast.get_weather("28.5355", "77.3910")
#response = Forecast.show_weather
end
Forecast view
<%= #response["currently"]["summary"] %>
You're asking a couple of different questions here.
Response headers: They are part of an HTTP response, and contain information about the response. For example, they might tell you the MIME-type of the response - eg. Content-Type: application/json. In this case, Forecast use it to tell you how many API calls you've made (X-Forecast-API-Calls) and how long it took them to respond (X-Response-Time) as well as some caching information.
API keys: Yes, these should be kept secret. The Forecast API works over HTTPS, so (in theory) your API key should be kept secret from people sniffing traffic on your network. The main danger is keeping it in your code and, for example, committing it to GitHub. You should figure out a safer way to store the API key. One example, whilst not perfect, would be to have it as an environment variable.
I hope that helps.
I am using Ruby on Rails 3 and I am trying to implement APIs to retrieve account information from a web service. That is, I would like to connect to a web service that has the Account class and get information from the show action routed at the URI http://<site_name>/accounts/1.
At this time, in the web service accounts_controller.rb file I have:
class AccountsController < ApplicationController
def show
#account = Account.find(params[:id])
respond_to do |format|
format.html
format.js
format.json { render :json => #account.to_json }
end
end
end
Now I need some advice for connecting to the web service. In the client application, I should have a HTTP GET request, but here is my question: What is "the best" approach to connect to a web service making HTTP requests?
This code in the client application works:
url = URI.parse('http://<site_name>/accounts/1.json')
req = Net::HTTP::Get.new(url.path)
res = Net::HTTP.start(url.host, url.port) {|http|
http.request(req)
}
#output = JSON(res.body)["account"]
but, is the above code "the way" to implement APIs?
Is it advisable to use third-party plugins and gems?
Yes, since you're using RESTful routes, they are your basic API. You're also returning structured JSON data easily consumable by an application.
There are other ways to implement a web services API (e.g. SOAP), but this is a good and proper way.
Since it's a web services API, connecting to the correct URL and parsing the response is the way to go on the client side. Though if you need to access many different resources it might be a good idea to create a flexible way of building the request URL.
If you don't need low-level tweak-ability offered by Net::HTTP, instead take a look at using Open-URI, which comes with Ruby. It makes it easy to request a page and receive the body back. Open-URI doesn't have all the bells and whistles but for a lot of what I do it's plenty good.
A simple use looks like:
require 'open-uri'
body = open('http://www.example.com').read
The docs have many other examples.
These are other HTTP clients I like:
HTTPClient
Typhoeus
They are more tweakable and can handle multiple connections at once if that's what you need. For instance, Typhoeus has a suite of simplified calls, similar to Open-URI's. From the docs:
response = Typhoeus::Request.get("http://www.pauldix.net")
response = Typhoeus::Request.head("http://www.pauldix.net")
response = Typhoeus::Request.put("http://localhost:3000/posts/1", :body => "whoo, a body")
response = Typhoeus::Request.post("http://localhost:3000/posts", :params => {:title => "test post", :content => "this is my test"})
response = Typhoeus::Request.delete("http://localhost:3000/posts/1")
HTTPClient has similar shortened methods too.
I'd recommend using Rails' ActiveResource for most cases. Failing that, httparty.
I would use ActiveResource if you just need a simple way to pull in rest-based resources. It's already included in rails and pretty trivial to set up. You just specify a base url and resource name in your ActiveResource subclass and then you can CRUD rest-based resources with an interface similar to that of ActiveRecord.
rest-client is the most popular gem for easily connecting to RESTful web services
I think one of the best solutions out there is the Her gem. It encapsulates restful requests providing objects with active-record like behavior.
I want to access a URL of another website from one of my models, parse some information and send it back to my user. Is this possible?
For example, the user sends me an address through a POST, and I want to validate the information through a third party website (USPS or GMaps)
What methods would I use to create the request and parse the response?
This is not a redirect. I want to open a new request that is transparent from the client.
There are a lot of libraries to handle this such as:
HTTParty on http://github.com/jnunemaker/httparty
Curb on http://curb.rubyforge.org/
Patron on http://github.com/toland/patron
Example using Patron:
sess = Patron::Session.new
sess.timeout = 10
sess.base_url = "http://myserver.com:9900"
sess.headers['User-Agent'] = 'myapp/1.0'
resp = sess.get("/foo/bar")
if resp.status < 400
puts resp.body
end
Each solution has its own way of handling requests and parsing them as well as variations in their API. Look for what fits your needs the best.