skip to content

Retrofit

Retrofit turns an annotated Kotlin interface into HTTP calls, with converters for bodies and call adapters for return types. Interviewers probe the layers beneath the annotations.

on this pageshow

explore

questions

page 1 of 2

In Retrofit 3, what may a suspend service method return, and why does Retrofit reject one declared to return Call<T>?

level: juniorimportance: must knowfreq 75%

answer

  1. three legal shapes, no adapter artifact
  2. body, Response wrapper, or nothing
  3. treated as if it returned Call<T>
  4. already asynchronous, so no nested Call

basics

~10 s

A Retrofit 3 suspend method returns the body type T, Response<T> when status and headers matter, or Unit to discard the body. Call<T> is rejected because a suspend method already runs its call asynchronously.

solid answer

~40 s

A `suspend` service method can return the deserialized body `T`, a `Response<T>` when the caller needs the status code and headers, or `Unit` when the body should be thrown away. Retrofit treats the method as if it returned `Call<T>`, enqueues that call and suspends until OkHttp answers, so it needs no extra adapter dependency and is safe to call from the main thread. A body-returning method throws `HttpException` for a non-2xx status, while `Response<T>` hands every HTTP response back to you. Declaring `suspend fun user(): Call<User>` would ask for a second, unexecuted call inside an already asynchronous one; since 2.10.0 Retrofit rejects that eagerly with a message telling you to return the body type instead.

code

kotlin · 18 lines
kotlin
import retrofit2.Response
import retrofit2.http.DELETE
import retrofit2.http.GET
import retrofit2.http.Path
import retrofit2.http.Query

data class Order(val id: Long, val status: String)

interface OrdersApi {
    @GET("orders/{id}")
    suspend fun order(@Path("id") id: Long): Order

    @GET("orders")
    suspend fun ordersPage(@Query("cursor") cursor: String?): Response<List<Order>>

    @DELETE("orders/{id}")
    suspend fun cancelOrder(@Path("id") id: Long): Unit
}

go deeper

for a junior

Name the three return shapes, body, Response<T> and Unit, and say that a non-2xx status throws HttpException only when you asked for the body.

for a middle

Explain that Retrofit adapts a suspend method as Call<T>, enqueues it and resumes the coroutine, which is why no adapter artifact is needed and the main thread is safe.

for a senior

Know the edges: the eager rejection of suspend methods returning Call since 2.10.0, Unit versus Void for empty bodies, and that request serialization still runs on the calling thread.

for a principal

Be ready to set a team convention for when service methods return T versus Response<T>, so that header-driven and status-driven endpoints stay explicit.

