Day 20: Connecting to REST APIs with Retrofit

📖 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

  1. Add Dependencies in build.gradle kotlinCopyEditimplementation "com.squareup.retrofit2:retrofit:2.9.0" implementation "com.squareup.retrofit2:converter-gson:2.9.0"
  2. Create a Data Model kotlinCopyEditdata class User(val id: Int, val name: String, val email: String)
  3. Define the API Interface kotlinCopyEditinterface ApiService { @GET("users") suspend fun getUsers(): List<User> @POST("users") suspend fun createUser(@Body user: User): Response<User> }
  4. Build Retrofit Instance kotlinCopyEditval 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.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top