$npx -y skills add rcosteira79/android-skills --skill android-retrofitUse when setting up or working with Retrofit in Android — service interface definitions, coroutines integration, OkHttp configuration, Hilt module setup, and error handling in the repository layer.
| 1 | # Android Networking with Retrofit |
| 2 | |
| 3 | Modern Retrofit setup for Android using coroutines, `kotlinx.serialization`, and Hilt. This reference covers the decisions that are easy to get wrong, not the standard boilerplate of service interfaces, Hilt module wiring, and the converter setup. |
| 4 | |
| 5 | ## Service interface |
| 6 | |
| 7 | Declare every endpoint as a `suspend` function. **Return the body type directly** — Retrofit throws `HttpException` on non-2xx, giving a clean `try/catch` at the repository boundary. Use `Response<T>` **only** when you need the status code, headers, or error body (e.g. server-side validation messages): |
| 8 | |
| 9 | ```kotlin |
| 10 | // Direct body — throws HttpException on non-2xx; the common case |
| 11 | @GET("users/{user}/repos") |
| 12 | suspend fun listRepos(@Path("user") user: String): List<Repo> |
| 13 | |
| 14 | // Response wrapper — only when you need code/headers/error body |
| 15 | @GET("users/{user}") |
| 16 | suspend fun getUser(@Path("user") user: String): Response<User> |
| 17 | ``` |
| 18 | |
| 19 | Wrapping every endpoint in `Response<T>` "just in case" forces callers to check `isSuccessful` and handle a nullable body even when only the body matters — don't. |
| 20 | |
| 21 | ## OkHttp & JSON |
| 22 | |
| 23 | Standard wiring (in a Hilt `@Module`/`@Provides @Singleton`): `HttpLoggingInterceptor` with its level gated on `BuildConfig.DEBUG`, sensible connect/read timeouts, and the `kotlinx.serialization` converter (`json.asConverterFactory("application/json".toMediaType())`). For an API that's loose with its payloads, configure: |
| 24 | |
| 25 | ```kotlin |
| 26 | Json { ignoreUnknownKeys = true; coerceInputValues = true; isLenient = true } |
| 27 | ``` |
| 28 | |
| 29 | ## Auth: interceptor, and the throw-vs-proceed decision |
| 30 | |
| 31 | Attach the token via an `Interceptor`, not a per-endpoint `@Header` — a single missed `@Header` parameter is an unauthenticated request that fails at runtime, not compile time. The part most often gotten wrong is **what to do when the token is absent**: |
| 32 | |
| 33 | ```kotlin |
| 34 | class AuthInterceptor @Inject constructor( |
| 35 | private val tokenProvider: TokenProvider, |
| 36 | ) : Interceptor { |
| 37 | override fun intercept(chain: Interceptor.Chain): Response { |
| 38 | val token = tokenProvider.getToken() |
| 39 | ?: throw IOException("Auth token unavailable") // fail fast — see note below |
| 40 | val request = chain.request().newBuilder() |
| 41 | .header("Authorization", "Bearer $token") |
| 42 | .build() |
| 43 | return chain.proceed(request) |
| 44 | } |
| 45 | } |
| 46 | ``` |
| 47 | |
| 48 | > **Throw vs proceed:** **Throw** when all endpoints require auth — a missing token should surface immediately rather than silently producing a confusing 401. **Proceed without the header** only if the same `OkHttpClient` is shared between authenticated and public endpoints: `?: return chain.proceed(chain.request())`. Silently proceeding when every call needs auth is a common mistake. |
| 49 | |
| 50 | ## Error handling |
| 51 | |
| 52 | The repository is the error boundary: catch `HttpException`/`IOException` there and map them to a domain error type — never let Retrofit/OkHttp exception types reach the ViewModel, and never expose Retrofit DTOs to it. Don't redefine the error hierarchy here; see `android-skills:android-data-layer` for the repository pattern and the shared `DataError` taxonomy. |
| 53 | |
| 54 | ## Checklist |
| 55 | |
| 56 | - [ ] All service functions are `suspend` |
| 57 | - [ ] `Response<T>` only when you need the status code, headers, or error body |
| 58 | - [ ] `OkHttpClient` logging gated behind `BuildConfig.DEBUG`; sensible timeouts set |
| 59 | - [ ] Auth applied via an `Interceptor`, with the token-absent policy chosen (throw vs proceed) |
| 60 | - [ ] Network exceptions mapped to domain types at the repository; DTOs never reach the ViewModel |