## What a suspend method may return Since Retrofit 2.6.0 a service interface method can carry Kotlin's `suspend` modifier. Retrofit 3.0.0 keeps that support unchanged, and it is **built into the core artifact**: unlike RxJava or Guava return types, no extra `CallAdapter.Factory` has to be added to the `Retrofit.Builder`. | Declared return type | What the caller gets | Typical use | |---|---|---| | `T` (for example `Order`) | the converted body of a 2xx response | most reads and writes | | `Response<T>` | the full `retrofit2.Response`: `code()`, `headers()`, `body()`, `errorBody()` | pagination headers, ETags, branching on status | | `Unit` | nothing; the body is closed without being converted | a DELETE or a fire-and-forget POST | A method returning `T` throws `retrofit2.HttpException` when the status is outside 2xx, and a method returning `Response<T>` returns that response instead, so the caller checks `isSuccessful`. Both still throw an `IOException` for a transport failure; how an app sorts those outcomes into results is covered in the lesson on Retrofit's HTTP errors. ## What Retrofit does behind the scenes The suspend method is not magic; it is the ordinary `Call` machinery with a Kotlin bridge on top. When Retrofit parses the method it: 1. Notices the hidden `Continuation` parameter that the Kotlin compiler adds to every `suspend` function. 2. Reads the continuation's type argument. If it is `Response<T>`, it unwraps `T` and remembers that the caller wants the whole response. 3. Asks the call-adapter factories for an adapter for **`Call<T>`**, not for the declared type, and marks the method with `@SkipCallbackExecutor` so the Android main-thread hop is skipped. 4. On each invocation, builds an `OkHttpCall`, passes it through that adapter, and calls one of Retrofit's own Kotlin extensions: `await()`, its nullable and `Unit` variants, or `awaitResponse()`. 5. Those extensions call `Call.enqueue()` inside a cancellable continuation, then resume the coroutine with the body, the response or the exception. Because of step 3, a suspend method and a method returning `Call<T>` share the same adapter lookup, which is why a custom `CallAdapter.Factory` for suspend methods must recognise `Call<...>`. ## Why Call<T> is rejected A suspend method returning `Call<User>` would mean: suspend, perform an asynchronous call, and hand back yet another call that nobody has executed. That is never what the author wants. Retrofit 2.10.0 started rejecting it **eagerly**, when the method is parsed, with the message "Suspend functions should not return Call, as they already execute asynchronously" followed by the suggested return type. Parsing happens on the method's first invocation, or for every method at `create()` when the builder has `validateEagerly(true)`. ## Threading - The HTTP exchange runs on OkHttp's dispatcher threads, because the call is enqueued rather than executed. - Response conversion happens on that background thread too, inside `OkHttpCall`, before the coroutine resumes. - The coroutine resumes on the dispatcher it was called from, so a call made from `Dispatchers.Main` can update the UI directly afterwards. - Building the request, including serializing a `@Body` with most converters, runs on the calling thread; Retrofit 2.12.0 added a `withStreaming()` option to several first-party converters to defer that work. Wrapping a suspend Retrofit call in `withContext(Dispatchers.IO)` is therefore harmless but unnecessary. ## Choosing between the three - Return **`T`** when the caller only needs the data and treats every non-2xx as an error. - Return **`Response<T>`** when headers or specific status codes drive behaviour, such as a `Link` header for the next page or a 304 handled as "unchanged". - Return **`Unit`** for endpoints whose body the app does not read. Retrofit special-cases `Unit`; Java's `Void` makes the converter produce `null`, which a suspend method's non-null body check then rejects. ## Common mistakes - Keeping `Call<T>` return types and wrapping `execute()` in a coroutine, which blocks a thread and loses cancellation; declare the method `suspend` instead. - Adding a third-party coroutine call adapter left over from before 2.6.0; suspend support needs no factory at all. - Returning `T` and then needing a header, which the body type cannot carry; switch that one method to `Response<T>`. - Assuming `Response<T>` turns every failure into a value; transport and conversion failures still throw. ## Version notes `suspend` support arrived in 2.6.0, with `Response<T>` as an alternative return type from the start. `Unit` became a built-in body-discarding type in 2.5.0 and was broadened in 2.10.0. Retrofit 3.0.0 changed the OkHttp dependency to 4.12, not the suspend contract, and 3.x stays binary-compatible with libraries compiled against 2.x.

  • You already have a Call<T> from an older service method; how do you use it inside a coroutine?
    Retrofit ships Kotlin extensions on `Call`: `await()` returns the body and throws `HttpException` for a non-2xx status, and `awaitResponse()` returns the `Response<T>`. Both enqueue the call and cancel it if the coroutine is cancelled, so there is no need to wrap `execute()` in a background dispatcher.
  • Why does a suspend method returning Response<User> still throw in some cases?
    `Response<T>` only absorbs HTTP-level outcomes: any status code comes back as a response. A timeout, a refused connection or a dropped socket still throws an `IOException`, and a body the converter cannot parse throws from the converter. Turning those into results is a separate decision covered with Retrofit's error handling.
  • Is it safe to call a Retrofit suspend method from Dispatchers.Main?
    Yes. Retrofit enqueues the OkHttp call, so the network exchange and the response conversion happen on OkHttp's background threads, and the coroutine resumes on the main dispatcher afterwards. Only request building, including most converters' body serialization, runs on the calling thread.

  • A suspend Retrofit method should still return Call<T> and be awaited.
  • You must add a separate coroutine call adapter factory for suspend methods.
  • A suspend Retrofit call blocks its thread unless wrapped in withContext(Dispatchers.IO).
  • Returning Response<T> means the suspend method can never throw.
  • Endpoints without a body must return ResponseBody because Unit is not supported.

