开发者

How do I make an API call to viralheat on submit and then parse and save the JSON response?

I want to send a request via Viralheat's API in my controller's update method so that when a user hits the submit button, an action is completed and the API call is made. I want to post to http://www.viralheat.com/api/sentiment/review.json?text=i&do&not&like&this&api_key=[* your api key *]

This will return some JSON in the format:

{"mood":"negative","prob":0.773171679917001,"text":"i do not like this"}

Is it possible to make that API call simultaneously while executing the controller method and how would I handle the JSON response? Which controller method would I put it in?

Ultimately I'd like to save the response mood to my sentiment column in a BrandUsers table. Submit is in main.html.erb which then uses the update method.

Controller

def update
  @brand = Brand.find(params[:id])
  current_user.tag(@brand, :with => params[:brand][:tag_list], :on => :tags)
开发者_如何学Python  if @brand.update_attributes(params[:brand])
    redirect_to :root, :notice  => "Brand tagged."
  else
    render :action => 'edit'
  end
end

def main
  @brands = Brand.all
  if current_user
    @brand = current_user.brands.not_tagged_by_user(current_user).order("RANDOM()").first
end


With the wrest gem installed, you could do something like

params[:api_key] = "your key"

url = "http://www.viralheat.com/api/sentiment/review.json"

response = url.to_uri.get(params).deserialize

response would contain the json already turned into a hash. So you can access the mood with

response[:mood]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