Live now!

Progress of current post

A Developer’s Guide: Leveraging Sportmonks Football API in Kotlin

According to its documentation page, “Kotlin is an open-source statically typed programming language that targets the JVM, Android, JavaScript, Wasm, and Native.” Kotlin was developed by JetBrains and the project started in 2010; its first official 1.0 release was in February 2016.

Time to read 15 min
Published 23 October 2024
Last updated 14 March 2025
Wesley Van Rooij
A Developer’s Guide: Leveraging Sportmonks Football API in Kotlin
Contents

Just like we did in our previous exercise, harnessing the power of Sportmonks API using GO, in today’s exercise, we will guide you on how to deploy our flexible and robust Football API, which has a coverage of 2,300 leagues and more than 60 endpoints, using Kotlin.

Influenced by C#, Eiffel, Java and Python, Kotlin’s versatility and ability to run on Android, Windows, Mac and Linux, makes it a perfect fit for building mobile and web applications.Designed by JetBrains, Kotlin first appeared in July 2011, after JetBrains’ lead Dmitry Jemerov said that most languages did not have the features they were looking for, with the exception of Scala. However, the objective of the new language was to compile as quickly as Java.

While it ranks 15th as the most popular programming language according to a 2024 survey by Stack Overflow, seven places behind C#, as far back as May 2019, Google had announced Kotlin as their preferred language on Android.

Like we did in our blogs, using Python, PHP, Java, and GO, in this blog we will focus on harnessing the power of Sportmonks API with Kotlin.

What can you build with Kotlin?

Kotlin can be used for any kind of development, be it client-side, web, or multiplatform library. Developers use Kotlin for mobile and server-side applications. Kotlin is fully compatible with Java, allowing experienced developers to easily migrate their code to Kotlin.

While you might be busy scratching your head over practical examples, the next time you run the mobile app Uber on your phone, you can be assured you just interacted with Kotlin. Not only that, Uber is also actively contributing to the Kotlin ecosystem.

What’s more, while you could be multitasking while watching your favourite series on Netflix, you have also interacted with Kotlin, which forms part of Netflix’s tech stack.

Pinterest, the popular photo-sharing app, also adopted Kotlin for its Android app development. So while you lick your lips over building what will be the next big thing, you can be rest assured you are on the right page.

Chapter 1. Setting up for Kotlin.

In each chapter, we will feature practical examples and code snippets to illustrate key concepts and help you understand how to use Sportmonks’ API with Kotlin. Each chapter will increase your confidence as we go along in harnessing Sportmonks’ Football API to its full potential.

1.1 Setting up IntelliJ IDEA to run Kotlin.

JetBrains provides the official Kotlin support for IntelliJ IDEA, which is a cross-platform IDE that provides consistent experience on the Windows, macOS, and Linux operating systems.

You may download IntelliJ IDEA Community Edition, which is completely free to use. You may also choose the alternative, JetBrains Fleet, or Android Studio, for this exercise based on your preference or operating system.

Open IntelliJ IDEA and create a new project. Select Kotlin as project type and make sure the JDK is selected. You may need to download one if you have not already, you can do this in the same selector.

JDK_Kotlin

Before you go on to the next section, you will need to create an API Token.

Obtaining an API Token

To use the API, sign up for an account. Your account automatically comes with the Danish Super Liga and Scottish Premier League plans. These are free forever.

However, for today’s exercise, you can take advantage of the 14-day free trial on any of the other plans.

Head over to the Create an API Token on your dashboard. Once you create your API token, which is required for authentication and accessing the data endpoints, you must keep it private.

Creat API Token_Sportmonks

If your API token becomes compromised at any time, you can easily delete it and create a new one. With your brand new API token, you’re ready to start making requests to Sportmonks’ Football API.

1.2 Retrieve League details using Kotlin.

Open the Main.kt file in IntelliJ IDEA and add the following code to retrieve league details from Sportmonks’ Football API.

import java.net.HttpURLConnection  

import java.net.URL  

