Using the Ball Don't Lie API with JavaScript

Ball Don't Lie is a popular public API that can be used to obtain basketball statistics. In this blog post, we'll take a look at how to use this API in JavaScript.

Getting Started

Before we can start using the Ball Don't Lie API, we need to obtain an API key. To do this, visit the Ball Don't Lie website (https://balldontlie.io) and sign up for an account. Once you have your API key, we can start making requests to the API.

Making a Request

To make a request to the Ball Don't Lie API, we can use the fetch function in JavaScript. Here's an example of how to make a request for the player with the ID of 237:

fetch('https://api.balldontlie.io/v1/players/237')
  .then(response => response.json())
  .then(data => console.log(data))

This code will make a GET request to the Ball Don't Lie API with the specified URL. The response from the API will be converted to a JSON object, and the data will be logged to the console.

Filtering Results

Sometimes we want to filter the data we receive from the Ball Don't Lie API. For example, if we only want to see players who play for the New York Knicks, we can make a request like this:

fetch('https://api.balldontlie.io/v1/players?team_id=20')
  .then(response => response.json())
  .then(data => console.log(data))

In this example, we've added a query parameter to the URL (team_id=20) to specify that we only want to see players who play for the New York Knicks (team ID 20).

Pagination

The Ball Don't Lie API limits the number of results returned in a single request. To retrieve all of the results, we need to make multiple requests using pagination. Here's an example of how to retrieve all of the games from the 2019-2020 season:

let page = 1
let games = []

const getGames = () => {
  fetch(`https://api.balldontlie.io/v1/games?page=${page}&seasons[]=2019&seasons[]=2020`)
    .then(response => response.json())
    .then(data => {
      games = games.concat(data.data)
      if (data.meta.next_page !== null) {
        page++
        getGames()
      } else {
        console.log(games)
      }
    })
}
getGames()

In this example, we've defined a getGames function that makes a request to the Ball Don't Lie API for a single page of games. We then use recursion to call the getGames function again with the next page until there are no more pages left. The data from each page is added to an array (games) until we have all of the games from the 2019-2020 season.

Conclusion

Using the Ball Don't Lie API in JavaScript is a great way to obtain basketball statistics for your application. With a little bit of JavaScript knowledge, you can easily make requests to the API and filter the results. The examples in this blog post should give you a good starting point for using the Ball Don't Lie API in your own applications.

Related APIs