Skip to main content

How to handle response using Retrofit in Kotlin Android

How to handle response using Retrofit in Kotlin Android.

Here's a step-by-step tutorial on how to handle response using Retrofit in Kotlin for Android.

Step 1: Setup Retrofit

First, you need to add the Retrofit dependency to your project. Open your project's build.gradle file and add the following line in the dependencies block:

implementation 'com.squareup.retrofit2:retrofit:2.9.0'

Next, create an interface that defines the API endpoints you want to call. For example, create a file called ApiService.kt and define an interface like this:

interface ApiService {
@GET("users")
fun getUsers(): Call<List<User>>
}

Here, getUsers() is a method that will be used to make a GET request to the "users" endpoint. The Call class is provided by Retrofit and represents a request that can be executed asynchronously.

Step 2: Create an instance of Retrofit

Now, create an instance of Retrofit in your activity or fragment. Add the following code to the onCreate() method:

val retrofit = Retrofit.Builder()
.baseUrl("https://api.example.com/") // Replace with your API base URL
.addConverterFactory(GsonConverterFactory.create())
.build()

val apiService = retrofit.create(ApiService::class.java)

Here, baseUrl() specifies the base URL for your API. addConverterFactory() is used to specify the converter factory to use for serialization and deserialization of objects. In this example, we're using Gson as the converter factory.

Step 3: Make a network request

To make a network request, call the desired method on the apiService instance. For example, to get a list of users, add the following code:

apiService.getUsers().enqueue(object : Callback<List<User>> {
override fun onResponse(call: Call<List<User>>, response: Response<List<User>>) {
if (response.isSuccessful) {
val users = response.body()
// Handle the list of users here
} else {
// Handle error response here
}
}

override fun onFailure(call: Call<List<User>>, t: Throwable) {
// Handle network failure here
}
})

The enqueue() method is used to enqueue the request and handle the response asynchronously. Inside the onResponse() method, you can check if the response was successful using response.isSuccessful. If it was successful, you can access the response body using response.body().

If the response was not successful, you can handle the error response inside the else block. In case of a network failure, the onFailure() method will be called.

That's it! You've successfully handled the response using Retrofit in Kotlin for Android.