fun main() {  

    val url = "https://api.sportmonks.com/v3/football/leagues?api_token=API_token" // Replace with your API token  

    val urlObj = URL(url)  

    val connection = urlObj.openConnection() as HttpURLConnection  

    try {  

        connection.requestMethod = "GET"  

        val responseCode = connection.responseCode  

        if (responseCode == HttpURLConnection.HTTP_OK) {  

            val response = connection.inputStream.bufferedReader().use { it.readText() }  

            println(response)  

        } else {  

            println("GET request failed with response code: $responseCode")  

        }  

    } catch (e: Exception) {  

        println("An error occurred: ${e.message}")  

    } finally {  

        connection.disconnect()  

    }  

} 

Run the Kotlin code. If everything is set up correctly, this will execute the API request and print the response. If you encounter any errors, verify that the JDK and Kotlin are installed properly and that the environment variables (JAVA_HOME and PATH) are set correctly.

1.3 Formatting the JSON Response

Going back to the piece of code in section 1.2, we will modify the code to do some formatting and have the JSON response printed in a much more readable way.

Before doing so, we will have to add an external library called Gson. Depending on your version of the IDE, you will have to navigate to the add library view, just as seen in the screen shot below.
Import Library_Gson

Once the Gson library has been imported into the project, then you can include the import statements as seen below.
Gson_added_Kotlin

You can then copy and paste this piece of code.

import java.net.HttpURLConnection 
import java.net.URL 
import com.google.gson.GsonBuilder 
import com.google.gson.JsonParser 
 
