HOW TO GET ALL TEAMS AND PLAYERS FROM A LEAGUE ID

  • December 14, 2021
  • API SPORTS

In this tutorial we will see the most efficient way to get all the teams and players of a competition. We will do this in PHP but the logic applied can be done in any programming language.

To make the API calls you will need your API-KEY which can be found in the profile section of the dashboard. If you don't have one yet you can create an account for free.

For this example we will get all the teams and players of the ENGLAND PREMIER LEAGUE for the season 2021-2022. The id of this competition is 39.

If you want to do this on another competition but you don't know its ID, it is possible to retrieve them by calling the endpoint leagues without parameters or to search them directly on the Dashboard:


Feel free to test these scripts with the competitions of your choice.
Note: Not all competitions have the same coverage, it is better to check before making calls to the API if this competition has the data you are looking for. You will find this information in the endpoint leagues and thanks to the coverage fields.

RETRIEVE ALL THE TEAMS FROM THE COMPETITION
A single call to the API is enough to collect all the teams of a competition and for that we will use the endpoint teams with the following parameters:
- league 39
- season 2021

$curl = curl_init();
curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://v3.football.api-sports.io/teams?league=39&season=2021',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'GET',
  CURLOPT_HTTPHEADER => array(
    'x-rapidapi-key: YOUR_API_KEY_HERE'
  ),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;


The API returns the following answer which contains all 20 teams for this season. (We have kept only the first two for a better readability)