Assumes Retrofit 3.0.0; suspend methods date from 2.6.0, and the eager rejection of a suspend method returning Call arrived in 2.10.0.

open as a page

In Retrofit 3, what does a converter factory do, and what happens if a service method returns a data class with none registered?

level: juniorimportance: must knowfreq 70%

basics

~20 s

A Retrofit converter factory turns a successful response body into the declared type and a @Body value into a request body. With none added, only ResponseBody, RequestBody, Unit and Void work; a data class fails with "Unable to create converter".

open as a page

With Retrofit, what happens on an HTTP 404 when a suspend service method returns User instead of Response<User>?

level: juniorimportance: must knowfreq 75%

basics

~20 s

Returning User, the suspend method throws HttpException on a 404, since it can only hand back a body. Returning Response<User>, it returns normally and you check isSuccessful, code() and errorBody(); a network failure throws either way.

open as a page

In Retrofit, how do you declare a service method that uploads a profile photo file together with a text caption?

level: juniorimportance: must knowfreq 55%

basics

~10 s

Annotate the method with @Multipart and a body-carrying verb such as @POST, pass the photo as @Part MultipartBody.Part built by createFormData with a filename, and pass the caption as @Part("caption") RequestBody.

open as a page

Why does Retrofit.Builder reject a baseUrl such as https://tracker.example.com/api/v2, and how do endpoint paths resolve against a base URL?

level: juniorimportance: must knowfreq 65%

basics

~20 s

A baseUrl with a path must end in a slash, or relative endpoints would replace its last segment; Retrofit.Builder throws IllegalArgumentException otherwise. Endpoints resolve like web links: relative paths append, a leading slash keeps only the host, a full URL replaces it.

open as a page

In Retrofit, how do @Path, @Query, @QueryMap and @Body map method arguments onto a request, and how does each treat null?

level: juniorimportance: must knowfreq 80%

basics

~20 s

@Path fills a {block} in the annotation's relative URL, @Query appends name=value pairs, @QueryMap appends a whole map and @Body becomes the converted request body. Of the four, only @Query skips null; null @Path, @Body or map entries throw IllegalArgumentException.

open as a page

In Retrofit, how do Call.execute() and Call.enqueue() differ, and on which thread does each deliver its result on Android?

level: middleimportance: must knowfreq 65%

basics

~20 s

Call.execute() sends the request synchronously and returns a Response on the calling thread, so it must never run on Android's main thread. Call.enqueue() sends it on OkHttp's threads and, on Android, invokes the Callback on the main thread.

open as a page

With Retrofit, why must ScalarsConverterFactory be added before a JSON converter factory when one endpoint returns plain text?

level: middleimportance: must knowfreq 62%

basics

~20 s

Retrofit asks converter factories in the order they were added and uses the first non-null converter. JSON factories claim every type, so a String return reaches the JSON parser and plain text fails; scalars must come first to claim String.

open as a page

In a Retrofit checkout call, how do you tell no network, a declined card's HTTP 402 and a malformed response body apart?

level: middleimportance: must knowfreq 70%

basics

~20 s

No network surfaces as an IOException. A 402 is a complete response, so a suspend method returning the body throws HttpException with code() 402. A malformed 2xx body fails in the converter, which throws its own exception.

open as a page

In a Retrofit app, how do you add a bearer token to every request through the OkHttpClient, and why not use @Header on each method?

level: middleimportance: must knowfreq 74%

basics

~20 s

Write an OkHttp Interceptor that reads the current token, copies the request with newBuilder().header("Authorization", "Bearer ..."), and calls chain.proceed; add it to the one OkHttpClient given to Retrofit, so no service method has to carry the token.

open as a page

With Retrofit on OkHttp, how does an Authenticator refresh an expired access token after a 401, and how do you stop it retrying forever?

level: seniorimportance: must knowfreq 68%

basics

~20 s

OkHttp calls the client's Authenticator when a server answers 401; it refreshes the token synchronously and returns the request with a new Authorization header, or returns null to hand the 401 back. Guard it with an attempt count and a token comparison.