fun main() { 
    val url = "https://api.sportmonks.com/v3/football/leagues?api_token=API_token" // Replace with your API token 
 
    val urlObj = URL(url) 
    val connection = urlObj.openConnection() as HttpURLConnection 
 
    try { 
        connection.requestMethod = "GET" 
 
        val responseCode = connection.responseCode 
        if (responseCode == HttpURLConnection.HTTP_OK) { 
            // Read the response 
            val response = connection.inputStream.bufferedReader().use { it.readText() } 
 
            // Parse and pretty-print the JSON response 
            val jsonElement = JsonParser.parseString(response) 
            val gson = GsonBuilder().setPrettyPrinting().create() // Enable pretty printing 
            val prettyJson = gson.toJson(jsonElement) 
 
            println(prettyJson) // Print formatted JSON 
        } else { 
            println("GET request failed with response code: $responseCode") 
        } 
    } catch (e: Exception) { 
        println("An error occurred: ${e.message}") 
    } finally { 
        connection.disconnect() 
    } 
}
{
  "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-10-23 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-10-24 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-10-21 19:00:00",
      "category": 1,
      "has_jerseys": false
    },
    {
      "id": 9,
      "sport_id": 1,
      "country_id": 462,
      "name": "Championship",
      "active": true,
      "short_code": "UK Champ",
      "image_path": "https://cdn.sportmonks.com/images/soccer/leagues/9/9.png",
      "type": "league",
      "sub_type": "domestic",
      "last_played_at": "2024-10-23 19:00:00",
      "category": 2,
      "has_jerseys": false
    },
    {
      "id": 12,
      "sport_id": 1,
      "country_id": 462,
      "name": "League One",
      "active": true,
      "short_code": "UK L1",
      "image_path": "https://cdn.sportmonks.com/images/soccer/leagues/12/12.png",
      "type": "league",
      "sub_type": "domestic",
      "last_played_at": "2024-10-22 18:45:00",
      "category": 2,
      "has_jerseys": false
    },
    {
      "id": 14,
      "sport_id": 1,
      "country_id": 462,
      "name": "League Two",
      "active": true,
      "short_code": "UK L2",
      "image_path": "https://cdn.sportmonks.com/images/soccer/leagues/14/14.png",
      "type": "league",
      "sub_type": "domestic",
      "last_played_at": "2024-10-22 18:45:00",
      "category": 2,
      "has_jerseys": false
    },
    {
      "id": 17,
      "sport_id": 1,
      "country_id": 462,
      "name": "National League",
      "active": true,
      "short_code": "UK NL",
      "image_path": "https://cdn.sportmonks.com/images/soccer/leagues/17/17.png",
      "type": "league",
      "sub_type": "domestic",
      "last_played_at": "2024-10-23 18:45:00",
      "category": 3,
      "has_jerseys": false
    },
    {
      "id": 20,
      "sport_id": 1,
      "country_id": 462,
      "name": "Vanarama National League North",
      "active": true,
      "short_code": "UK NLN",
      "image_path": "https://cdn.sportmonks.com/images/soccer/leagues/20/20.png",
      "type": "league",
      "sub_type": "domestic",
      "last_played_at": "2024-10-23 18:45:00",
      "category": 4,
      "has_jerseys": false
    },
    {
      "id": 23,
      "sport_id": 1,
      "country_id": 462,
      "name": "Community Shield",
      "active": true,
      "short_code": null,
      "image_path": "https://cdn.sportmonks.com/images/soccer/leagues/23/23.png",
      "type": "league",
      "sub_type": "domestic_cup",
      "last_played_at": "2024-08-10 14:00:00",
      "category": 2,
      "has_jerseys": false
    },
    {
      "id": 24,
      "sport_id": 1,
      "country_id": 462,
      "name": "FA Cup",
      "active": true,
      "short_code": "UK FA Cup",
      "image_path": "https://cdn.sportmonks.com/images/soccer/leagues/24/24.png",
      "type": "league",
      "sub_type": "domestic_cup",
      "last_played_at": "2024-10-15 18:45:00",
      "category": 2,
      "has_jerseys": false
    },
    {
      "id": 27,
      "sport_id": 1,
      "country_id": 462,
      "name": "Carabao Cup",
      "active": true,
      "short_code": null,
      "image_path": "https://cdn.sportmonks.com/images/soccer/leagues/27/27.png",
      "type": "league",
      "sub_type": "domestic_cup",
      "last_played_at": "2024-10-01 18:45:00",
      "category": 2,
      "has_jerseys": false
    },
    {
      "id": 30,
      "sport_id": 1,
      "country_id": 462,
      "name": "Fa Trophy",
      "active": true,
      "short_code": null,
      "image_path": "https://cdn.sportmonks.com/images/soccer/leagues/30/30.png",
      "type": "league",
      "sub_type": "domestic_cup",
      "last_played_at": "2024-10-05 14:00:00",
      "category": 2,
      "has_jerseys": false
    },
    {
      "id": 32,
      "sport_id": 1,
      "country_id": 462,
      "name": "Premier League Cup",
      "active": true,
      "short_code": "ENG DL2",
      "image_path": "https://cdn.sportmonks.com/images/soccer/leagues/0/32.png",
      "type": "league",
      "sub_type": "domestic_cup",
      "last_played_at": "2024-10-22 18:00:00",
      "category": 3,
      "has_jerseys": false
    },
    {
      "id": 35,
      "sport_id": 1,
      "country_id": 462,
      "name": "Premier League U21",
      "active": true,
      "short_code": null,
      "image_path": "https://cdn.sportmonks.com/images/soccer/leagues/3/35.png",
      "type": "league",
      "sub_type": "domestic",
      "last_played_at": "2016-05-12 10:30:00",
      "category": 3,
      "has_jerseys": false
    },
    {
      "id": 38,
      "sport_id": 1,
      "country_id": 462,
      "name": "Premier League International Cup",
      "active": true,
      "short_code": null,
      "image_path": "https://cdn.sportmonks.com/images/soccer/leagues/6/38.png",
      "type": "league",
      "sub_type": "domestic_cup",
      "last_played_at": "2024-10-22 18:30:00",
      "category": 3,
      "has_jerseys": false
    },
    {
      "id": 39,
      "sport_id": 1,
      "country_id": 462,
      "name": "EFL Trophy",
      "active": true,
      "short_code": "UK EFLT",
      "image_path": "https://cdn.sportmonks.com/images/soccer/leagues/7/39.png",
      "type": "league",
      "sub_type": "domestic_cup",
      "last_played_at": "2024-10-08 18:45:00",
      "category": 2,
      "has_jerseys": false
    },
    {
      "id": 42,
      "sport_id": 1,
      "country_id": 462,
      "name": "Premier League U18",
      "active": true,
      "short_code": null,
      "image_path": "https://cdn.sportmonks.com/images/soccer/leagues/10/42.png",
      "type": "league",
      "sub_type": "domestic",
      "last_played_at": "2024-10-19 11:00:00",
      "category": 3,
      "has_jerseys": false
    },
    {
      "id": 44,
      "sport_id": 1,
      "country_id": 462,
      "name": "Wsl 2 Women",
      "active": true,
      "short_code": null,
      "image_path": "https://cdn.sportmonks.com/images/soccer/leagues/12/44.png",
      "type": "league",
      "sub_type": "domestic",
      "last_played_at": "2024-10-20 13:00:00",
      "category": 3,
      "has_jerseys": false
    },
    {
      "id": 45,
      "sport_id": 1,
      "country_id": 462,
      "name": "Women's Super League",
      "active": true,
      "short_code": null,
      "image_path": "https://cdn.sportmonks.com/images/soccer/leagues/13/45.png",
      "type": "league",
      "sub_type": "domestic",
      "last_played_at": "2024-10-20 17:45:00",
      "category": 3,
      "has_jerseys": false
    },
    {
      "id": 48,
      "sport_id": 1,
      "country_id": 462,
      "name": "Professional Development League",
      "active": true,
      "short_code": "UK U23 DL",
      "image_path": "https://cdn.sportmonks.com/images/soccer/leagues/16/48.png",
      "type": "league",
      "sub_type": "domestic",
      "last_played_at": "2024-10-24 18:00:00",
      "category": 4,
      "has_jerseys": false
    },
    {
      "id": 51,
      "sport_id": 1,
      "country_id": 462,
      "name": "Non League Premier: Isthmian",
      "active": true,
      "short_code": null,
      "image_path": "https://cdn.sportmonks.com/images/soccer/leagues/19/51.png",
      "type": "league",
      "sub_type": "domestic",
      "last_played_at": "2024-10-22 18:45:00",
      "category": 4,
      "has_jerseys": false
    },
    {
      "id": 53,
      "sport_id": 1,
      "country_id": 462,
      "name": "Non League Div One: Isthmian North",
      "active": true,
      "short_code": null,
      "image_path": "https://cdn.sportmonks.com/images/soccer/leagues/21/53.png",
      "type": "league",
      "sub_type": "domestic",
      "last_played_at": "2024-10-23 18:45:00",
      "category": 4,
      "has_jerseys": false
    },
    {
      "id": 54,
      "sport_id": 1,
      "country_id": 462,
      "name": "Non League Div One: Southern Central",
      "active": true,
      "short_code": null,
      "image_path": "https://cdn.sportmonks.com/images/soccer/leagues/22/54.png",
      "type": "league",
      "sub_type": "domestic",
      "last_played_at": "2024-10-22 18:45:00",
      "category": 4,
      "has_jerseys": false
    },
    {
      "id": 57,
      "sport_id": 1,
      "country_id": 462,
      "name": "Non League Div One: Northern North",
      "active": false,
      "short_code": null,
      "image_path": "https://cdn.sportmonks.com/images/soccer/leagues/25/57.png",
      "type": "league",
      "sub_type": "domestic",
      "last_played_at": "2020-12-26 21:00:12",
      "category": 4,
      "has_jerseys": false
    },
    {
      "id": 60,
      "sport_id": 1,
      "country_id": 462,
      "name": "Non League Div One: Isthmian South",
      "active": false,
      "short_code": null,
      "image_path": "https://cdn.sportmonks.com/images/soccer/leagues/28/60.png",
      "type": "league",
      "sub_type": "domestic",
      "last_played_at": "2020-11-04 09:00:27",
      "category": 4,
      "has_jerseys": false
    }
  ],
  "pagination": {
    "count": 25,
    "per_page": 25,
    "current_page": 1,
    "next_page": "https://api.sportmonks.com/v3/football/leagues?page=2",
    "has_more": true
  },
  "subscription": [
    {
      "meta": {
        "trial_ends_at": "2024-10-16 14:50:45",
        "ends_at": null,
        "current_timestamp": 1729811556
      },
      "plans": [
        {
          "plan": "Enterprise plan (loyal)",
          "sport": "Football",
          "category": "Advanced"
        },
        {
          "plan": "Enterprise Plan",
          "sport": "Cricket",
          "category": "Standard"
        },
        {
          "plan": "Formula One",
          "sport": "Formula One",
          "category": "Standard"
        }
      ],
      "add_ons": [
        {
          "add_on": "All-in News API",
          "sport": "Football",
          "category": "News"
        },
        {
          "add_on": "pressure index add-on",
          "sport": "Football",
          "category": "Default"
        },
        {
          "add_on": "Enterprise Plan Predictions",
          "sport": "Football",
          "category": "Predictions"
        },
        {
          "add_on": "xG Advanced",
          "sport": "Football",
          "category": "Expected"
        }
      ],
      "widgets": [
        {
          "widget": "Sportmonks Widgets",
          "sport": "Football"
        }
      ]
    }
  ],
  "rate_limit": {
    "resets_in_seconds": 3079,
    "remaining": 2998,
    "requested_entity": "League"
  },
  "timezone": "UTC"
}

