Step 1. Create a new project
Create a new Java project in your IDE and add the OkHttp and org.json dependencies to your project. If you’re using Maven, add the following to your pom.xml:
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.1</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20240303</version>
</dependency>
It should look something like this:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>sportmonks-api-example</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.1</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20240303</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<mainClass>com.example.SportmonksApiClient</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>
Step 2. Write the Java Code
Create a new Java class (e.g., SportmonksApiClient) and write the following code:
package com.example;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
import org.json.JSONArray;
import org.json.JSONObject;
public class SportmonksApiClient {
private static final String API_URL = "https://api.sportmonks.com/v3/football/fixtures";
private static final String API_KEY = "YOUR_API_KEY"; // Replace with your actual API key
public static void main(String[] args) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(API_URL + "?api_token=" + API_KEY)
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
}
// Parse the response
String responseBody = response.body().string();
JSONObject jsonResponse = new JSONObject(responseBody);
JSONArray fixtures = jsonResponse.getJSONArray("data");
// Print formatted results
for (int i = 0; i < fixtures.length(); i++) {
JSONObject fixture = fixtures.getJSONObject(i);
String name = fixture.getString("name");
String date = fixture.getString("starting_at");
System.out.printf("Fixture: %s on %s%n", name, date);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Step 3. Run Your Program
Replace “YOUR_API_KEY” with your actual Sportmonks API key, compile, and run your Java program. The program will request fixtures from the Sportmonks API and print the results in a formatted manner.
Explanation
OkHttpClient: Used to make HTTP requests.
Request: Defines the request we want to make, including the URL and API token.
Response: Represents the response from the API.
JSONObject: Used to parse the JSON response from the API.
JSONArray: Represents the list of fixtures in the response.
This code sends a GET request to the Sportmonks API, parses the JSON response, and prints the fixtures in a human-readable format.
Step 4: Using the customisation options
As explained above there are multiple ways to customise the requests and responses.
Step 4.1 Let’s use an include
First we would like to use includes. Let’s see how that looks. If you want to use includes with the Sportmonks API to fetch additional related data in the same request, you can do this by adding the appropriate query parameters to your request URL. The includes parameter allows you to specify additional related data to include in the response, such as team details, league information, etc.
Below is the updated Java program that includes team details in the fixtures request and prints the formatted results, including team names.
package com.example;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONObject;
public class SportmonksApiClient {
private static final String API_URL = "https://api.sportmonks.com/v3/football/fixtures";
private static final String API_KEY = "YOUR_API_KEY"; // Replace with your actual API key
public static void main(String[] args) {
OkHttpClient client = new OkHttpClient();
// URL with include=participants parameter to get home and away team details
String urlWithIncludes = API_URL + "?api_token=" + API_KEY +
"&include=participants";
Request request = new Request.Builder()
.url(urlWithIncludes)
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
}
// Parse the response
String responseBody = response.body().string();
JSONObject jsonResponse = new JSONObject(responseBody);
JSONArray fixtures = jsonResponse.getJSONArray("data");
// Print formatted results
for (int i = 0; i < fixtures.length(); i++) {
JSONObject fixture = fixtures.getJSONObject(i);
// Get team details from included data
HashMap<String, JSONObject> keyedParticipants = getKeyedParticipants(
fixture.getJSONArray("participants"));
JSONObject homeTeam = keyedParticipants.get("home");
JSONObject awayTeam = keyedParticipants.get("away");
String homeTeamName = homeTeam.getString("name");
String awayTeamName = awayTeam.getString("name");
String date = fixture.getString("starting_at");
System.out.printf("On %s, %s plays against %s%n", date, homeTeamName, awayTeamName);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static HashMap<String, JSONObject> getKeyedParticipants(JSONArray participants) {
HashMap<String, JSONObject> keyedParticipants = new HashMap<String, JSONObject>();
for (int p = 0; p < participants.length(); p++) {
JSONObject participant = participants.getJSONObject(p);
keyedParticipants.put(participant.getJSONObject("meta").getString("location"), participant);
}
return keyedParticipants;
}
}
Explanation
– URL with Includes: The urlWithIncludes variable includes the include=participants query parameter to fetch the details of the home and away teams.
– Parsing Included Data: The response will include additional data about the teams. This data is accessed using a method that adds them to a HashMap, keyed by home and away, for convenience.
Step 4.2 Running the Program
Replace “YOUR_API_KEY” with your actual Sportmonks API key, compile, and run your Java program. This will request fixtures along with the team details from the Sportmonks API and print the fixtures including the team names.
With this setup, you can include any related data supported by the API by adjusting the include parameter in the request URL accordingly. For example, to include league information, you could use &include=league. The includes that are supported on an endpoint can be found in the API documentation.
Step 4.3 Now let’s use sorting
To sort the request based on dates using the sortBy and order parameters, you can add these parameters to your API request URL. Below is the updated Java program that sorts the fixtures by the starting_at field in descending order and prints the formatted results.
Updated Java Code with Sorting
First, ensure you have the OkHttp dependency added to your project as mentioned earlier. Then, update the Java class:
package com.example;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONObject;
public class SportmonksApiClient {
private static final String API_URL = "https://api.sportmonks.com/v3/football/fixtures";
private static final String API_KEY = "YOUR_API_KEY"; // Replace with your actual API key
public static void main(String[] args) {
OkHttpClient client = new OkHttpClient();
// URL with include=participants parameter to get home and away team details
String urlWithIncludesAndSorting = API_URL + "?api_token=" + API_KEY +
"&include=participants" +
"&sortBy=starting_at&order=desc";
Request request = new Request.Builder()
.url(urlWithIncludesAndSorting)
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
}
// Parse the response
String responseBody = response.body().string();
JSONObject jsonResponse = new JSONObject(responseBody);
JSONArray fixtures = jsonResponse.getJSONArray("data");
// Print formatted results
for (int i = 0; i < fixtures.length(); i++) {
JSONObject fixture = fixtures.getJSONObject(i);
// Get team details from included data
HashMap<String, JSONObject> keyedParticipants = getKeyedParticipants(
fixture.getJSONArray("participants"));
JSONObject homeTeam = keyedParticipants.get("home");
JSONObject awayTeam = keyedParticipants.get("away");
String homeTeamName = homeTeam.getString("name");
String awayTeamName = awayTeam.getString("name");
String date = fixture.getString("starting_at");
System.out.printf("On %s, %s plays against %s%n", date, homeTeamName, awayTeamName);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static HashMap<String, JSONObject> getKeyedParticipants(JSONArray participants) {
HashMap<String, JSONObject> keyedParticipants = new HashMap<String, JSONObject>();
for (int p = 0; p < participants.length(); p++) {
JSONObject participant = participants.getJSONObject(p);
keyedParticipants.put(participant.getJSONObject("meta").getString("location"), participant);
}
return keyedParticipants;
}
}
Explanation
– URL with Includes and Sorting: The urlWithIncludesAndSorting variable includes the include=participants query parameter to fetch the details of the home and away teams. It also includes sortBy=starting_at&order=asc to sort the fixtures by the starting_at field in ascending order.
– Sorting Parameters: sortBy=starting_at specifies that the fixtures should be sorted by the starting_at field, and order=desc specifies that the sorting should be in descending order.
4.4 Running the Program
Replace “YOUR_API_KEY” with your actual Sportmonks API key, compile, and run your Java program. This will request fixtures sorted by the date (starting_at) in ascending order, along with the team details, and print the fixtures including the team names and dates.