Live now!

Progress of current post

A Developer’s Guide: Unleashing the Potential of Sportmonks Football API with PHP

PHP is a versatile and powerful programming language that developers leverage to build dynamic web applications. In this guide, we’ll explore how to harness the capabilities of the Sportmonks’ Football API using PHP. Whether creating a football statistics website, a fantasy football platform, or any other football-related application, integrating our Football API can provide rich data to enhance your project.

 

Time to read 20 min
Published 22 April 2024
Last updated 7 March 2025
Wesley Van Rooij
A Developer’s Guide: Unleashing the Potential of Sportmonks Football API with PHP
Contents

Why choose Sportmonks’ Football API for your PHP application?

The Football API offers a comprehensive and reliable source of football-related data, making it an excellent choice for developers looking to enhance their awesome applications. Enjoy a vast array of football data, including fixtures, live scores, player statistics, team information, and more. Whether you’re building a football statistics website, a fantasy football platform, or a mobile app for football fans, Sportmonks’ Football API offers the data you need to create engaging and informative user experiences. Check our coverage page for a complete list of features and available Football Leagues & Cups. In this guide, we will learn how to use PHP with our API. We will dive into these chapters:

  1. Authentication
  2. Make your first API request
  3. Request season teams
  4. Request player season stats
  5. Recap

Why PHP?

PHP is a popular language with server-side scripting that powers a significant portion of the web, making it an excellent choice for building dynamic and interactive web applications. PHP boasts a rich ecosystem of code libraries, frameworks, and tools that streamline the development process and enable you to build robust and scalable applications quickly. Whether you prefer lightweight frameworks like Slim or full-stack frameworks like Laravel, PHP offers a range of options to suit your development needs. Many developers are already familiar with PHP’s syntax and conventions, making it easy to integrate the Football API into existing PHP projects or learn the language from scratch. With its intuitive and straightforward syntax, PHP enables developers to focus on building functionality rather than wrestling with complex language features.

Sportmonks’ Football API with PHP

In the upcoming sections, we’ll walk you through configuring your development environment, initiating fundamental API calls, accessing details about football leagues, retrieving teams, squads and detailed player statistics. Each segment will showcase hands-on examples and code snippets.

Upon completing this guide, you’ll possess the expertise and resources to fully leverage Sportmonks’ Football API, enabling you to craft football applications with PHP and Laravel.

So, without further ado, let’s start developing!

1. Getting started 

1.1 Create your API token

Before you begin integrating the API into your Laravel application, it’s essential to register at MySportmonks and create your unique API token. This token serves to authenticate requests. Once you have your API token, you can integrate the API for Football Data into your amazing application using Laravel.

1.2 Authentication

Authenticating your requests to the Football API is essential to ensure secure access to the data. Your API token is a unique identifier, allowing us to validate your identity and authorize your requests. In this how-to guide, we discuss three different request methods.

Authentication using PHP

You can authenticate your requests to the Football API using PHP cURL by including the API token in the request headers. Here’s how you can do it:

$apiToken = 'YOUR_API_TOKEN';
$endpoint = 'https://api.sportmonks.com/v3/football/leagues';

// Execute request
$response = file_get_contents($endpoint, false, stream_context_create([
  'http' => [
    'header' => [
      "Authorization: $api_key\r\n"
    ]
  ]
]));

// Check for errors
if ($response === false) {
  echo 'An error occurred';
} else {
  // Print API response
  echo $response;
}

Using Laravel HTTP Client

With Laravel’s built-in HTTP client, you can seamlessly authenticate your requests by including the API token in the request headers. Here’s how you can do it:

use Illuminate\Support\Facades\Http;

$apiToken = 'YOUR_API_TOKEN';
$endpoint = 'https://api.sportmonks.com/v3/football/leagues';

try {
    $response = Http::withHeaders([
        'Content-Type' => 'application/json',
        'Accept' => 'application/json',
        'Authorization' => 'Bearer ' . $apiToken,
    ])->get($endpoint);

    // Handle response...
} catch (Exception $e) {
    // Handle exceptions...
}

Authentication using Laravel Controller Method

If you prefer organizing your authentication logic within a controller, you can utilize Laravel controller methods to handle the authentication process. Here’s how you can integrate authentication within your SportmonksApiController:

baseUrl . $endpoint;

        // And we'll append the query parameters (like includes and filters)
        if(!empty($query)) {
            $url .= '?' . http_build_query($query);
        }

        // Authenticate using the token, send the request, and parse the JSON to an array
        return Http::withHeaders(['Authorization' => $this->apiToken])
            ->get($url)
            ->json();
    }
}
Adding Route

To execute the Laravel Controller Method request, you need to add additional code.

Adding Route::controller(SportmonksApiController::class)->group() in your Laravel routes file allows you to map HTTP requests to methods within your SportmonksApiController. This approach provides a clean and organized way to handle different API endpoints related to the Sportmonks Football API.

