Retrofit & REST Interview Questions
DATA › Networking
How does Retrofit work?
What a strong answer covers: You define an interface with annotations like @GET("users/{id}") and parameters like @Path, @Query and @Body. Retrofit generates an implementation at runtime with a dynamic proxy that builds HTTP requests, runs them through OkHttp, and converts responses with a converter (kotlinx.serialization, Moshi, Gson). With suspend functions, calls run asynchronously and return the body directly or Response<T>.
How do you handle errors from Retrofit calls?
What a strong answer covers: A suspend function returning T throws HttpException for non-2xx responses and IOException for network problems; returning Response<T> lets you check isSuccessful, code() and errorBody() yourself. Wrap calls in the data layer and map them to a domain Result or sealed error type (no network, unauthorised, server error, parse error), and don't catch CancellationException.
Where should you create the Retrofit and OkHttp instances, and why does it matter?
What a strong answer covers: Create a single instance of each for the app (a singleton in DI), because OkHttpClient holds a connection pool, thread pool and cache that are meant to be shared. Creating clients per request wastes resources and breaks connection reuse and caching. Use newBuilder() to derive variants that share the same pool.
How would you add common headers, logging and authentication to every request?
What a strong answer covers: OkHttp interceptors: an application interceptor adds headers like Authorization or Accept-Language; HttpLoggingInterceptor logs requests in debug builds only, with sensitive headers redacted; an Authenticator handles 401 responses by refreshing the token and retrying. Configure timeouts too.
Your app calls an API that sometimes returns 200 with an error payload, sometimes 500, and sometimes malformed JSON. How would you design the network layer to deal with this cleanly?
What a strong answer covers: Use a call adapter or a wrapper function that converts every outcome into one sealed NetworkResult type: success, HTTP error with a parsed error body, API error from a 200 with an error envelope, network failure and serialisation failure. Parse error bodies with a separate model; configure the serialiser to ignore unknown keys and treat missing fields deliberately. Log failures with context, and add contract tests with MockWebServer so changes are caught early.