This is probably a very basic process, but it’s something I’ve struggled to do in Kotlin as the vast majority of examples are shown using Java. While I would have been able to get my head around that code given some time, the process would have been a lot simpler had I seen a Kotlin version instead. So, I’ve made this post.
The sole goal of this post is to be able to connect to an external API and retrieve its data using Kotlin. This post won’t cover parsing the data in any form other than a string – parsing will come in a later post. For now, I just want to get some data in!
If you want to go straight to the code, it lives here.
First, we set up a very basic project using Spring Initializer. I set this up as a Gradle project and will be using the Kotlin DSL (Domain Specific Language) for the build file.
Coming from JavaScript land, I tended to use the built-in ‘fetch’ function to call an API so that I wouldn’t need to pull in any dependencies. However, I have been told many times that it’s best to use a client like OkHttp when using Kotlin for web development.
To be able to use OkHttp, we need to bring it in as a dependency. This is done through the build.gradle.kts
file in the dependencies block:
When we import our Gradle project, we’ll have access to OkHttp and the methods it brings for making a simple API call.
Next, we create a Repository
class that will hold the code for calling the API (note that it doesn’t need to have a Repository
annotation).
makeRequest()
function) so that we can access its methods;Request.Builder()
and pass it a URL to hit. As we don’t need any further information for this API, we can just build the request. However, you may need to use the .addHeader
method to, for example, to extra information to the API;makeRequest()
function, we are doing a few things. First, we’re taking the request we built. Then, we’re asking OkHttp to make a new API call and execute that API call.makeRequest()
function. This is a Spring annotation that calls the function after the initialization of the bean properties. It gets called once the beans have been instantiated and the initial delay has passed. The fixedDelay
tells the function how long to wait until it runs next.println(parsedResponse)
call within makeRequest()
. This is just to prove that we’ve got a response.And here’s the output:
At the moment this isn’t largely useful as we’ll want to parse out the data and manipulate/store that information. However, we’ve managed to get data in from an external API, which is a start!
I hope that this post is useful to some beginner Kotliners. Check back in soon; we’ll parse that data into a more manageable format.
https://github.com/square/okhttp
If you enjoyed this type of content and would like to see more, feel free to check out my social media accounts:
Free Resources