ruby-on-railsapimethodsespn

Troubleshooting ESPN API in Rails


In my rails app, I've got a working method for capturing ESPN Headlines via their API. But, when I try to replicate this to capture all NFL players, the method is failing.

Here's the headline method that is working via IRB, when I run Headline.all in IRB it works great.

MODEL (headline.rb)
class Headline
  include HTTParty
  base_uri 'http://api.espn.com/v1/sports'

  def self.all
    response = Headline.get('/news/headlines',
      :query => { :apikey => 'my_api_key' })
    response["headlines"]
  end
end

CONTROLLER (headlines_controller.rb)
class HeadlinesController < ApplicationController
  def index
    @headlines = Headline.all
  end
end

Here's the almost identical code for NFL players, and it returns "nil" via IRB. Any ideas why?

MODEL (athlete.rb)
class Athlete
  include HTTParty
  base_uri 'http://api.espn.com/v1/sports'

  def self.all
    response = Athlete.get('/football/nfl/athletes',
      :query => { :apikey => 'my_api_key_from_espn' })
    response["athletes"]
  end
end

CONTROLLER (athletes_controller.rb)
class AthletesController < ApplicationController
  def index
    @athletes = Athlete.all
  end
end

Update: I should comment that I can successfully run the GET request via the browser (and see results) via...http://api.espn.com/v1/sports/football/nfl/athletes/?apikey=my_api_key_from_espn

Thanks. This is my first post to StackOverflow so open to feedback on approach/format of my question.


Solution

  • I got it working and here's my revised method syntax for Athlete.all. Basically, the athletes API response array needs to be walked a bit deeper than the headlines api.

    class Athlete
     include HTTParty
     base_uri 'http://api.espn.com/v1/sports'
    
      def self.all
        response = Athlete.get('/football/nfl/athletes',
          :query => { :apikey => 'my_api_key_from_espn' })
        response['sports'].first['leagues'].first['athletes']
      end
    end
    

    For good measure, here's my app/views/athletes/index.html.erb syntax:

    <ul id="athletes">
      <% @athletes.each do |item| %>
        <li class="item"><%= link_to item["displayName"], item["links"]["web"]["athletes"]["href"] %></li>
      <% end %>
    </ul>
    

    (Special thanks to @ivanoats and of course @deefour on this.)