Table of Contents
Introduction
Retrofit is a popular networking library for Android that makes calling REST APIs simpler and more structured. In this chapter you will focus only on setting up Retrofit in an Android project. You will not yet design API interfaces or parse responses in detail, because those topics belong to later chapters.
The goal here is that by the end of this chapter you can add Retrofit to your project, create a basic Retrofit instance, and understand where this code belongs in an Android app.
Adding Retrofit to your project
Retrofit is added as a Gradle dependency. You always work in the app module build.gradle or build.gradle.kts file, not the project level one.
In Groovy based Gradle scripts you add dependencies inside the dependencies block.
dependencies {
implementation "com.squareup.retrofit2:retrofit:2.9.0"
}In Kotlin DSL scripts you use a slightly different syntax, but the idea is the same.
dependencies {
implementation("com.squareup.retrofit2:retrofit:2.9.0")
}After you add the dependency you must sync the project. Android Studio usually shows a notification at the top with a "Sync Now" button. Syncing downloads the library and makes it available to your code.
Always sync Gradle after adding or changing Retrofit dependencies. If you forget, your imports will fail and the code will not compile.
Adding a converter dependency
Retrofit only knows how to handle raw HTTP bodies by default. In real apps you almost always want Retrofit to convert JSON into Kotlin data classes automatically. This conversion is handled by a converter.
One of the most common choices is the Gson converter.
For Groovy Gradle:
dependencies {
implementation "com.squareup.retrofit2:retrofit:2.9.0"
implementation "com.squareup.retrofit2:converter-gson:2.9.0"
}For Kotlin DSL:
dependencies {
implementation("com.squareup.retrofit2:retrofit:2.9.0")
implementation("com.squareup.retrofit2:converter-gson:2.9.0")
}Later, when you configure the Retrofit instance, you will plug this converter into Retrofit so that responses can be mapped to your data classes.
Creating a basic Retrofit instance
After adding the dependencies, the next step is to create a Retrofit object. This object holds the base settings for your API calls, such as the root URL and the converter.
A minimal Retrofit instance looks like this:
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
val retrofit = Retrofit.Builder()
.baseUrl("https://api.example.com/")
.addConverterFactory(GsonConverterFactory.create())
.build()
The baseUrl must end with a /. This is a strict requirement.
Retrofit baseUrl must end with /. For example https://api.example.com/ is valid, but https://api.example.com without the trailing slash causes an error.
The converter factory connects Retrofit with Gson so JSON responses can be turned into Kotlin objects. The exact way these objects are defined is handled later in the course.
Choosing where to place the Retrofit setup
You should not create a new Retrofit instance every time you perform an API call. Creating one instance and reusing it is more efficient and easier to maintain.
A common simple pattern is to place Retrofit setup inside a Kotlin object, which gives you a singleton instance.
object RetrofitClient {
private const val BASE_URL = "https://api.example.com/"
val instance: Retrofit by lazy {
Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
}
The by lazy keyword ensures that the Retrofit instance is created only when you use it for the first time, not when the app starts. This object can live in a file such as RetrofitClient.kt inside a network or data package.
Later, when you learn about dependency injection, you will see more advanced ways to manage this kind of global object. For now, an object is simple and works for small apps.
Adding a logging interceptor (optional but useful)
While developing and debugging, it is very helpful to see the HTTP requests and responses in Logcat. For this you use OkHttp logging interceptor. OkHttp is the HTTP client library used by Retrofit internally.
First, add the interceptor dependency.
For Groovy Gradle:
dependencies {
implementation "com.squareup.retrofit2:retrofit:2.9.0"
implementation "com.squareup.retrofit2:converter-gson:2.9.0"
implementation "com.squareup.okhttp3:logging-interceptor:4.12.0"
}For Kotlin DSL:
dependencies {
implementation("com.squareup.retrofit2:retrofit:2.9.0")
implementation("com.squareup.retrofit2:converter-gson:2.9.0")
implementation("com.squareup.okhttp3:logging-interceptor:4.12.0")
}
Then, create an OkHttpClient with the interceptor and pass it to Retrofit.
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
object RetrofitClient {
private const val BASE_URL = "https://api.example.com/"
private val loggingInterceptor = HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.BODY
}
private val httpClient = OkHttpClient.Builder()
.addInterceptor(loggingInterceptor)
.build()
val instance: Retrofit by lazy {
Retrofit.Builder()
.baseUrl(BASE_URL)
.client(httpClient)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
}You should only use detailed logging in debug builds. For release builds you normally reduce or disable logging. That build specific handling is usually done with build configs and is not the focus of this chapter.
Using the Retrofit instance to create API services
Retrofit uses interfaces to describe endpoints, which you will study in the next chapter. For setup purposes, you only need to know that you call retrofit.create(...) on your instance.
With the RetrofitClient singleton from earlier, you might later write something like this:
val retrofit = RetrofitClient.instance
val api = retrofit.create(MyApiService::class.java)
At this stage you do not have to define MyApiService. The important part is that a correctly configured Retrofit instance can now be reused across your app to create one or more service interfaces.
Summary
In this chapter you have set up Retrofit in an Android project. You added the core Retrofit library, a JSON converter, and optionally a logging interceptor. You learned how to create a single reusable Retrofit instance and where to place this setup code. In the next chapter, you will focus on defining API interfaces that use this instance to perform real network requests.