Here’s the explanation. We used GsonBuilder().setPrettyPrinting().create() to create a Gson instance that formats the JSON response from the url with proper indentation.

The GsonBuilder() is used to configure Gson to pretty-print the output, while the toJson() method converts the parsed jsonElement into a well-formatted, human-readable string.

Chapter 2. Getting a Specific League.

We will take a step further by retrieving a specific league. By now you must have guessed the league ID for the Premier League is 8, based on the results of the previous exercise. Once again, the result may appear slightly different from yours based on the plan you have subscribed to.

We will use this url with the previous piece of code. https://api.sportmonks.com/v3/football/leagues/8?api_token=API_Token.

import java.net.HttpURLConnection 
import java.net.URL 
import com.google.gson.GsonBuilder 
import com.google.gson.JsonParser 
 
fun main() { 
    val url = "https://api.sportmonks.com/v3/football/leagues/8?api_token=API_token" // Replace with your API token 
 
    val urlObj = URL(url) 
    val connection = urlObj.openConnection() as HttpURLConnection 
 
    try { 
        connection.requestMethod = "GET" 
 
        val responseCode = connection.responseCode 
        if (responseCode == HttpURLConnection.HTTP_OK) { 
            // Read the response 
            val response = connection.inputStream.bufferedReader().use { it.readText() } 
 
            // Parse and pretty-print the JSON response 
            val jsonElement = JsonParser.parseString(response) 
            val gson = GsonBuilder().setPrettyPrinting().create() // Enable pretty printing 
            val prettyJson = gson.toJson(jsonElement) 
 
            println(prettyJson) // Print formatted JSON 
        } else { 
            println("GET request failed with response code: $responseCode") 
        } 
    } catch (e: Exception) { 
        println("An error occurred: ${e.message}") 
    } finally { 
        connection.disconnect() 
    } 
} 
{
  "data": {
    "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-10-21 19:00:00",
    "category": 1,
    "has_jerseys": false
  },
}

