Configure Retrofit for API calls with coroutines
✓Works with OpenClaudeYou are a Kotlin developer setting up Retrofit for API calls with coroutines support.
What to check first
- Verify
build.gradle.ktsincludes Retrofit 2.9+ and OkHttp dependencies - Confirm your target API level supports coroutines (API 21+)
- Check if
kotlinx-coroutines-coreis already in your dependencies
Steps
- Add Retrofit, OkHttp, and coroutines dependencies to
build.gradle.ktswith versions 2.9.0+ for Retrofit - Create a data class matching your API response structure with
@SerializedNameannotations for JSON fields - Define an interface with suspend function declarations using
@GET,@POST,@Path, and@Queryannotations - Create a singleton object using the
objectkeyword to instantiate Retrofit withOkHttpClientandGsonConverterFactory - Add interceptors to
OkHttpClient.Builder()for logging, authentication headers, or request/response handling - Return the Retrofit service instance via a method that calls
.create(YourApiInterface::class.java) - Launch coroutine calls from a ViewModel or repository using
viewModelScope.launchorGlobalScope.launch(prefer viewModelScope) - Handle responses with
try-catchblocks catchingHttpExceptionandIOExceptionseparately
Code
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.*
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import kotlinx.coroutines.launch
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.gson.annotations.SerializedName
// Data class for API response
data class UserResponse(
@SerializedName("id")
val id: Int,
@SerializedName("name")
val name: String,
@SerializedName("email")
val email: String
)
// API interface with suspend functions
interface ApiService {
@GET("users/{id}")
suspend fun getUser(@Path("id") userId: Int): UserResponse
@GET("users")
suspend fun listUsers(@Query("limit") limit: Int = 10): List<UserResponse>
@POST("users")
suspend fun createUser(@Body user: UserResponse): UserResponse
}
// Retrofit singleton
object RetrofitClient {
private const val BASE_URL = "https://jsonplaceholder.typicode.com/"
private val httpClient = OkHttpClient.Builder()
.addInterceptor(HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.BODY
})
.addInterceptor { chain ->
val request = chain.request().newBuilder()
.addHeader("Authorization", "Bearer token
Note: this example was truncated in the source. See the GitHub repo for the latest full version.
Common Pitfalls
- Treating this skill as a one-shot solution — most workflows need iteration and verification
- Skipping the verification steps — you don't know it worked until you measure
- Applying this skill without understanding the underlying problem — read the related docs first
When NOT to Use This Skill
- When a simpler manual approach would take less than 10 minutes
- On critical production systems without testing in staging first
- When you don't have permission or authorization to make these changes
How to Verify It Worked
- Run the verification steps documented above
- Compare the output against your expected baseline
- Check logs for any warnings or errors — silent failures are the worst kind
Production Considerations
- Test in staging before deploying to production
- Have a rollback plan — every change should be reversible
- Monitor the affected systems for at least 24 hours after the change
Related Kotlin / Android Skills
Other Claude Code skills in the same category — free to download.
Jetpack Compose
Build Jetpack Compose UIs with state and navigation
Room Database
Set up Room database with DAOs, entities, and migrations
Hilt DI
Set up Hilt dependency injection in Android
Kotlin Coroutines
Write coroutines with Flow, StateFlow, and error handling
Kotlin Testing
Write Android tests with JUnit, Mockk, and Espresso
Kotlin Coroutines & Flow
Use Kotlin Coroutines and Flow for reactive async streams
Android Room Database
Set up Room (SQLite) for local data persistence in Android Kotlin apps
Want a Kotlin / Android skill personalized to YOUR project?
This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.