【问题标题】:I'm having issues with using an API我在使用 API 时遇到问题
【发布时间】:2020-12-12 17:39:07
【问题描述】:

我有以下代码:

class EpisodeIndex::API

    def initialize
        @url = "https://www.officeapi.dev/api/episodes?limit=400"
    end

    def get_episode_data
        uri = URI.parse(@url)
        response = Net::HTTP.get(uri)
        data = JSON.parse(response)
        data["data"].each do |episode|
            get_episode_title(episode["title"])
        end
    end

    def get_episode_title(title)
        uri = URI.parse(title)
        response = Net::HTTP.get(title)
        data = JSON.parse(response)
        binding.pry
    end

    EpisodeIndex::API.new.get_episode_data

end

我得到了这个错误作为回报。

`get_response': undefined method `hostname' for "Pilot":String (NoMethodError)
jocelynpeters@Jocelyns-Air office_cli % 

我不知道如何解决它。请善待。我对编程很陌生。

谢谢!

【问题讨论】:

    标签: ruby api command-line-interface


    【解决方案1】:

    API 返回的数据如下所示:

    {
      "data":
        [
          {
            "_id":"5e94d646f733a1332868e1dc",
            "title":"Pilot",
            "description":"A documentary crew gives a firsthand introduction to the staff of the Scranton branch of the Dunder Mifflin Paper Company, managed by Michael Scott.",
            "writer": {
              "_id":"5e95242f9511994a07f9a319",
              "name":"Greg Daniels",
              "role":"Writer/Director",
              "__v":0
            },
            "director": {
              "_id":"5e9523649511994a07f9a313",
              "name":"Ken Kwapis",
               "role":"Director",
               "__v":0
            },
            "airDate":"2005-03-24T06:00:00.000Z",
            "__v":0
          },
          # ...
    

    这意味着结果集已经包含每集的标题,并且不包含任何可以加载更多信息的 URL(您当前在 get_episode_title 方法中尝试的内容)。因此,您可以将代码简化为:

    module EpisodeIndex
      require "json"
      require "net/http"
    
      class API
        def initialize
          @url = "https://www.officeapi.dev/api/episodes?limit=400"
        end
    
        def titles
          uri = URI.parse(@url)
          response = Net::HTTP.get(uri)
          
          data = JSON.parse(response)
          data["data"].map do |episode|
              episode["title"]
          end
        end
      end
    end
    
    EpisodeIndex::API.new.titles
    #=> ["Pilot", "Diversity Day", "Health Care", "The Alliance", "Basketball", "Hot Girl", "The Dundies", "Sexual Harassment", "Office Olympics", "The Fire", "Halloween", "The Fight", "The Client", "Performance Review", "E-Mail Surveillance", "Christmas Party", "Booze Cruise", "The Injury", "The Secret", "The Carpet", "Boys and Girls", "Valentine's Day", "Dwight's Speech", "Take Your Daughter to Work Day", "Michael's Birthday", "Drug Testing", "Conflict Resolution", "Casino Night"]
    

    【讨论】:

      猜你喜欢
      • 2022-07-15
      • 2020-02-09
      • 1970-01-01
      • 1970-01-01
      • 2023-02-13
      • 2020-12-23
      • 2021-11-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多