2.1 Retrieving League Fixtures between dates.

Consider a scenario where you have been tasked with building an app to display upcoming fixtures between a certain period. In this exercise, we will retrieve fixtures scheduled between two different dates in a specific league using a filter. Once again, we will make use of the Premier League. Here’s our url.

https://api.sportmonks.com/v3/football/fixtures/between/2024-11-20/2024-11-30?api_token=API_Token&filters=fixtureLeagues:8

Examining the url, you will find that we are retrieving match details from the 20th to the 30th of November 2024. Placing the url in your browser will retrieve the complete JSON response. However, we will modify our code to display just a few details such as name, date and time.

You will find this piece of code can be easily modified to add or remove any detail.

import java.net.HttpURLConnection
import java.net.URL
import com.google.gson.Gson
import com.google.gson.annotations.SerializedName

// Wrapper class to represent the response structure
data class ApiResponse(
       @SerializedName("data") val fixtures: List 
)

// Class to represent the league
data class Fixture(
    val name: String,
    @SerializedName("starting_at") val startingAt: String
)

fun main() {
    val url = "https://api.sportmonks.com/v3/football/fixtures/between/2024-11-20/2024-11-30?api_token=API_TOKEN&filters=fixtureLeagues:8" // Replace with your API Token

    val urlObj = URL(url)
    val connection = urlObj.openConnection() as HttpURLConnection

    try {
        connection.requestMethod = "GET"

        val responseCode = connection.responseCode
        if (responseCode == HttpURLConnection.HTTP_OK) {
            // Read the response
            val response = connection.inputStream.bufferedReader().use { it.readText() }

            // Deserialize the JSON response into the ApiResponse object
            val apiResponse: ApiResponse = Gson().fromJson(response, ApiResponse::class.java)

            // Print specific fields from each league in the data field
            apiResponse.fixtures.forEach { fixture ->
                println("Name: ${fixture.name}")
                println("Time: ${fixture.startingAt}")
                println("----------")
            }
        } else {
            println("GET request failed with response code: $responseCode")
        }
    } catch (e: Exception) {
        println("An error occurred: ${e.message}")
    } finally {
        connection.disconnect()
    }
}
Name: Leicester City vs Chelsea
Time: 2024-11-23 12:30:00
----------
Name: AFC Bournemouth vs Brighton & Hove Albion
Time: 2024-11-23 15:00:00
----------
Name: Arsenal vs Nottingham Forest
Time: 2024-11-23 15:00:00
----------
Name: Aston Villa vs Crystal Palace
Time: 2024-11-23 15:00:00
----------
Name: Everton vs Brentford
Time: 2024-11-23 15:00:00
----------
Name: Fulham vs Wolverhampton Wanderers
Time: 2024-11-23 15:00:00
----------
Name: Manchester City vs Tottenham Hotspur
Time: 2024-11-23 17:30:00
----------
Name: Southampton vs Liverpool
Time: 2024-11-24 14:00:00
----------
Name: Ipswich Town vs Manchester United
Time: 2024-11-24 16:30:00
----------
Name: Newcastle United vs West Ham United
Time: 2024-11-25 20:00:00
----------
Name: Brighton & Hove Albion vs Southampton
Time: 2024-11-29 20:00:00
----------
Name: Brentford vs Leicester City
Time: 2024-11-30 15:00:00
----------
Name: Crystal Palace vs Newcastle United
Time: 2024-11-30 15:00:00
----------
Name: Nottingham Forest vs Ipswich Town
Time: 2024-11-30 15:00:00
----------
Name: Wolverhampton Wanderers vs AFC Bournemouth
Time: 2024-11-30 15:00:00
----------
Name: West Ham United vs Arsenal
Time: 2024-11-30 17:30:00
----------