Here’s an explanation of why you might need to add this and where you should add it:

– Organized routing: By grouping routes related to the Sportmonks Football API under a single controller, you maintain a clear and structured routing setup in your Laravel application.

– Code consistency: Grouping routes under a controller ensures consistency in how you handle requests related to the Sportmonks API. It’s easier to manage and update your code when all related logic is contained within one controller class.

– Controller approach: Utilizing controllers for routing allows you to encapsulate request handling logic, improving code readability and maintainability.

You should add the Route::controller(SportmonksApiController::class)->group()statement in your Laravel routes file, typically located at routes/web.php.

Here’s how you can do it:

use App\Http\Controllers\SportmonksApiController;
use Illuminate\Support\Facades\Route;

Route::controller(SportmonksApiController::class)->group(function () {
    Route::get('/leagues', 'leagues');
    Route::get('/leaguesWithCurrentSeason', 'leaguesWithCurrentSeason');
    Route::get('/seasonTeams', 'seasonTeams');
    Route::get('/seasonTeamsWithPlayerNames', 'seasonTeamsWithPlayerNames');
    Route::get('/playerSeasonStatistics', 'playerSeasonStatistics');
    Route::get('/previousPlayerSeasonStatistics', 'previousPlayerSeasonStatistics');
});

In this setup:

SportmonksApiController::class specifies the controller class to use.

Route::controller() binds routes to methods in the specified controller.

->group() wraps the routes to apply any shared middleware or route attributes.

By adding these routes, you define how different Sportmonks Football API endpoints are accessed within your Laravel application, all managed through the methods defined in your SportmonksApiController.

Let’s start developing

In this comprehensive guide, we will explore three methods for integrating the Football API into your Football application:

Authentication using PHP cURL: This method involves using PHP’s cURL library to authenticate requests to the Football API. By including the API token in the request headers, you can securely access the data.

Authentication using Laravel’s Built-in HTTP Client: Laravel provides a convenient built-in HTTP client that allows seamless authentication with the Football API. By including the API token in the request headers, you ensure secure communication between your application and the API.

Authentication using Laravel Controller Method: Leveraging Laravel’s controller method, you can encapsulate request handling logic for authentication and data retrieval. This approach offers a structured and organized way to manage API endpoints within your Laravel application.

Each method offers its advantages in terms of flexibility, ease of implementation, and maintainability, allowing you to choose the approach that best fits your application’s requirements.

2. Making your first request

Let’s start with the beginning of almost every football application: displaying the leagues. Now, based on your subscription, the response is different. We will opt for the Enterprise Plan for this how-to guide, which means we can access every football league. You can use one of our League API endpoints to gather data from the leagues you’ve access to. Let’s break down the process and explore the different ways we can accomplish this task.

Using cURL PHP Requests:

We started by employing cURL PHP requests to interact with the Sportmonks API. This method involves initializing a cURL session, setting the necessary options such as the API endpoint and headers, executing the request, and handling the response. This approach provides a low-level interface for making HTTP requests in PHP.

Laravel option 1: Utilizing Laravel’s Built-in HTTP Client

This option directly uses Laravel’s HTTP client (Http::) to make a GET request to the specified endpoint. It handles the request and response within the same method, providing error handling for both successful and failed requests.

Laravel option 2: Using a Controller Method

This option involves defining a controller method (leagues()) that internally calls another method (requestEndpoint()) to make the HTTP request. The requestEndpoint() method handles the HTTP request logic and returns the response, which is then returned as a JsonResponse from the leagues() method.

Key differences between option 1 and 2:

Direct Usage vs. Controller Method: Option 1 directly uses Laravel’s HTTP client in the controller, while Option 2 encapsulates the HTTP request logic within a separate method called by the controller.

Error Handling: Option 1 includes error handling within the same method, while Option 2 delegates error handling to the requestEndpoint() method or relies on Laravel’s default error handling mechanism.

Return Type: Option 1 returns the JSON response directly from the controller method, while Option 2 returns a JsonResponse object generated from the response returned by the requestEndpoint() method.

Both options achieve the same goal of making an HTTP request to retrieve a list of football leagues from the Sportmonks API, but they differ in their implementation approach and error handling strategy. Choose the option that best fits your application’s requirements and coding preferences.

For example, your request to the GET All Leagues endpoint looks like this:

 [
    'header' => [
      "Authorization: $api_key\r\n"
    ]
  ]
]));