open as a page

In a Retrofit app, how do you log HTTP traffic with OkHttp's HttpLoggingInterceptor, and how do you keep it out of release builds?

level: juniorimportance: should knowfreq 62%

basics

~20 s

Add an HttpLoggingInterceptor to the OkHttpClient passed to Retrofit.Builder.client(), pick BASIC, HEADERS or BODY in debug builds, keep NONE (its default) in release, and call redactHeader("Authorization") so the bearer token is masked in the log.

open as a page

In Retrofit, how does a service method's return type select a CallAdapter.Factory, and what happens when no registered factory accepts it?

level: middleimportance: should knowfreq 40%

basics

~20 s

Retrofit asks each CallAdapter.Factory in order, the ones you added first and its built-in ones last, and uses the first whose get() returns non-null. If none accepts the type, the method fails with an IllegalArgumentException naming the type and every factory tried.

open as a page

With Retrofit's RxJava 3 adapter, how do create(), createSynchronous() and createWithScheduler() differ, and why can subscribeOn have no effect?

level: middleimportance: should knowfreq 42%

basics

~20 s

RxJava3CallAdapterFactory.create() enqueues each call on OkHttp's threads, so subscribeOn does not change where it runs. createSynchronous() executes on the subscribing thread, and createWithScheduler() executes on the given scheduler. None of them moves results to the main thread; observeOn does.

open as a page

In Retrofit, why does a Kotlin enum passed as @Query send its constant name, and how does a stringConverter change that?

level: middleimportance: should knowfreq 30%

basics

~20 s

Retrofit renders @Query, @Path, @Header and @Field values through stringConverter. The Gson, Moshi and kotlinx factories don't implement it, so Retrofit falls back to toString() and sends ACTIVE. A custom Converter.Factory overriding stringConverter sends the API's spelling instead.

open as a page

With Retrofit, how do you parse the JSON error body of a failed call, such as a 402 card decline, into a typed object?

level: middleimportance: should knowfreq 60%

basics

~10 s

Ask the Retrofit instance for a converter with retrofit.responseBodyConverter(ApiError::class.java, emptyArray()) and run it on errorBody(). The first read consumes the error body, so parse it once and keep the result.

open as a page

In a Retrofit multipart method, how do @Part RequestBody, @Part MultipartBody.Part and @PartMap differ, and which one sends a filename?

level: middleimportance: should knowfreq 38%

basics

~20 s

A named @Part RequestBody gets a Content-Disposition with only a name; a MultipartBody.Part is sent exactly as built, so createFormData can add a filename; @PartMap adds one named part per map entry. Only MultipartBody.Part carries a filename.

open as a page

In Retrofit, what does @Streaming change when a service method downloads a large PDF as a ResponseBody, and what must the caller then do?

level: middleimportance: should knowfreq 33%

basics

~20 s

Without @Streaming, Retrofit reads a ResponseBody fully into memory before returning it; with @Streaming it returns the live network body. The caller must then read it off the main thread, copy it to a file in chunks, and close it.

open as a page

How do you configure OkHttp's CertificatePinner on the client a Retrofit app uses, and what does a Retrofit call see when no pin matches?

level: middleimportance: should knowfreq 48%

basics

~20 s

Build a CertificatePinner with add(host, "sha256/...") for a primary and a backup key, set it with certificatePinner() on the OkHttpClient given to Retrofit, and expect a mismatch to fail the call with SSLPeerUnverifiedException, an IOException, before any request is sent.

open as a page

In Retrofit, how do you call a URL the server returns at runtime, such as a pre-signed download link, and what constraints does @Url carry?

level: middleimportance: should knowfreq 45%

basics

~20 s

Declare the method annotation with no path and pass the URL as an @Url parameter. Retrofit resolves it against the baseUrl like a link, so an absolute URL replaces the host. @Url cannot be combined with @Path or a path in the annotation.

open as a page

With Retrofit, when do you send @FormUrlEncoded with @Field or @FieldMap instead of a @Body, and which combinations does Retrofit reject?

level: middleimportance: should knowfreq 45%

basics

~20 s