Here’s the explanation

Wrapper Class (ApiResponse): The ApiResponse class is a wrapper that contains a list of League objects under the “data” field. This matches the structure of the JSON returned by the API.

SerializedName: The @SerializedName annotation ensures Gson maps the “data” field from the JSON to the leagues property in ApiResponse.

Extracting the List: Once the response is deserialised, you can access the leagues list and print only the relevant fields (name and starting_at).

Chapter 3. Retrieving League Standings.

In our previous blog, where we deployed GO, we found out how to retrieve Odds data. However, in this chapter, we will take another direction by retrieving league standings for the Premier League.

Apart from live scores, which are covered by our Football API, league standings are a popular demand by many, especially for top leagues such as the Premier League, La Liga, and Bundesliga, which forms part of our coverage.

Using the previous piece of code, we will make slight modifications to retrieve league standings for the Premier League, whose ID is 8. Using this url in your browser, you can view the structure of the JSON data.

https://api.sportmonks.com/v3/football/standings/live/leagues/8?api_token=API_Token

import java.net.HttpURLConnection
import java.net.URL
import com.google.gson.Gson
import com.google.gson.annotations.SerializedName
// Wrapper class to represent the response structure
data class ApiResponse(
  @SerializedName("data") val leagueStandings: List 
)

// Class to represent the league
data class LeagueStandings(
    @SerializedName("participant_id") val participantId: Int,
    val position: Int,
    val points: Int
)

fun main() {
    val url = "https://api.sportmonks.com/v3/football/standings/live/leagues/8?api_token=API_Token" // Replace with your API Token

    val urlObj = URL(url)
    val connection = urlObj.openConnection() as HttpURLConnection

    try {
        connection.requestMethod = "GET"

        val responseCode = connection.responseCode
        if (responseCode == HttpURLConnection.HTTP_OK) {
            // Read the response
            val response = connection.inputStream.bufferedReader().use { it.readText() }

            // Deserialize the JSON response into the ApiResponse object
            val apiResponse: ApiResponse = Gson().fromJson(response, ApiResponse::class.java)

            // Print specific fields from the league standings in the data field
            apiResponse.leagueStandings.forEach { team ->
                println("Team ID: ${team.participantId}")
                println("Position: ${team.position}")
                println("Points: ${team.points}")
                println("----------")
            }
        } else {
            println("GET request failed with response code: $responseCode")
        }
    } catch (e: Exception) {
        println("An error occurred: ${e.message}")
    } finally {
        connection.disconnect()
    }
}
Club ID: 8
Position: 1
Points: 21
----------
Club ID: 9
Position: 2
Points: 20
----------
Club ID: 19
Position: 3
Points: 17
----------
Club ID: 15
Position: 4
Points: 17
----------
Club ID: 78
Position: 5
Points: 15
----------
Club ID: 18
Position: 6
Points: 14
----------
Club ID: 6
Position: 7
Points: 13
----------
Club ID: 63
Position: 8
Points: 13
----------
Club ID: 20
Position: 9
Points: 12
----------
Club ID: 11
Position: 10
Points: 11
----------
Club ID: 52
Position: 11
Points: 11
----------
Club ID: 14
Position: 12
Points: 11
----------
Club ID: 236
Position: 13
Points: 10
----------
Club ID: 42
Position: 14
Points: 9
----------
Club ID: 1
Position: 15
Points: 8
----------
Club ID: 13
Position: 16
Points: 8
----------
Club ID: 116
Position: 17
Points: 4
----------
Club ID: 51
Position: 18
Points: 3
----------
Club ID: 65
Position: 19
Points: 1
----------
Club ID: 29
Position: 20
Points: 1
----------