// Check for errors
if ($response === false) {
  echo 'An error occurred';
} else {
  // Print API response
  echo $response;
}

 'application/json',
        'Accept' => 'application/json',
        'Authorization' => $api_key // Include the API key in the Authorization header
    ])->get($endpoint);

    // Check if request was successful
    if ($response->successful()) {
        // Return the JSON response
        return $response->json();
    } else {
        // Return error message
        return response()->json(['error' => 'Request failed'], $response->status());
    }
} catch (Exception $e) {
    // Return error message if an exception occurs
    return response()->json(['error' => $e->getMessage()], 500);
}
// 2. Making your first request
    public function leagues(): JsonResponse
    {
        // https://api.sportmonks.com/v3/football/leagues
        $response = $this->requestEndpoint('/football/leagues');
        return new JsonResponse($response);
    }
{
    "data": [
        {
            "id": 2,
            "sport_id": 1,
            "country_id": 41,
            "name": "Champions League",
            "active": true,
            "short_code": "UEFA CL",
            "image_path": "https://cdn.sportmonks.com/images/soccer/leagues/2.png",
            "type": "league",
            "sub_type": "cup_international",
            "last_played_at": "2024-04-17 19:00:00",
            "category": 1,
            "has_jerseys": false
        },
        {
            "id": 5,
            "sport_id": 1,
            "country_id": 41,
            "name": "Europa League",
            "active": true,
            "short_code": "UEFA EL",
            "image_path": "https://cdn.sportmonks.com/images/soccer/leagues/5/5.png",
            "type": "league",
            "sub_type": "cup_international",
            "last_played_at": "2024-04-18 19:00:00",
            "category": 1,
            "has_jerseys": false
        },
        {
            "id": 8,
            "sport_id": 1,
            "country_id": 462,
            "name": "Premier League",
            "active": true,
            "short_code": "UK PL",
            "image_path": "https://cdn.sportmonks.com/images/soccer/leagues/8/8.png",
            "type": "league",
            "sub_type": "domestic",
            "last_played_at": "2024-04-15 19:00:00",
            "category": 1,
            "has_jerseys": false
        },
//and more!

With this request, you’ve received a list of leagues you can access. Are you interested in each league’s active season? Use the currentSeason include on the endpoint, and you’re good to go!

 [
    'header' => [
      "Authorization: $api_key\r\n"
    ]
  ]
]));

// Check for errors
if ($response === false) {
  echo 'An error occurred';
} else {
  // Print API response
  echo $response;
}
 'application/json',
        'Accept' => 'application/json',
        'Authorization' => $api_key // Include the API key in the Authorization header
    ])->get($endpoint);

    // Check if request was successful
    if ($response->successful()) {
        // Return the JSON response
        return $response->json();
    } else {
        // Return error message
        return response()->json(['error' => 'Request failed'], $response->status());
    }
} catch (Exception $e) {
    // Return error message if an exception occurs
    return response()->json(['error' => $e->getMessage()], 500);
}
public function leaguesWithCurrentSeason(): JsonResponse
{
    // https://api.sportmonks.com/v3/football/leagues?include=currentSeason
    $response = $this->requestEndpoint('/football/leagues', [
        'include' => 'currentSeason'
    ]);

    return new JsonResponse($response);
}
{
    "data": [
        {
            "id": 2,
            "sport_id": 1,
            "country_id": 41,
            "name": "Champions League",
            "active": true,
            "short_code": "UEFA CL",
            "image_path": "https://cdn.sportmonks.com/images/soccer/leagues/2.png",
            "type": "league",
            "sub_type": "cup_international",
            "last_played_at": "2024-04-17 19:00:00",
            "category": 1,
            "has_jerseys": false,
            "currentseason": {
                "id": 21638,
                "sport_id": 1,
                "league_id": 2,
                "tie_breaker_rule_id": 170,
                "name": "2023/2024",
                "finished": false,
                "pending": false,
                "is_current": true,
                "starting_at": "2023-06-27",
                "ending_at": "2024-06-01",
                "standings_recalculated_at": "2023-12-13 21:56:27",
                "games_in_current_week": true
            }
        },
        {
            "id": 5,
            "sport_id": 1,
            "country_id": 41,
            "name": "Europa League",
            "active": true,
            "short_code": "UEFA EL",
            "image_path": "https://cdn.sportmonks.com/images/soccer/leagues/5/5.png",
            "type": "league",
            "sub_type": "cup_international",
            "last_played_at": "2024-04-18 19:00:00",
            "category": 1,
            "has_jerseys": false,
            "currentseason": {
                "id": 22130,
                "sport_id": 1,
                "league_id": 5,
                "tie_breaker_rule_id": 171,
                "name": "2023/2024",
                "finished": false,
                "pending": false,
                "is_current": true,
                "starting_at": "2023-08-08",
                "ending_at": "2024-05-22",
                "standings_recalculated_at": "2023-12-14 21:57:27",
                "games_in_current_week": true
            }
        },
        {
            "id": 8,
            "sport_id": 1,
            "country_id": 462,
            "name": "Premier League",
            "active": true,
            "short_code": "UK PL",
            "image_path": "https://cdn.sportmonks.com/images/soccer/leagues/8/8.png",
            "type": "league",
            "sub_type": "domestic",
            "last_played_at": "2024-04-15 19:00:00",
            "category": 1,
            "has_jerseys": false,
            "currentseason": {
                "id": 21646,
                "sport_id": 1,
                "league_id": 8,
                "tie_breaker_rule_id": 171,
                "name": "2023/2024",
                "finished": false,
                "pending": false,
                "is_current": true,
                "starting_at": "2023-08-11",
                "ending_at": "2024-05-19",
                "standings_recalculated_at": "2024-04-15 21:00:54",
                "games_in_current_week": true
            }
        },
//and more!

Full Laravel Controller Method request so far:

baseUrl . $endpoint;

        // And we'll append the query parameters (like includes and filters)
        if(!empty($query)) {
            $url .= '?' . http_build_query($query);
        }

        // Authenticate using the token, send the request, and parse the JSON to an array
        return Http::withHeaders(['Authorization' => $this->apiToken])
            ->get($url)
            ->json();
    }

    // 2. Making your first request
    public function leagues(): JsonResponse
    {
        // https://api.sportmonks.com/v3/football/leagues
        $response = $this->requestEndpoint('/football/leagues');
        return new JsonResponse($response);
    }

    public function leaguesWithCurrentSeason(): JsonResponse
    {
        // https://api.sportmonks.com/v3/football/leagues?include=currentSeason
        $response = $this->requestEndpoint('/football/leagues', [
            'include' => 'currentSeason'
        ]);

        return new JsonResponse($response);
    }
Route::controller(SportmonksApiController::class)->group(function () {
    Route::get('/leagues', 'leagues');
    Route::get('/leaguesWithCurrentSeason', 'leaguesWithCurrentSeason');
    Route::get('/seasonTeams', 'seasonTeams');
    Route::get('/seasonTeamsWithPlayerNames', 'seasonTeamsWithPlayerNames');
    Route::get('/playerSeasonStatistics', 'playerSeasonStatistics');
    Route::get('/previousPlayerSeasonStatistics', 'previousPlayerSeasonStatistics');
});

You can use the season IDs in another API request, like for example, in the next chapter, we will request the squads of the English Premier League teams in the 2023/2024 season (season ID;  21646)

3. Request season teams

Now that we have the English Premier League’s current season ID, we can request the IDs of all the teams participating in the season. We will use the Teams by Season ID endpoint for this. Via this endpoint, you receive all the teams of the season you’re interested in. In our case, the 2023/2024 English Premier League.

 [
    'header' => [
      "Authorization: $api_key\r\n"
    ]
  ]
]));

