📖 Introduction
In modern Android development, interacting with a server is essential for real-time data, dynamic content, and app scalability. Retrofit, developed by Square, is one of the most powerful and easy-to-use libraries to connect Android apps with REST APIs. Whether you’re fetching weather data, user info, or sending a post request, Retrofit makes it clean and scalable.
🚀 What is Retrofit?
Retrofit is a type-safe HTTP client for Android and Java that lets you define your network requests as interfaces and use annotations to simplify HTTP methods like GET
, POST
, PUT
, and DELETE
. It converts HTTP API into a Java/Kotlin interface.
💡 Why Use Retrofit?
- Built-in support for Gson, Moshi, Kotlin Coroutines
- Clean API abstraction via interfaces
- Handles JSON conversion automatically
- Supports error handling, interceptors, logging
- Easily testable and modular
⚙️ Setting Up Retrofit in Android
- Add Dependencies in
build.gradle
kotlinCopyEditimplementation "com.squareup.retrofit2:retrofit:2.9.0" implementation "com.squareup.retrofit2:converter-gson:2.9.0"
- Create a Data Model kotlinCopyEdit
data class User(val id: Int, val name: String, val email: String)
- Define the API Interface kotlinCopyEdit
interface ApiService { @GET("users") suspend fun getUsers(): List<User> @POST("users") suspend fun createUser(@Body user: User): Response<User> }
- Build Retrofit Instance kotlinCopyEdit
val retrofit = Retrofit.Builder() .baseUrl("https://api.example.com/") .addConverterFactory(GsonConverterFactory.create()) .build() val apiService = retrofit.create(ApiService::class.java)
🔁 Using Retrofit with Coroutines
viewModelScope.launch {
try {
val users = apiService.getUsers()
// Update UI
} catch (e: Exception) {
// Handle error
}
}
🛡️ Error Handling Best Practices
- Wrap API calls with
try-catch
- Use
Response<T>
to check HTTP status codes - Use
OkHttp Interceptor
for global error tracking - Implement a
sealed class ApiResult<Success, Error>
for state management
🧪 Testing Retrofit Services
- Use
MockWebServer
for unit testing APIs - Inject Retrofit instance using Hilt/Dagger for testable architecture
[ UI Layer (e.g., ViewModel) ]
|
v
🔄 Launch Coroutine (viewModelScope.launch)
|
v
[ Retrofit API Interface ]
|
----------------------------------
| | |
@GET @POST Other HTTP Methods
getUsers() createUser(User) (PUT, DELETE, etc.)
|
v
[ Retrofit Instance with Base URL ]
|
v
[ OkHttpClient + Converter (e.g., Gson) ]
|
v
🌐 HTTP Request to REST API Server
|
v
📥 Response Received (JSON/XML)
|
v
[ Parsed via Converter -> Kotlin Data Class ]
|
v
🛡️ Error Handling (try-catch, Response<T>, Interceptor)
|
v
[ Update UI / Emit State via ApiResult ]
🧩 Key Points:
- What is Retrofit?
- Why use Retrofit for API calls in Android
- How to set up Retrofit in your Android project
- Making GET and POST requests
- Handling JSON with Gson/Moshi
- Retrofit + Coroutines integration
- Error handling and best practices
✅ Conclusion
Using Retrofit with Kotlin and Coroutines is a modern and efficient way to interact with REST APIs. It reduces boilerplate code, improves readability, and ensures smooth data flow between your backend and app. With a solid setup and best practices, you’ll build faster, safer, and more scalable Android apps.