create an api call to gather nba player stats in ruby

To create an API call to gather NBA player stats in Ruby, we can use the httparty gem which makes HTTP requests and handles responses easily.

Here’s an example code block that shows how to use httparty to gather player stats from the NBA API.

main.rb
require 'httparty'

url = "http://stats.nba.com/stats/commonallplayers/?LeagueID=00&Season=2018-19&IsOnlyCurrentSeason=1"
headers = {
  "User-Agent" => "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"
}

response = HTTParty.get(url, headers: headers)
player_data = response.parsed_response["resultSets"][0]["rowSet"]

player_data.each do |player|
  player_name = player[2]
  player_id = player[0]
  stats_url = "http://stats.nba.com/stats/playerprofilev2/?PlayerID=#{player_id}&PerMode=Totals&Season=2018-19&LeagueID=00"

  stats_response = HTTParty.get(stats_url, headers: headers)
  player_stats = stats_response.parsed_response["resultSets"][0]["rowSet"]

  puts "Player Name: #{player_name}"
  puts "Player Stats: #{player_stats}"
  puts "======================================="
end
857 chars
23 lines

In this example, we first fire a GET request to the NBA API to get all current players in the league. We then filter the necessary data and loop through each player to get their individual stats. Finally, we print out the player name and stats for each player.

gistlibby LogSnag