Retrofit & REST Flashcards

DATA › Networking

How do you build a Retrofit instance, and what is required?
Use Retrofit.Builder(): set baseUrl(...), add at least one converter factory via addConverterFactory(...), optionally supply a custom OkHttpClient with client(...), then call build(). The baseUrl must end with a trailing slash.
What is the difference between a suspend function returning Response<T> versus returning the body type T directly?
Returning T gives the deserialized body but throws HttpException on non-2xx and IOException on network failure. Returning Response<T> never throws for HTTP errors; you inspect isSuccessful, code(), body(), and errorBody() yourself.
What do @Path, @Query, and @Body do?
@Path replaces a {placeholder} segment in the URL; @Query appends a ?key=value query parameter; @Body serializes an object as the request body using the configured converter.
How do you wire kotlinx.serialization into Retrofit?
Add the retrofit2-kotlinx-serialization-converter dependency and call addConverterFactory(Json.asConverterFactory("application/json".toMediaType())). The model classes must be annotated @Serializable.
Which annotations send form-encoded data versus multipart uploads?
Annotate the method @FormUrlEncoded and each parameter @Field("name") for form data. For file uploads use @Multipart on the method and @Part on each part.
Which HTTP methods are idempotent, and why does it matter for retries?
GET, PUT, DELETE, and HEAD (and PATCH by convention) are idempotent, so repeating them yields the same server state and they are safe to retry. POST is not idempotent, so blind retries can create duplicate resources.
How would you model API outcomes with a sealed Result<T>?
Define a sealed interface Result<out T> with Success(data: T) and Error(...) (optionally Loading). Wrap the suspend call in try/catch, map a 2xx Response to Success, and map non-2xx responses and exceptions to Error.
Which conditions signal a transient failure worth retrying?
408 Request Timeout, 429 Too Many Requests, and 5xx (500/502/503/504), plus IOExceptions like timeouts. 4xx client errors such as 400/401/404 are permanent, so retrying will not help.
What does a robust retry strategy look like for network calls?
Exponential backoff with jitter, a capped number of attempts, retrying only idempotent/transient failures, and honoring the Retry-After header on 429/503. Implement it via an OkHttp Interceptor or Flow.retryWhen.

Back to Retrofit & REST