Use @FormUrlEncoded when the server expects application/x-www-form-urlencoded key=value pairs. @Field adds one pair, skipping null; @FieldMap adds many and rejects null. Retrofit refuses @Field without @FormUrlEncoded, @Body beside fields, and form encoding on a bodiless method.

open as a page

In Retrofit, when do you use @Headers, @Header and @HeaderMap on a service method, and how do the headers they add combine?

level: middleimportance: should knowfreq 60%

basics

~20 s

@Headers adds fixed headers to one method, @Header sets one header from an argument (null omits it) and @HeaderMap adds many from a map. Apart from Content-Type, same-named headers are all sent, never overwritten. Headers for every request belong in an OkHttp interceptor.

open as a page

When a coroutine awaiting a Retrofit suspend method is cancelled, how does that cancellation reach the HTTP request, and when does it not reach it?

level: seniorimportance: should knowfreq 33%

basics

~20 s

Retrofit awaits a suspend method's Call in a cancellable continuation that calls Call.cancel() when the coroutine is cancelled, which cancels the underlying OkHttp call. It does not reach a blocking Call.execute() inside withContext, nor an enqueued Call nobody cancels.

open as a page

When you write a Retrofit CallAdapter.Factory so suspend methods return a sealed ApiResult<T> instead of throwing, what type does the factory receive, and what must the adapter return?

level: seniorimportance: should knowfreq 38%

basics

~20 s

For suspend fun user(): ApiResult<User>, the factory is asked about Call<ApiResult<User>>. It must return a CallAdapter whose responseType() is User and whose adapt() returns a delegating Call<ApiResult<User>> that always reports a successful Response holding the wrapped outcome.

open as a page

How do you write a Retrofit Converter.Factory that unwraps a {"data": ...} API envelope by delegating to the JSON converter?

level: seniorimportance: should knowfreq 38%

basics

~10 s

Subclass Converter.Factory; in responseBodyConverter build the type Envelope<T>, get its converter from retrofit.nextResponseBodyConverter(this, ...), and return a converter that delegates and takes data. Register it before the JSON factory, which otherwise claims T first.

open as a page

With Retrofit and GsonConverterFactory, why can a missing JSON field leave a non-null Kotlin property null, and where does it fail?

level: seniorimportance: should knowfreq 52%

basics

~20 s

Gson's reflective adapter can create the object without running its Kotlin constructor, so a missing field keeps the JVM default: null even for a non-null String. Retrofit reports success, and the NullPointerException surfaces later, wherever the property is first used.

open as a page

A Retrofit suspend method declared with a nullable Receipt return type throws KotlinNullPointerException on a 204 No Content; why, and what should it declare instead?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Retrofit returns a null body for 204 and 205, and its suspend support cannot see the ? in Receipt?, so it treats the type as non-null and throws KotlinNullPointerException. Declare Response<Receipt> and check body(), or Unit when no body ever comes.

open as a page

With Retrofit, how do you upload a profile photo the user picked as a content:// Uri without reading the whole file into memory?

level: seniorimportance: should knowfreq 22%

basics

~20 s

Write a RequestBody whose writeTo() opens contentResolver.openInputStream(uri) and copies its source into the sink, report the size from OpenableColumns.SIZE or -1, and wrap it with createFormData. Reading the Uri into a byte array is the classic mistake.

open as a page

With Retrofit, how do you report upload progress for a multipart photo upload, and why might the progress bar fill twice?

level: seniorimportance: should knowfreq 26%

basics

~20 s

Wrap the photo's RequestBody in one whose writeTo counts bytes through an Okio ForwardingSink against contentLength(). writeTo can run more than once, for body-level logging or an OkHttp retransmission, so progress must restart on each pass.

open as a page

In a Retrofit app's OkHttpClient, where does a custom retry interceptor belong, and what must it do between attempts?

level: seniorimportance: should knowfreq 38%

basics

~20 s

A retry interceptor must be added with addInterceptor, because a network interceptor may call proceed() only once. Between attempts it closes the failed response, stops if the call was cancelled, backs off, and never retries a certificate-pin or hostname failure.

open as a page

showing 1–30 of 34