What is Retrofit and why is it needed?
Retrofit is a type-safe HTTP client for Java and Kotlin, developed by Square. It is one of the most popular libraries for working with REST APIs in the Android ecosystem. Retrofit allows developers to easily and elegantly perform HTTP requests to remote servers, automatically converting JSON responses into Kotlin objects and vice versa.
Why is Retrofit needed?
- Simplifies working with APIs: Instead of writing bulky code with HttpURLConnection or OkHttp, you define an interface with annotations, and Retrofit generates the implementation itself.
- Automatic serialization/deserialization: Thanks to integration with converters (Gson, Moshi, Kotlinx Serialization), Retrofit automatically converts JSON into Kotlin objects.
- Support for various HTTP methods: GET, POST, PUT, DELETE, PATCH, HEAD, and OPTIONS.
- Header and parameter management: Easily add dynamic or static headers, query parameters, and path parameters.
- Asynchrony: Support for Kotlin coroutines (suspend functions) and Callback interfaces.
- Integration with OkHttp: Retrofit uses OkHttp as its HTTP engine, providing access to powerful request interception capabilities (interceptors).
Retrofit is ideal for Android applications that interact with RESTful web services: from simple weather apps to complex social networks.
Installing Retrofit in a Kotlin Project
Unlike Python (where pip is used), in Kotlin/Android projects dependencies are managed via Gradle. Add the following lines to your module's build.gradle.kts (or build.gradle) file (usually app):
// build.gradle.kts (Module :app)dependencies { // Main Retrofit library implementation("com.squareup.retrofit2:retrofit:2.9.0") // Converter for working with JSON (Gson) implementation("com.squareup.retrofit2:converter-gson:2.9.0") // Alternative converter (Moshi) // implementation("com.squareup.retrofit2:converter-moshi:2.9.0") // For coroutine support (suspend functions) implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3") // OkHttp (usually already included, but can be added explicitly) implementation("com.squareup.okhttp3:okhttp:4.12.0") implementation("com.squareup.okhttp3:logging-interceptor:4.12.0")}Important: After adding dependencies, click "Sync Now" in Android Studio to download the libraries.
Quick Start: Code Example
Let's create a simple application that retrieves a list of posts from JSONPlaceholder (a free test API).
Step 1: Create a data class for the response
data class Post( val userId: Int, val id: Int, val title: String, val body: String)Step 2: Define the API interface
interface ApiService { @GET("posts") suspend fun getPosts(): List<Post> @GET("posts/{id}") suspend fun getPostById(@Path("id") postId: Int): Post}Step 3: Create the Retrofit client
object RetrofitClient { private const val BASE_URL = "https://jsonplaceholder.typicode.com/" val instance: ApiService by lazy { Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build() .create(ApiService::class.java) }}Step 4: Use in Activity or ViewModel
class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) {