Contents
CWCoding With DhrumilCW Practical Flutter and Kotlin tutorials for working mobile developers

Home › Articles

Retrofit2 with Kotlin: A Practical Getting-Started Guide

By Priya Shah · Published · Updated · 4 min read

Network cable plugged into a server port representing HTTP client setup.
Network cable plugged into a server port representing HTTP client setup. · Foto: Martinelle / Pixabay

Retrofit2 is still the most common HTTP client in Android codebases written in Kotlin, and for good reason: it turns a plain interface into type-safe API calls with almost no boilerplate. This guide walks through a working setup from an empty project to your first parsed response, with the numbers you actually care about along the way.

We will cover Gradle dependencies, the converter that turns JSON into Kotlin data classes, how to choose between suspend functions and Call, and the error paths that bite people in production. Expect concrete timings and a comparison table so you can decide what fits your app.

Add Retrofit2 and a JSON Converter to Your Project

Start with three dependencies: the Retrofit core, a converter such as Moshi or Gson, and OkHttp logging if you want readable request logs during development. In a typical Kotlin Android project this adds roughly 400–700 KB to the APK after shrinking, which is small enough to justify on almost any app. Pin exact versions in your version catalog or build file; mismatched converter and core versions are the most common first-day crash.

If you plan to use Kotlin coroutines, Retrofit 2.6.0 and later supports suspend functions natively, so no extra adapter is needed. For older codebases still returning Call<T>, you will add the coroutine call adapter separately. Either way, keep the HTTP client instance as a singleton — creating one per screen multiplies connection pools and thread usage, and that cost shows up quickly in memory profiles.

  • retrofit core plus one converter (Moshi, Gson, or kotlinx.serialization)
  • okhttp logging-interceptor for debug builds only
  • a single OkHttpClient shared across all Retrofit instances
  • explicit timeouts: 10–20 s connect, 30 s read is a sane default
650Cold start120Warm connection2500Slow network400Server error200Empty 204
Typical Retrofit2 request latency by scenario (ms) (milliseconds)

Define the Interface and Data Classes

A Retrofit service is just an interface with annotations. Declare suspend functions for one-shot requests and return the parsed body directly; wrap it in Response<T> only when you need status codes and headers. Data classes should mirror the JSON exactly, with default values for fields the server may omit — nullable fields are safer than non-null ones when the backend is outside your control.

Keep the interface small and focused: one service per feature area, not one giant API class. When a response shape changes, you want the change to touch a single file. For list endpoints, page sizes of 20–50 items are typical; design your data class around that and let the UI layer handle paging rather than the network layer.

Wire Up the Retrofit Instance and Base URL

Build the Retrofit instance once, usually in a dependency injection module or a simple object. Use a base URL ending in a slash and relative paths on the interface methods — missing that slash is the classic cause of doubled path segments. For environment switching, keep debug and release base URLs in BuildConfig rather than hardcoding them in the service interface.

Timeouts deserve real thought. Mobile networks routinely add 200–800 ms of latency before your request even leaves the device, and flaky connections can stall for several seconds. A 10-second connect timeout and 30-second read timeout covers most APIs without making users stare at a spinner indefinitely. Add retry logic only for idempotent GETs and cap it at one or two attempts.

Calling the API From a ViewModel

Call the suspend function from viewModelScope so the request cancels when the ViewModel clears. Wrap the call in try/catch for IOException and HttpException, and expose a sealed UI state — loading, success, error — instead of raw exceptions. This keeps your composables or fragments dumb and testable. If you are still deciding how much state belongs in the widget layer, our comparison of StatelessWidget vs StatefulWidget is worth a read before you split things up.

Cancellation matters more than people expect: a user tapping back during a slow request should not leave a coroutine running for 30 seconds. Structured concurrency handles this for free when you use viewModelScope, but only if you avoid GlobalScope and fire-and-forget patterns. Our notes on common coroutine mistakes cover the specific traps around scope and exception handling.

Typical timings and costs for a small Retrofit2 setup on Android
ScenarioTypical latencyRetry adviceNotes
First request, cold connection400–900 msNoneIncludes DNS and TLS handshake
Repeat request, warm connection50–200 msNoneConnection reuse via OkHttp pool
Slow mobile network1–4 sOne retrySet read timeout to 30 s
Server 5xx response200–600 msOne retry, 1–2 s backoffOnly for idempotent calls
Empty 204 response100–300 msNoneReturn Unit to avoid parse errors
APK size added (shrunk)400–700 KB—Core plus one converter

Handle Errors and Empty Responses Properly

HTTP errors arrive as HttpException when you use suspend functions, and network failures as IOException. Treat 4xx as permanent for that request — retrying a 401 or 422 wastes battery — while 5xx and timeouts are candidates for a single retry with a short backoff. Parse the error body when the API returns structured messages, but never let a malformed error body crash the app.

Empty bodies and 204 responses are another quiet source of crashes. If your function returns a non-null type and the body is empty, Retrofit throws; declare Unit or a nullable type for endpoints that may return nothing. Log the raw response once during development, then remove verbose logging from release builds — request logs can leak tokens and add measurable overhead.

  • 4xx: show a message, do not retry automatically
  • 5xx and timeouts: one retry with 1–2 s backoff
  • 204 or empty body: return Unit or nullable type
  • logging interceptor: debug builds only, never in release

Measure Before You Optimize

Once the first call works, measure it. Log the time from request start to parsed response — on a decent connection a small JSON payload typically lands in 150–600 ms including TLS handshake, and subsequent calls on the same connection drop to 50–200 ms. Those numbers tell you whether the bottleneck is the network or your parsing and UI work.

If you later add caching with OkHttp, a 60-second cache on list endpoints can cut repeat requests dramatically without stale data becoming a problem for most feeds. And if you are comparing HTTP clients for a new module, our Retrofit vs Ktor Client comparison puts the trade-offs side by side.

  • Keep one OkHttpClient and one Retrofit instance for the whole app.
  • Prefer suspend functions with viewModelScope over Call<T> in new Kotlin code.
  • Set explicit connect and read timeouts; retry only idempotent requests and only once.
  • Measure cold versus warm request latency before adding caching or retries.
Priya Shah · Android and Kotlin author
Covers Kotlin, Jetpack libraries and Android architecture with a hands-on approach. Focuses on migration guides, database work and networking patterns for small teams.

Related articles

↑