Viewing the ‘Response’ tab you will see the Club ID, current position, and number of points for all the clubs in the Premier League. We will take another step in the next chapter, building on our response to retrieve club names.

Chapter 4. Retrieve league standings with club name.

Now that you can retrieve the league standings from the Premier League, we will take one more step to tie the club ID to the club’s name using another endpoint, since the IDs alone don’t just cut it. Here’s the piece of code.

import java.net.HttpURLConnection
import java.net.URL
import com.google.gson.Gson
import com.google.gson.annotations.SerializedName

// Wrapper class to represent the standings response structure
data class ApiResponse(
@SerializedName("data") val leagueStandings: List 
)

// Class to represent each league standings entry
data class LeagueStandings(
    @SerializedName("participant_id") val participantId: Int,
    val position: Int,
    val points: Int
)

// Wrapper class for the club details response
data class TeamResponse(
    @SerializedName("data") val team: Team
)

// Class to represent a club with a name
data class Team(
    val name: String
)

// Function to fetch club name based on participant_id
fun getTeamName(participantId: Int, apiToken: String): String? {
    val url = "https://api.sportmonks.com/v3/football/teams/$participantId?api_token=$apiToken"
    val urlObj = URL(url)
    val connection = urlObj.openConnection() as HttpURLConnection

    return try {
        connection.requestMethod = "GET"
        val responseCode = connection.responseCode
        if (responseCode == HttpURLConnection.HTTP_OK) {
            val response = connection.inputStream.bufferedReader().use { it.readText() }
            val teamResponse: TeamResponse = Gson().fromJson(response, TeamResponse::class.java)
            teamResponse.team.name // Return the club name
        } else {
            println("GET request for club name failed with response code: $responseCode")
            null
        }
    } catch (e: Exception) {
        println("An error occurred while retrieving club name: ${e.message}")
        null
    } finally {
        connection.disconnect()
    }
}

fun main() {
    val apiToken = "API_Token" // Replace with your API token
    val standingsUrl = "https://api.sportmonks.com/v3/football/standings/live/leagues/8?api_token=$apiToken"

    val urlObj = URL(standingsUrl)
    val connection = urlObj.openConnection() as HttpURLConnection

    try {
        connection.requestMethod = "GET"
        val responseCode = connection.responseCode
        if (responseCode == HttpURLConnection.HTTP_OK) {
            // Read the response
            val response = connection.inputStream.bufferedReader().use { it.readText() }

            // Deserialize the JSON response into the ApiResponse object
            val apiResponse: ApiResponse = Gson().fromJson(response, ApiResponse::class.java)

            // For each club, retrieve additional details (like club name) using the participant_id
            apiResponse.leagueStandings.forEach { team ->
                val teamName = getTeamName(team.participantId, apiToken) ?: "Unknown Team"
                println("Team: $teamName")
                println("Position: ${team.position}")
                println("Points: ${team.points}")
                println("----------")
            }
        } else {
            println("GET request for standings failed with response code: $responseCode")
        }
    } catch (e: Exception) {
        println("An error occurred: ${e.message}")
    } finally {
        connection.disconnect()
    }
}
Club: Liverpool
Position: 1
Points: 21
----------
Club: Manchester City
Position: 2
Points: 20
----------
Club: Arsenal
Position: 3
Points: 17
----------
Club: Aston Villa
Position: 4
Points: 17
----------
Club: Brighton & Hove Albion
Position: 5
Points: 15
----------
Club: Chelsea
Position: 6
Points: 14
----------
Club: Tottenham Hotspur
Position: 7
Points: 13
----------
Club: Nottingham Forest
Position: 8
Points: 13
----------
Club: Newcastle United
Position: 9
Points: 12
----------
Club: Fulham
Position: 10
Points: 11
----------
Club: AFC Bournemouth
Position: 11
Points: 11
----------
Club: Manchester United
Position: 12
Points: 11
----------
Club: Brentford
Position: 13
Points: 10
----------
Club: Leicester City
Position: 14
Points: 9
----------
Club: West Ham United
Position: 15
Points: 8
----------
Club: Everton
Position: 16
Points: 8
----------
Club: Ipswich Town
Position: 17
Points: 4
----------
Club: Crystal Palace
Position: 18
Points: 3
----------
Club: Southampton
Position: 19
Points: 1
----------
Club: Wolverhampton Wanderers
Position: 20
Points: 1
----------

