HTTParty'get'返回nil:Ruby

时间:2017-01-19 20:13:59

标签: ruby-on-rails json ruby web-deployment httparty

我是Ruby on Rails框架的新手。我正在使用课程上的Ruby on Rails教程进行练习,我必须使用HTTParty从Coursera API获取有关课程的信息,并在屏幕上显示此信息。但不幸的是我遇到了问题。

以下是我的代码,它从Coursera API获取信息并将其返回

class Coursera
     include HTTParty

     base_uri 'https://api.coursera.org/api/catalog.v1/courses'
     default_params fields: "smallIcon,shortDescription", q: "search"
     format :json

     def self.for term
         response=get("", query: { query: term})["elements"]
         if(response==nil)
             puts "Got Negative response!"
         else
             puts "Got Positive response!"
             return response
         end
     end
 end

有人可以指出为什么“得到”返回零。我确定我犯了一些大错,但有人可以指出吗?提前致谢

1 个答案:

答案 0 :(得分:0)

怪异。看起来,coursera并不总​​是返回相同的响应。

[1,2,3]

有时返回:

require 'httparty'

class Coursera
  include HTTParty

  base_uri 'https://api.coursera.org/api/catalog.v1/courses'
  default_params fields: "smallIcon,shortDescription", q: "search"
  format :json

  def self.for term
    response = get("", query: {query: term})
    puts response.request.last_uri.to_s
    elements = response["elements"]
    if elements
      puts "Got Positive response!"
      response
    else
      puts "Got Negative response!"
    end
  end
end

p Coursera.for 'python'

有时候:

https://api.coursera.org/api/catalog.v1/courses?fields=smallIcon%2CshortDescription&q=search&query=python
Got Negative response!
nil