API Calls with Retrofit in Android Kotlin: A Comprehensive Guide

Kuldeep Singh Rai
3 min readAug 8, 2023

--

In the world of modern software development, communication between different software components is crucial. One of the most common ways to achieve this is through APIs (Application Programming Interfaces). When it comes to making API calls in Android app development, Retrofit has become the go-to library due to its simplicity, efficiency, and robustness. In this article, we will explore the ins and outs of making API calls using Retrofit in a Kotlin-based Android application. Additionally, we’ll implement the singleton pattern to ensure efficient and consistent usage of the Retrofit instance and ApiService.

Prerequisites:

Before we dive into the implementation, make sure you have the following set up:

  1. Android Studio installed on your machine.
  2. Basic understanding of Kotlin programming language.
  3. Internet connectivity for API testing.

Setting Up Retrofit with Singleton Pattern:

To get started, follow these steps to add Retrofit to your Android project and implement the singleton pattern for the Retrofit instance and ApiService:

  1. Open your Android Studio project.
  2. Navigate to your build.gradle (Module: app) file and add the following dependencies:
dependencies {
// ... other dependencies

implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
}

Sync your project to ensure the new dependencies are added.

Creating Retrofit and ApiService Singletons:

In order to ensure that we have a single instance of Retrofit and ApiService throughout the application, we can implement the singleton pattern. Create a new Kotlin file, e.g., ApiClient.kt, and implement the following:

import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

object RetrofitClient {
private const val BASE_URL = "https://jsonplaceholder.typicode.com/"

val retrofit: Retrofit by lazy {
Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
}

object ApiClient {
val apiService: ApiService by lazy {
RetrofitClient.retrofit.create(ApiService::class.java)
}
}

With this implementation, you have a single instance of Retrofit and ApiService that can be accessed throughout your application.

Defining the ApiService Interface:

Now that we have our singleton pattern in place for the Retrofit instance, let’s define the ApiService interface that outlines the API endpoints and their respective HTTP methods. Create a new Kotlin file, e.g., ApiService.kt, and implement the following:

import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Path

interface ApiService {
@GET("posts/{id}")
fun getPostById(@Path("id") postId: Int): Call<Post>
}

In this example, we’ve defined a simple API endpoint to retrieve a post by its ID. Make sure to replace Post with your data model.

Making the API Call Using Singletons:

With our ApiClient singleton and ApiService interface ready, making API calls becomes straightforward. In your activity or fragment, you can now start making API calls using the ApiClient singleton. Let's assume you're making the API call when a button is clicked. Here's a simplified example:

import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val button = findViewById<Button>(R.id.button)
button.setOnClickListener {
val postId = 1 // Replace with the desired post ID
val call = ApiClient.apiService.getPostById(postId)

call.enqueue(object : Callback<Post> {
override fun onResponse(call: Call<Post>, response: Response<Post>) {
if (response.isSuccessful) {
val post = response.body()
// Handle the retrieved post data
} else {
// Handle error
}
}

override fun onFailure(call: Call<Post>, t: Throwable) {
// Handle failure
}
})
}
}
}

Conclusion:

Retrofit simplifies the process of making API calls in Android applications. By implementing the singleton pattern for the Retrofit instance and ApiService, you ensure a single and efficient instance throughout your app. This article covered the basics of using Retrofit for API calls in Kotlin-based Android projects, introduced the concept of singletons for better performance and maintainability, and included the ApiService interface definition that outlines the API endpoints. As you continue to explore Retrofit and its advanced features, remember that using singletons is just one of the many strategies you can employ to optimise your app’s networking layer.

Further Exploration:

  1. Explore Retrofit documentation: Retrofit Documentation
  2. Learn about different types of HTTP methods: HTTP Methods
  3. Implement error handling in API calls with Retrofit: Error Handling with Retrofit
  4. Enhance your app’s networking layer with OkHttp: OkHttp
  5. Dive into advanced Retrofit topics like authentication and request customisation.

Remember that practice and experimentation are key to becoming proficient with Retrofit and networking in Android app development.

--

--