getClubName() Function, this function takes a participant_id and makes a second API call to retrieve the club’s details, particularly the name. It returns the club’s name if the request is successful, or null if the request fails. Both API requests (standings and club name) use the same API token, which is passed into both API calls.

After the first API call to retrieve the standings, we loop through the list of LeagueStandings, making a second API call for each participant_id to get the club’s name. 

The results are printed with club name, position, and points after the code first retrieves the standings data using the participant ID. Then, for each participant ID, a second API request is made to get the club’s name. The club’s name, along with other information like position and points, are printed in readable format. 

Here’s the wrap: Unlocking the Power of Sportmonks’ Football API with Kotlin

Now that you’ve added another notch to your belt, you can see how easy it is to retrieve data from Sportmonks’ Football API.

As a summary, let’s go over all we did together. This developer’s guide covers essential topics such as setting up a local environment, installing an IDE, making a basic API request, and retrieving league details. We looked at the API’s structure and its features while retrieving basic information from the API.

We also handled the JSON results using an external library to print the output in a readable way. Those are just a few of the comprehensive set of endpoints that our Football API provides, not to mention news, xG, in-play events, live scores, and many more details. We will look at some of these in our next blog, Harnessing the Power of Sportmonks’ Football API with C#. With extensive documentation on Kotlin online, coupled with our up-to-date and constantly evolving API documentation, you too can build a mind-blowing football app using our API without breaking the bank.

These few code snippets can get you up and running in little to no time, especially if you wish to build a mobile app for Android. What are you waiting for? Check out our plans or sign up for your 14-day free trial now.

Are there any limitations or restrictions when using Sportmonks Football API with Postman?
Sportmonks Football API does not impose any specific limitations or restrictions on using Postman with the API. However, you should be mindful of your API usage limits based on your subscription plan. Additionally, ensure that you handle sensitive information such as API keys securely within Postman to prevent unauthorized access or misuse.
Can I keep my current API token?
You can use the same API token as you are currently using for API 2.0. You don't need to create another token for API 3.0.
Do I need an API token for the Football Widgets to work?
Maintenance is done by our developers, and the widgets will request our API every time it is needed. Therefore, no API token is required.
How can I test the Sportmonks API for FREE?
You have two options:
  1. Create an account on My Sportmonks and get immediate access to our free plan.
  2. Subscribe to one of our paid plans and receive a one-time-only 14-day free trial.
How do I build and filter API requests?
Use the base URL and include necessary data points like scores, events, and participants. Apply filters to refine the data to match specific criteria. Here’s an example of how to incorporate the filter into your request: https://api.sportmonks.com/v3/football/livescores/inplay?api_token=YOUR_TOKEN&include=events&filters=eventTypes:14,19,20,21 By utilising filtering capabilities, we can tailor the data retrieved from the API to match the specific needs and preferences of our livescore website. For further details on filtering techniques, refer to our dedicated filter tutorial for additional guidance.
As users, what if we get stuck and need help?
Our responsive customer support team is a trademark of our business. So, whether you're using our 5-star user documentation or chatting with our agents, you can get applications up and running in no time.

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.

Sportmonks’ Football API with Postman.

Ready to get started? Read our Postman Guide to help you get started quickly.

Read our Blog