// Check for errors
if ($response === false) {
  echo 'An error occurred';
} else {
  // Print API response
  echo $response;
}

 'application/json',
        'Accept' => 'application/json',
        'Authorization' => $api_key // Include the API key in the Authorization header
    ])->get($endpoint);

    // Check if request was successful
    if ($response->successful()) {
        // Return the JSON response
        return $response->json();
    } else {
        // Return error message
        return response()->json(['error' => 'Request failed'], $response->status());
    }
} catch (Exception $e) {
    // Return error message if an exception occurs
    return response()->json(['error' => $e->getMessage()], 500);
}
// 3. Request season teams
 public function seasonTeams(): JsonResponse
 {
     // https://api.sportmonks.com/v3/football/teams/seasons/21646
     $response = $this->requestEndpoint('/football/teams/seasons/21646');

     return new JsonResponse($response);
 }
{
    "data": [
        {
            "id": 78,
            "sport_id": 1,
            "country_id": 462,
            "venue_id": 480,
            "gender": "male",
            "name": "Brighton & Hove Albion",
            "short_code": "BHA",
            "image_path": "https://cdn.sportmonks.com/images/soccer/teams/14/78.png",
            "founded": 1901,
            "type": "domestic",
            "placeholder": false,
            "last_played_at": "2024-04-13 14:00:00"
        },
        {
            "id": 11,
            "sport_id": 1,
            "country_id": 462,
            "venue_id": 485,
            "gender": "male",
            "name": "Fulham",
            "short_code": "FUL",
            "image_path": "https://cdn.sportmonks.com/images/soccer/teams/11/11.png",
            "founded": 1879,
            "type": "domestic",
            "placeholder": false,
            "last_played_at": "2024-04-14 13:00:00"
        },
        {
            "id": 8,
            "sport_id": 1,
            "country_id": 462,
            "venue_id": 230,
            "gender": "male",
            "name": "Liverpool",
            "short_code": "LIV",
            "image_path": "https://cdn.sportmonks.com/images/soccer/teams/8/8.png",
            "founded": 1892,
            "type": "domestic",
            "placeholder": false,
            "last_played_at": "2024-04-18 19:00:00"
        },
        {
            "id": 19,
            "sport_id": 1,
            "country_id": 462,
            "venue_id": 204,
            "gender": "male",
            "name": "Arsenal",
            "short_code": "ARS",
            "image_path": "https://cdn.sportmonks.com/images/soccer/teams/19/19.png",
            "founded": 1886,
            "type": "domestic",
            "placeholder": false,
            "last_played_at": "2024-04-17 19:00:00"
        },
//and more!

Quite cool, isn’t it? Suppose you’re building a fantasy game, and you need a complete list of the players per team. You can use various includes and even filters for this. In our case, we want the players (via the players.player include), but only the display name of the players using the select syntax. Check our filter and select tutorial for more information.  

 [
    'header' => [
      "Authorization: $api_key\r\n"
    ]
  ]
]));

