
Contents
What is Java?
According to Amazon, “Java is a multi-platform, object-oriented, and network-centric language that can be used as a platform in itself. It is a fast, secure, reliable programming language for coding everything from mobile apps and enterprise software to big data applications and server-side technologies.”
Do you need Java to use the Sportmonks’ API?
Let’s be clear: You decide which development platform or language you want to use.
This blog is here just to show how to use the Football API with JAVA. However, we have written a blog about how to use the Football API with Python, PHP, JSON, Excel, and Postman as well. You don’t have to use any of these. The Football API can be used in any way you like. You can find a complete list of leagues, features and statistics included in our Football API on our coverage page.
Now up to you:
1. Java project: Make sure you have a Java development environment set up (JDK and an IDE like IntelliJ IDEA or Eclipse).
2. API Token: Sign up for the Football API and obtain your API token in your personal development environment. Store your token safely.
3. Start coding: Create a Java class that makes a request to the Sportmonks API and prints the results.
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<>(); 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, // and sorting by starting_at in descending order 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<>(); 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.