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:
<?php
$api_key = 'YOUR_API_TOKEN'; // Copy/paste your unique API token here
$endpoint = 'https://api.sportmonks.com/v3/football/leagues'; // The API endpoint
// 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;
}
<?php
use Illuminate\Support\Facades\Http;
$api_key = 'YOUR_API_TOKEN'; // Copy/paste your unique API token here
$endpoint = 'https://api.sportmonks.com/v3/football/leagues'; // The API endpoint
try {
// Make HTTP GET request using Laravel HTTP client
$response = Http::withHeaders([
'Content-Type' => '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!
<?php
$api_key = 'YOUR_API_TOKEN'; // Copy/paste your unique API token here
$endpoint = 'https://api.sportmonks.com/v3/football/leagues?include=currentSeason'; // The API endpoint
// 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;
}
<?php
use Illuminate\Support\Facades\Http;
$api_key = 'YOUR_API_TOKEN'; // Copy/paste your unique API token here
$endpoint = 'https://api.sportmonks.com/v3/football/leagues?include=currentSeason'; // The API endpoint
try {
// Make HTTP GET request using Laravel HTTP client
$response = Http::withHeaders([
'Content-Type' => '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:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Http;
class SportmonksApiController extends Controller
{
protected string $baseUrl = 'https://api.sportmonks.com/v3';
protected string $apiToken = '';
// 1.2 Authentication
protected function requestEndpoint(string $endpoint, array $query = [])
{
// We'll append the endpoint to the base URL
$url = $this->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)