// Check for errors
if ($response === false) {
  echo 'An error occurred';
} else {
  // Print API response
  echo $response;
}

 'application/json',
        'Accept' => 'application/json',
        'Authorization' => $api_key // Include the API key in the Authorization header
    ])->get($endpoint);

    // Check if request was successful
    if ($response->successful()) {
        // Return the JSON response
        return $response->json();
    } else {
        // Return error message
        return response()->json(['error' => 'Request failed'], $response->status());
    }
} catch (Exception $e) {
    // Return error message if an exception occurs
    return response()->json(['error' => $e->getMessage()], 500);
}
public function seasonTeamsWithPlayerNames(): JsonResponse
 {
     // https://api.sportmonks.com/v3/football/teams/seasons/21646?include=players.player:display_name
     $response = $this->requestEndpoint('/football/teams/seasons/21646', [
         'include' => 'players.player:display_name',
     ]);

     return new JsonResponse($response);
 }
{
    "id": 19,
    "sport_id": 1,
    "country_id": 462,
    "venue_id": 204,
    "gender": "male",
    "name": "Arsenal",
    "short_code": "ARS",
    "image_path": "https://cdn.sportmonks.com/images/soccer/teams/19/19.png",
    "founded": 1886,
    "type": "domestic",
    "placeholder": false,
    "last_played_at": "2024-04-17 19:00:00",
    "players": [
        {
            "id": 633774,
            "transfer_id": 183831,
            "player_id": 61780,
            "team_id": 19,
            "position_id": 27,
            "detailed_position_id": 152,
            "start": "2023-01-20",
            "end": "2026-06-30",
            "captain": false,
            "jersey_number": 19,
            "player": {
                "id": 61780,
                "country_id": 556,
                "sport_id": 1,
                "city_id": null,
                "position_id": 27,
                "detailed_position_id": 152,
                "nationality_id": 556,
                "display_name": "Leandro Trossard"
            }
        },
        {
            "id": 874920,
            "transfer_id": null,
            "player_id": 37676786,
            "team_id": 19,
            "position_id": 25,
            "detailed_position_id": null,
            "start": null,
            "end": null,
            "captain": false,
            "jersey_number": 79,
            "player": {
                "id": 37676786,
                "country_id": 462,
                "sport_id": 1,
                "city_id": null,
                "position_id": 25,
                "detailed_position_id": null,
                "nationality_id": 462,
                "display_name": "A. Heaven"
            }
        },
        {
            "id": 840512,
            "transfer_id": null,
            "player_id": 5329,
            "team_id": 19,
            "position_id": 27,
            "detailed_position_id": null,
            "start": null,
            "end": null,
            "captain": false,
            "jersey_number": 9,
            "player": {
                "id": 5329,
                "country_id": 5,
                "sport_id": 1,
                "city_id": null,
                "position_id": 27,
                "detailed_position_id": 151,
                "nationality_id": 5,
                "display_name": "Gabriel Jesus"
            }
        },

Full Laravel Controller Method request so far:

baseUrl . $endpoint;

        // And we'll append the query parameters (like includes and filters)
        if(!empty($query)) {
            $url .= '?' . http_build_query($query);
        }

        // Authenticate using the token, send the request, and parse the JSON to an array
        return Http::withHeaders(['Authorization' => $this->apiToken])
            ->get($url)
            ->json();
    }

    // 2. Making your first request
    public function leagues(): JsonResponse
    {
        // https://api.sportmonks.com/v3/football/leagues
        $response = $this->requestEndpoint('/football/leagues');
        return new JsonResponse($response);
    }

    public function leaguesWithCurrentSeason(): JsonResponse
    {
        // https://api.sportmonks.com/v3/football/leagues?include=currentSeason
        $response = $this->requestEndpoint('/football/leagues', [
            'include' => 'currentSeason'
        ]);

        return new JsonResponse($response);
    }

    // 3. Request season teams
    public function seasonTeams(): JsonResponse
    {
        // https://api.sportmonks.com/v3/football/teams/seasons/21646
        $response = $this->requestEndpoint('/football/teams/seasons/21646');

        return new JsonResponse($response);
    }

    public function seasonTeamsWithPlayerNames(): JsonResponse
    {
        // https://api.sportmonks.com/v3/football/teams/seasons/21646?include=players.player:display_name
        $response = $this->requestEndpoint('/football/teams/seasons/21646', [
            'include' => 'players.player:display_name',
        ]);

        return new JsonResponse($response);
    }
Route::controller(SportmonksApiController::class)->group(function () {
    Route::get('/leagues', 'leagues');
    Route::get('/leaguesWithCurrentSeason', 'leaguesWithCurrentSeason');
    Route::get('/seasonTeams', 'seasonTeams');
    Route::get('/seasonTeamsWithPlayerNames', 'seasonTeamsWithPlayerNames');
    Route::get('/playerSeasonStatistics', 'playerSeasonStatistics');
    Route::get('/previousPlayerSeasonStatistics', 'previousPlayerSeasonStatistics');
});

In the next chapter, we’ll dive deeper into retrieving specific data, starting with requesting player season statistics. Stay tuned as we continue to unravel the possibilities of integrating the Sportmonks Football API into your Laravel application.

4. Request player season statistics

Last but certainly not least, let’s also request the player statistics. To do so, I recommend using the GET Team Squad by Team ID endpoint (for current-season team squads) or the Squad by Team and Season ID endpoint (for historical team squads). 

For example, if we want a list of all the Arsenal (team ID: 19) players with their current season statistics:

 [
    'header' => [
      "Authorization: $api_key\r\n"
    ]
  ]
]));

