Live now!

Progress of current post

A DEVELOPER’S GUIDE: Football API with JAVA

The Sportmonks API is praised for being one of the most developer-friendly football APIs on the market. The reason is not the immense data set or the API’s speed. No, it is about the option to create requests exactly the way a developer wants to get the response exactly as he/she likes. There are many ways for developers to customise the Football API responses, including using includes, filters, selecting fields, ordering and sorting.

Let’s find out how this will look in Java.

Time to read 9 min
Published 19 June 2024
Last updated 7 March 2025
Wesley Van Rooij
A DEVELOPER’S GUIDE: Football API with JAVA
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.

Advantages of using Java and why is it used?

Java has significant advantages over other languages and environments. It is suitable for almost any programming task. Just like our Football API, it focuses on being developer-friendly. How do you ask?

Java is designed to be easy to learn and use. It is easier to write, compile and debug compared to other programming languages. Java allows you to create modular programmes and code you can keep for future usage. Last but not least, Java is platform independent. This might actually be one of the biggest advantages Java has. You will be able to move easily from one computer system to another. This is obviously really important for the world we are currently living in, with all its World Wide Web software.

Copa America how-to guide

Why is Sportmonks’ Football API praised for being developer-friendly?

At Sportmonks, we believe that quality football data should be available to everyone.

Available to everyone.” What does that mean? It means affordable pricing, an API that is available everywhere, and easy-to-use software. We are not going into much detail about pricing or availability, as this blog is here to help you start using it with Java. So, what makes it easy to use? Well, as already mentioned, the API can be used with many different platforms and programming languages, such as Python, PHP, and Java. Besides those, there are many others.

That is cool, but that isn’t all that makes the Football API developer-friendly. You cannot only choose the programming language and how you integrate the API into your web application, but you can also choose how you want your response to look. By using includes, filters, selecting fields, ordering and sorting, there are many ways to customise the Football API responses for developers. We will briefly describe the options and include the documentation pages for each option to give a broader explanation.

Includes

Includes are the cornerstone of our API. These includes allow you to enrich and customise any API response. All the endpoints have their own list of includes, which you can use to get a specific extra array of data.

How to use includes: you simply add &include=[YOUR_INCLUDE(S)]

Example: &include=scores

How to use multiple includes: &include=participants;events

Nested includes

The nested include allows you to further enrich your data by requesting more information from a standard include. Might sound difficult, but we assure you, it’s anything but hard.

We have seen how to use multiple includes, but how do you use nested includes? Well, they have to be related. Because the include event is related to a player. You can add .player to the include, which will result in the nested include: events.player

How to use nested includes: &include=participants;events.player

Filters

Each endpoint has two types of filters, static and dynamic filters. You can combine any dynamic filter with any static filter or use a multitude. Static filters are always the same and filter in one specific way without any custom options.

The dynamic filters are based on entities and includes. Each dynamic filter uses an entity to filter on and one entity to apply the filter to. Below is an example with an explanation of how filters are set up:

  1. First you have a base entity to define.
  2. Next, you have to define what you wish to see in your response. So, you define the expected types.
  3. Finally, you add the IDs you expect to see in the response.

Ordering and Sorting

For paginated endpoints, the API supports ordering on a specific field. The order query parameter is used to specify the order in which paginated results should be returned. By default, results are returned in ascending order. However, you can use the order parameter to specify that results should be returned in descending order instead.

How to use ordering: &order=asc or &order=desc

You can use custom sorts on endpoints; this enables the sorting of base entities returned in the endpoint responses. This feature is designed to enhance flexibility and customisation for users interacting with the API.

How to use sorting: &sortBy=starting_at

Can you use them both? Yes of course: &sortBy=starting_at&order=desc

Selecting fields

The biggest advantage of the option to select the specific fields you like is that it reduces the speed of the responses. Besides that, you don’t have to worry about finding the specific data like a needle in a haystack, as the response size can be drastically reduced.

How to use selecting fields: &select={specific fields on the base entity}

Example: &select=name

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).

Pick your plan icon

2. API Token: Sign up for the Football API and obtain your API token in your personal development environment. Store your token safely.

Dart icon

3. Start coding: Create a Java class that makes a request to the Sportmonks API and prints the results.

Surpass the competition icon

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<>();
        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.

FAQ

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.
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.
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.
What is an API-token?
Sportmonks makes use of API-tokens for authorization of our API. You are required to add the parameter 'api_token' to your API requests. The parameter's value is the actual token you received when you created it in My Sportmonks. Without this key, you cannot use our APIs.

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.