{
    "get": "teams",
    "parameters": {
        "league": "39",
        "season": "2021"
    },
    "errors": [],
    "results": 20,
    "paging": {
        "current": 1,
        "total": 1
    },
    "response": [
        {
            "team": {
                "id": 33,
                "name": "Manchester United",
                "code": "MUN",
                "country": "England",
                "founded": 1878,
                "national": false,
                "logo": "https://media.api-sports.io/football/teams/33.png"
            },
            "venue": {
                "id": 556,
                "name": "Old Trafford",
                "address": "Sir Matt Busby Way",
                "city": "Manchester",
                "capacity": 76212,
                "surface": "grass",
                "image": "https://media.api-sports.io/football/venues/556.png"
            }
        },
        {
            "team": {
                "id": 34,
                "name": "Newcastle",
                "code": "NEW",
                "country": "England",
                "founded": 1892,
                "national": false,
                "logo": "https://media.api-sports.io/football/teams/34.png"
            },
            "venue": {
                "id": 562,
                "name": "St. James' Park",
                "address": "St. James' Street",
                "city": "Newcastle upon Tyne",
                "capacity": 52389,
                "surface": "grass",
                "image": "https://media.api-sports.io/football/venues/562.png"
            }
        },
        {...}



RETRIEVE ALL THE PLAYERS FROM THE COMPETITION
We will now collect all the players for our competition. For this we will use the endpoint players.
Note: This endpoint uses a pagination system with 20 results per page, so we will have to adapt our scripts or make a recursive function in order to get all the expected results.

According to the documentation it is possible to get all the players for a team and a season but it would imply to call the API as many times as there are teams in this competition and even more if a team has more than 20 players (due to the pagination). This method is not optimal to get all the players of the competition.

Fortunately it is possible to call this endpoint with the league and season parameters, so we will have to call the API to get the first page containing the first 20 players and then add the page parameter to get the next players and so on for all the available pages.

Let's try

$curl = curl_init();
curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://v3.football.api-sports.io/players?league=39&season=2021',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'GET',
  CURLOPT_HTTPHEADER => array(
    'x-rapidapi-key: YOUR_API_KEY_HERE'
  ),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;


Return

{
    "get": "players",
    "parameters": {
        "league": "39",
        "season": "2021"
    },
    "errors": [],
    "results": 20,
    "paging": {
        "current": 1,
        "total": 39
    },
    "response": [
        {
            "player": {
                "id": 625,
                "name": "P. Sandler",
                "firstname": "Philippe",
                "lastname": "Sandler",
                "age": 25,
                "birth": {
                    "date": "1997-02-10",
                    "place": "Amsterdam",
                    "country": "Netherlands"
                },
                "nationality": "Netherlands",
                "height": "188 cm",
                "weight": "76 kg",
                "injured": false,
                "photo": "https://media.api-sports.io/football/players/625.png"
            },
            "statistics": [
                {
                    "team": {
                        "id": 50,
                        "name": "Manchester City",
                        "logo": "https://media.api-sports.io/football/teams/50.png"
                    },
                    "league": {
                        "id": 39,
                        "name": "Premier League",
                        "country": "England",
                        "logo": "https://media.api-sports.io/football/leagues/39.png",
                        "flag": "https://media.api-sports.io/flags/gb.svg",
                        "season": 2021
                    },
                    "games": {
                        "appearences": 0,
                        "lineups": 0,
                        "minutes": 0,
                        "number": null,
                        "position": "Defender",
                        "rating": null,
                        "captain": false
                    },
                    "substitutes": {
                        "in": 0,
                        "out": 0,
                        "bench": 0
                    },
                    "shots": {
                        "total": null,
                        "on": null
                    },
                    "goals": {
                        "total": 0,
                        "conceded": null,
                        "assists": null,
                        "saves": null
                    },
                    "passes": {
                        "total": null,
                        "key": null,
                        "accuracy": null
                    },
                    "tackles": {
                        "total": null,
                        "blocks": null,
                        "interceptions": null
                    },
                    "duels": {
                        "total": null,
                        "won": null
                    },
                    "dribbles": {
                        "attempts": null,
                        "success": null,
                        "past": null
                    },
                    "fouls": {
                        "drawn": null,
                        "committed": null
                    },
                    "cards": {
                        "yellow": 0,
                        "yellowred": 0,
                        "red": 0
                    },
                    "penalty": {
                        "won": null,
                        "commited": null,
                        "scored": null,
                        "missed": null,
                        "saved": null
                    }
                }
            ]
        },
        {...}


The API sends us 20 players with the teams they belong to and also their playing statistics for the season.
But now we need to get all the other players and if we look at the response of the API, it tells us we are on page 1 of 39.

"paging": {
    "current": 1,
    "total": 39
},


We will have to call this endpoint by specifying the desired page by adding the page parameter and this until we reach page 39, and we will have all the data we need.

For this we have two solutions:
- Make a loop that starts from 2 to 39 (as we have already recovered page 1) and calls the API. (Not optimal)
- Create a recursive function that calls back the API until it reaches the last page. (Optimal)

The non-optimal method would be to generate a code like this:

for ($i=2; $i <= 39; $i++) {

    $curl = curl_init();
    curl_setopt_array($curl, array(
      CURLOPT_URL => 'https://v3.football.api-sports.io/players?league=39&season=2021&page='.$i,
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => '',
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 0,
      CURLOPT_FOLLOWLOCATION => true,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => 'GET',
      CURLOPT_HTTPHEADER => array(
        'x-rapidapi-key: YOUR_API_KEY_HERE'
      ),
    ));
    $response = curl_exec($curl);
    curl_close($curl);
    echo $response;
}


Although we obtain the desired data, this method is to be left aside because the number of pages for each league could be different and we prefer that it is optimized to work with each of the API competitions.

The best way to proceed when an endpoint has a paging system is to make a recursive function that will automatically detect if there is more than one page to call to get all the data.

What should our function be capable of to recover all the players whatever the competition and whatever the number of pages:
- Detect the number of pages
- Detect the current page
- Stop after calling the last one
- Send back the whole data
- Delaying API calls*
*Note: The API having a ratelimit per minute (depending on your subscribed plan) it will thus be necessary to delay certain calls to the API in order not to have errors 429 - Too Many Requests and thus not retrieve all the data.

For a better readability of the script we will also create a function that contains the CURL call to the API and on which we can dynamically modify the parameters.

Let's start with this function that we will name call_api().

function call_api($endpoint, $params = []) {

    $parameters = '';
    if (count($params) > 0) {
        $parameters = '?'.http_build_query($params);
    }

    $curl = curl_init();
    curl_setopt_array($curl, array(
      CURLOPT_URL => 'https://v3.football.api-sports.io/'.$endpoint.$parameters,
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => '',
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 0,
      CURLOPT_FOLLOWLOCATION => true,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => 'GET',
      CURLOPT_HTTPHEADER => array(
        'x-rapidapi-key: YOUR_API_KEY_HERE'
      ),
    ));
    $response = curl_exec($curl);
    $response = json_decode($response);
    curl_close($curl);
    return $response;
}


To call the API we just have to call this function and specify the 2 parameters it expects:
- The endpoint to call
- The parameters linked to the endpoint

Let's move on to the creation of our recursive function which we will name players_data().

function players_data($league, $season, $page = 1, $players_data = []) {

    $players = call_api('players', ['league' => $league, 'season' => $season, 'page' => $page]);
    $players_data = array_merge($players_data, $players->response);

    if ($players->paging->current < $players->paging->total) {

        $page = $players->paging->current + 1;
        if ($page%2 == 1) {
            sleep(1);
        }
        $players_data = players_data($league, $season, $page, $players_data);
    }
    return $players_data;
}


How it works?
The function expects 4 parameters:
- league 39
- season 2021
- page
- players_data
Only league and season are necessary to launch it since by default the page parameter is set to 1 and the array containing the players is empty by default.

Let's see how it works line by line:

$players = call_api('players', ['league' => $league, 'season' => $season, 'page' => $page]);

The players_data() function calls the API via our call_api() function with the necessary parameters. and stores the API response in the $players variable.

$players_data = array_merge($players_data, $players->response);

The array $player_data is filled with the data contained in the object $players->response.

if ($players->paging->current < $players->paging->total) { ... }

The code contained in this condition is executed as long as we haven't reached the last page of the API data.
Let's take a closer look at the contents:

$page = $players->paging->current + 1;

We increase the page parameter value by +1 in relation to the page we are on.

if ($page%2 == 1) {
    sleep(1);
}

This condition tests if the next page is even or odd and in the case of an odd page the script pauses for 1 second, in order to avoid reaching the rateLimit per minute. This piece of script is not necessarily mandatory depending on the plan you use.

$players_data = players_data($league, $season, $page, $players_data);

Finally, the function will call itself with the new $page parameter and so on until it reaches the last page.

return $players_data;

Once the last page is reached the function returns the array $players_data containing all the players of the competition.

By running the script we get 771 results because page 39 had only 11 players. so if we calculate 38 pages x 20 players + the 11 players of the last page. (38x20)+11 = 771. We have therefore recovered all the players and their statistics.

Here is the whole script, you just have to copy it and add your API-KEY. Feel free to improve it.

function call_api($endpoint, $params = []) {

    $parameters = '';
    if (count($params) > 0) {
        $parameters = '?'.http_build_query($params);
    }

    $curl = curl_init();
    curl_setopt_array($curl, array(
      CURLOPT_URL => 'https://v3.football.api-sports.io/'.$endpoint.$parameters,
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => '',
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 0,
      CURLOPT_FOLLOWLOCATION => true,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => 'GET',
      CURLOPT_HTTPHEADER => array(
        'x-rapidapi-key: YOUR_API_KEY_HERE'
      ),
    ));
    $response = curl_exec($curl);
    $response = json_decode($response);
    curl_close($curl);
    return $response;
}

function players_data($league, $season, $page = 1, $players_data = []) {

    $players = call_api('players', ['league' => $league, 'season' => $season, 'page' => $page]);
    $players_data = array_merge($players_data, $players->response);

    if ($players->paging->current < $players->paging->total) {

        $page = $players->paging->current + 1;
        if ($page%2 == 1) {
            sleep(1);
        }
        $players_data = players_data($league, $season, $page, $players_data);
    }
    return $players_data;
}

// Get all the teams from this competition
$teams = call_api('teams', ['league' => 39, 'season' => 2021]);
var_dump($teams); // To display the results if necessary

// Get all the players from this competition
$players = players_data(39, 2021);
var_dump($players); // To display the results if necessary