// Check for errors
if ($response === false) {
  echo 'An error occurred';
} else {
  // Print API response
  echo $response;
}
 'application/json',
        'Accept' => 'application/json',
        'Authorization' => $api_key // Include the API key in the Authorization header
    ])->get($endpoint);

    // Check if request was successful
    if ($response->successful()) {
        // Return the JSON response
        return $response->json();
    } else {
        // Return error message
        return response()->json(['error' => 'Request failed'], $response->status());
    }
} catch (Exception $e) {
    // Return error message if an exception occurs
    return response()->json(['error' => $e->getMessage()], 500);
}
// 4. Request player season statistics
public function playerSeasonStatistics(): JsonResponse
{
    // https://api.sportmonks.com/v3/football/squads/teams/19?include=player.statistics.details&filters=playerStatisticSeasons:21646
    $response = $this->requestEndpoint('/football/squads/teams/19', [
        'include' => 'player.statistics.details',
        'filters' => 'playerStatisticSeasons:21646'
    ]);

    return new JsonResponse($response);
}
{
    "data": [
        {
            "id": 633774,
            "transfer_id": 183831,
            "player_id": 61780,
            "team_id": 19,
            "position_id": 27,
            "detailed_position_id": 152,
            "start": "2023-01-20",
            "end": "2026-06-30",
            "captain": false,
            "jersey_number": 19,
            "player": {
                "id": 61780,
                "sport_id": 1,
                "country_id": 556,
                "nationality_id": 556,
                "city_id": null,
                "position_id": 27,
                "detailed_position_id": 152,
                "type_id": 26,
                "common_name": "L. Trossard",
                "firstname": "Leandro",
                "lastname": "Trossard",
                "name": "Leandro Trossard",
                "display_name": "Leandro Trossard",
                "image_path": "https://cdn.sportmonks.com/images/soccer/players/20/61780.png",
                "height": 172,
                "weight": 61,
                "date_of_birth": "1994-12-04",
                "gender": "male",
                "statistics": [
                    {
                        "id": 483841395,
                        "player_id": 61780,
                        "team_id": 19,
                        "season_id": 21646,
                        "has_values": true,
                        "position_id": 27,
                        "jersey_number": 19,
                        "details": [
                            {
                                "id": 34125850,
                                "player_statistic_id": 483841395,
                                "type_id": 41,
                                "value": {
                                    "total": 17
                                }
                            },
                            {
                                "id": 33137242,
                                "player_statistic_id": 483841395,
                                "type_id": 42,
                                "value": {
                                    "total": 47
                                }
                            },
                            {
                                "id": 35712299,
                                "player_statistic_id": 483841395,
                                "type_id": 47,
                                "value": {
                                    "total": 0,
                                    "won": 1,
                                    "scored": 0,
                                    "committed": 0,
                                    "saved": 0,
                                    "missed": 0
                                }
                            },
                            {
                                "id": 33137236,
                                "player_statistic_id": 483841395,
                                "type_id": 51,
                                "value": {
                                    "total": 8
                                }
                            },
                            {
                                "id": 33137230,
                                "player_statistic_id": 483841395,
                                "type_id": 52,
                                "value": {
                                    "total": 8,
                                    "goals": 8,
                                    "penalties": 0
                                }
                            },
                            {
                                "id": 33999879,
                                "player_statistic_id": 483841395,
                                "type_id": 56,
                                "value": {
                                    "total": 11
                                }
                            },
                            {
                                "id": 33586089,
                                "player_statistic_id": 483841395,
                                "type_id": 58,
                                "value": {
                                    "total": 12
                                }
                            },
// and more!

Or, if we want a list of all the Arsenal (team ID: 19) players with their season statistics in the 2022/2023 season. 

 [
    'header' => [
      "Authorization: $api_key\r\n"
    ]
  ]
]));

// Check for errors
if ($response === false) {
  echo 'An error occurred';
} else {
  // Print API response
  echo $response;
}
 'application/json',
        'Accept' => 'application/json',
        'Authorization' => $api_key // Include the API key in the Authorization header
    ])->get($endpoint);

    // Check if request was successful
    if ($response->successful()) {
        // Return the JSON response
        return $response->json();
    } else {
        // Return error message
        return response()->json(['error' => 'Request failed'], $response->status());
    }
} catch (Exception $e) {
    // Return error message if an exception occurs
    return response()->json(['error' => $e->getMessage()], 500);
}
  public function previousPlayerSeasonStatistics(): JsonResponse
    {
        // https://api.sportmonks.com/v3/football/squads/seasons/19734/teams/19?include=player;details.type
        $response = $this->requestEndpoint('/football/squads/seasons/19734/teams/19', [
            'include' => 'player;details.type',
        ]);

        return new JsonResponse($response);
    }
}
{
    "data": [
        {
            "id": 520041,
            "player_id": 172960,
            "team_id": 19,
            "season_id": 19734,
            "has_values": true,
            "position_id": 25,
            "jersey_number": 3,
            "player": {
                "id": 172960,
                "sport_id": 1,
                "country_id": 1161,
                "nationality_id": 1161,
                "city_id": null,
                "position_id": 25,
                "detailed_position_id": 155,
                "type_id": 25,
                "common_name": "K. Tierney",
                "firstname": "Kieran",
                "lastname": "Tierney",
                "name": "Kieran Tierney",
                "display_name": "Kieran Tierney",
                "image_path": "https://cdn.sportmonks.com/images/soccer/players/0/172960.png",
                "height": 180,
                "weight": 70,
                "date_of_birth": "1997-06-05",
                "gender": "male"
            },
            "details": [
                {
                    "id": 24424381,
                    "player_statistic_id": 520041,
                    "type_id": 42,
                    "value": {
                        "total": 6
                    },
                    "type": {
                        "id": 42,
                        "name": "Shots Total",
                        "code": "shots-total",
                        "developer_name": "SHOTS_TOTAL",
                        "model_type": "statistic",
                        "stat_group": "offensive"
                    }
                },
                {
                    "id": 28807563,
                    "player_statistic_id": 520041,
                    "type_id": 51,
                    "value": {
                        "total": 1
                    },
                    "type": {
                        "id": 51,
                        "name": "Offsides",
                        "code": "offsides",
                        "developer_name": "OFFSIDES",
                        "model_type": "statistic",
                        "stat_group": "offensive"
                    }
                },
                {
                    "id": 24424290,
                    "player_statistic_id": 520041,
                    "type_id": 56,
                    "value": {
                        "total": 5
                    },
                    "type": {
                        "id": 56,
                        "name": "Fouls",
                        "code": "fouls",
                        "developer_name": "FOULS",
                        "model_type": "statistic",
                        "stat_group": "defensive"
                    }
                },
// and more!

If you’re interested in more in-depth knowledge about fetching team squads, I recommend checking our Football Documentation. 

Final Laravel Controller Method code:

baseUrl . $endpoint;

        // And we'll append the query parameters (like includes and filters)
        if(!empty($query)) {
            $url .= '?' . http_build_query($query);
        }

        // Authenticate using the token, send the request, and parse the JSON to an array
        return Http::withHeaders(['Authorization' => $this->apiToken])
            ->get($url)
            ->json();
    }

    // 2. Making your first request
    public function leagues(): JsonResponse
    {
        // https://api.sportmonks.com/v3/football/leagues
        $response = $this->requestEndpoint('/football/leagues');
        return new JsonResponse($response);
    }

    public function leaguesWithCurrentSeason(): JsonResponse
    {
        // https://api.sportmonks.com/v3/football/leagues?include=currentSeason
        $response = $this->requestEndpoint('/football/leagues', [
            'include' => 'currentSeason'
        ]);

        return new JsonResponse($response);
    }

    // 3. Request season teams
    public function seasonTeams(): JsonResponse
    {
        // https://api.sportmonks.com/v3/football/teams/seasons/21646
        $response = $this->requestEndpoint('/football/teams/seasons/21646');

        return new JsonResponse($response);
    }

    public function seasonTeamsWithPlayerNames(): JsonResponse
    {
        // https://api.sportmonks.com/v3/football/teams/seasons/21646?include=players.player:display_name
        $response = $this->requestEndpoint('/football/teams/seasons/21646', [
            'include' => 'players.player:display_name',
        ]);

        return new JsonResponse($response);
    }

    // 4. Request player season statistics
    public function playerSeasonStatistics(): JsonResponse
    {
        // https://api.sportmonks.com/v3/football/squads/teams/19?include=player.statistics.details&filters=playerStatisticSeasons:21646
        $response = $this->requestEndpoint('/football/squads/teams/19', [
            'include' => 'player.statistics.details',
            'filters' => 'playerStatisticSeasons:21646'
        ]);

        return new JsonResponse($response);
    }

    public function previousPlayerSeasonStatistics(): JsonResponse
    {
        // https://api.sportmonks.com/v3/football/squads/seasons/19734/teams/19?include=player;details.type
        $response = $this->requestEndpoint('/football/squads/seasons/19734/teams/19', [
            'include' => 'player;details.type',
        ]);

        return new JsonResponse($response);
    }
}
Route::controller(SportmonksApiController::class)->group(function () {
    Route::get('/leagues', 'leagues');
    Route::get('/leaguesWithCurrentSeason', 'leaguesWithCurrentSeason');
    Route::get('/seasonTeams', 'seasonTeams');
    Route::get('/seasonTeamsWithPlayerNames', 'seasonTeamsWithPlayerNames');
    Route::get('/playerSeasonStatistics', 'playerSeasonStatistics');
    Route::get('/previousPlayerSeasonStatistics', 'previousPlayerSeasonStatistics');
});

Embracing the Power of Sportmonks’ Football API with PHP

PHP is a stalwart among programming languages, empowering developers to craft dynamic web applications quickly. In this guide, we’ve delved into the realm of Sportmonks’ Football API, exploring how PHP is an invaluable tool for leveraging its capabilities. Whether you’re fashioning a football statistics hub, a fantasy football game, or any other football-related application, integrating our Football API into your application helps you with a wealth of football data.

Make sure to check out our other blogs on web development and API utilisation. Happy coding!

FAQ

How can I integrate Sportmonks Football API with PHP?
To integrate Sportmonks Football API with PHP, you'll need to sign up for an account on MySportmonks platform to obtain your API token. Once you have your token, you can use PHP's cURL or Guzzle HTTP client to make HTTP requests to the API endpoints. The How-to guide provides a comprehensive guide on how to authenticate your requests, make various types of API calls, and handle the responses in PHP.
What data can I access through Sportmonks Football API?
The Football API offers a wide range of football-related data, including match fixtures, live scores, player statistics, team information, standings, and more. You can retrieve data for current and upcoming matches, as well as historical data for past matches, tournaments, and leagues. Please visit our coverage page for an overview of all leagues and features.
Do I need any special knowledge or skills to integrate the API with PHP?
While basic knowledge of PHP programming is essential for integrating the API with PHP, the how-to guide provides detailed instructions and code examples to guide you through the integration process. Familiarity with handling JSON data and making HTTP requests using PHP's cURL or Guzzle library would be beneficial but not mandatory.
Can I customise the data retrieved from Sportmonks Football API?
Yes, you can customise the data retrieved from the Football API to suit your specific requirements. The API allows you to filter data based on various parameters, such as date, team, player, league, and more. Additionally, you can specify which fields you want to include or exclude in the API responses to minimize bandwidth usage and optimize performance. Check our documentation for more information.
How can I create an API-token?
Once you’ve created your account, you can create your API token via the settings page on My Sportmonks. For security reasons, the API token will only be shown to you once when you create it. Please make sure to write down your API token somewhere safe.
Is there a limit to the number of API requests I can make?
We offers different subscription plans with varying levels of access and usage limits. While the Free plan has certain restrictions on the number of API requests allowed per day, higher-tier plans offer increased usage (3,000 API calls per entity per hour) allowances and additional features. If you require more API requests than your current plan allows, you can consider upgrading to a higher-tier plan or contacting support for customised solutions tailored to your needs.

Written by Wesley Van Rooij

Wesley van Rooij is a marketing and football expert with over 5 years of industry experience. His comprehensive knowledge of the Sportmonks Football API and a focused approach to APIs in the Sports Data industry allow him to offer insights and support to enthusiasts and businesses. His outstanding marketing and communication skills and technical writing expertise enable him to empathise with developers. He understands their needs and challenges to facilitate the development of cutting-edge football applications that stand out in the market.

Start developing

Unlock the full potential of your football application with Sportmonks’ Football API. Subscribe now and embark on a 14-day free trial to experience the richness of our data firsthand. Whether you’re a seasoned developer or just starting out, our API provides everything you need to take your project to the next level. Don’t miss out—sign up now and kickstart your journey to success!

Start developing