Retrofit with Kotlin Coroutine in Android
Last Updated :
02 Jan, 2025
Retrofit is a type-safe http client which is used to retrieve, update and delete the data from web services. Nowadays retrofit library is popular among the developers to use the API key. The Kotlin team defines coroutines as “lightweight threads”. They are sort of tasks that the actual threads can execute. Coroutines were added to Kotlin in version 1.3 and are based on established concepts from other languages. Kotlin coroutines introduce a new style of concurrency that can be used on Android to simplify async code. In this article, we will learn about retrofit using Kotlin coroutine. So we will be using Retrofit for network requests. Retrofit is a very popular library used for working APIs and very commonly used as well. We will learn it by making a simple app using an API to get some data using Retrofit.
Step-by-Step Implementation
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio .
Step 2: Add dependency
Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section.
// retrofit
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
// GSON
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
// coroutine
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.2'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2'
We are using GSON to convert JSON to kotlin(Java) object. We will add these dependencies in build.gradle file inside our project.
Step 3: We will use the below API
https://quotable.io/quotes?page=1
Figure 01 So our JSON response will look like this Figure01.
Step 4 : Then we will create data classes according to JSON response
In JSON response we have 2 JSON objects, So we will create 2 data class
- QuoteList
- Results
Kotlin
// data class QuoteList
// according to JSON response
package com.ayush.retrofitexample
data class QuoteList(
val count: Int,
val lastItemIndex: Int,
val page: Int,
val results: List<Result>,
val totalCount: Int,
val totalPages: Int
)
2nd data class
Kotlin
package com.ayush.retrofitexample
data class Result(
val _id: String,
val author: String,
val authorSlug: String,
val content: String,
val dateAdded: String,
val dateModified: String,
val length: Int,
val tags: List<String>
)
Step 5 : We will create a Retrofit interface to add the endpoints of the URL (quotes in our case is the endpoint)
Kotlin
// Retrofit interface
package com.ayush.retrofitexample
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Query
interface QuotesApi {
@GET("/quotes")
suspend fun getQuotes() : Response<QuoteList>
}
Step 6 : We will create a new file to get the Retrofit object
In this file, we will have a function that will return the Retrofit object.
Kotlin
package com.ayush.retrofitexample
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
object RetrofitHelper {
val baseUrl = "https://quotable.io/"
fun getInstance(): Retrofit {
return Retrofit.Builder().baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
// we need to add converter factory to
// convert JSON object to Java object
.build()
}
}
Step 7 : Now we will link the Retrofit object and Retrofit interface file in MainActivity
Kotlin
package com.ayush.retrofitexample
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import retrofit2.create
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val quotesApi = RetrofitHelper.getInstance().create(QuotesApi::class.java)
// launching a new coroutine
GlobalScope.launch {
val result = quotesApi.getQuotes()
if (result != null)
// Checking the results
Log.d("ayush: ", result.body().toString())
}
}
}
Step 8 : Add Internet permission in the manifests file
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Results: we can check the logcat window. We can see the result in the green box.
Output:

Similar Reads
Kotlin Tutorial This Kotlin tutorial is designed for beginners as well as professional, which covers basic and advanced concepts of Kotlin programming language. In this Kotlin tutorial, you'll learn various important Kotlin topics, including data types, control flow, functions, object-oriented programming, collecti
4 min read
Kotlin Android Tutorial Kotlin is a cross-platform programming language that may be used as an alternative to Java for Android App Development. Kotlin is an easy language so that you can create powerful applications immediately. Kotlin is much simpler for beginners to try as compared to Java, and this Kotlin Android Tutori
6 min read
Retrofit with Kotlin Coroutine in Android Retrofit is a type-safe http client which is used to retrieve, update and delete the data from web services. Nowadays retrofit library is popular among the developers to use the API key. The Kotlin team defines coroutines as âlightweight threadsâ. They are sort of tasks that the actual threads can e
3 min read
Introduction to Kotlin Kotlin is a statically typed, general-purpose programming language developed by JetBrains, which has built world-class IDEs like IntelliJ IDEA, PhpStorm, Appcode, etc. It was first introduced by JetBrains in 2011 as a new language for the JVM. Kotlin is an object-oriented language, and a better lang
4 min read
Kotlin Data Types The most fundamental data type in Kotlin is the Primitive data type and all others are reference types like array and string. Java needs to use wrappers (java.lang.Integer) for primitive data types to behave like objects but Kotlin already has all data types as objects.There are different data types
3 min read
Kotlin when expression In Kotlin, when replaces the switch operator of other languages like Java. A certain block of code needs to be executed when some condition is fulfilled. The argument of when expression compares with all the branches one by one until some match is found. After the first match is found, it reaches to
6 min read
Kotlin Constructor A constructor is a special member function that is automatically called when an object of a class is created. Its main purpose is to initialize properties or perform setup operations. In Kotlin, constructors are concise, expressive, and provide significant flexibility with features like default para
6 min read
Android RecyclerView in Kotlin In this article, you will know how to implement RecyclerView in Android using Kotlin . Before moving further let us know about RecyclerView. A RecyclerView is an advanced version of ListView with improved performance. When you have a long list of items to show you can use RecyclerView. It has the ab
4 min read
ProgressBar in Android Progress Bar are used as loading indicators in android applications. These are generally used when the application is loading the data from the server or database. There are different types of progress bars used within the android application as loading indicators. In this article, we will take a lo
3 min read
Kotlin Array An Array is one of the most fundamental data structures in practically all programming languages. The idea behind an array is to store multiple items of the same data type, such as an integer or string, under a single variable name. Arrays are used to organize data in programming so that a related s
6 min read