In a Retrofit app, how can one OkHttp interceptor apply per-endpoint behaviour, such as skipping the auth header, by reading Retrofit's Invocation tag?
answer
- Retrofit tags every request
- keyed by a class
- the Method carries annotations
- custom runtime annotation
- @Tag for per-call values
basics
~20 sRetrofit attaches an Invocation to every OkHttp request as a tag; an interceptor reads request.tag(Invocation::class.java), takes its method(), and checks a custom annotation on that service method to skip auth, change a timeout or opt into retries.
solid answer
~40 sRetrofit tags every OkHttp `Request` it builds with an `Invocation`, keyed by `Invocation.class`. In an interceptor, `chain.request().tag(Invocation::class.java)` returns it, and `method()` gives the `java.lang.reflect.Method` of the service method, with its annotations. So I declare a marker such as `@NoAuth` on the login method, and the auth interceptor skips the header when `method.isAnnotationPresent(NoAuth::class.java)`. The same pattern can set a longer read timeout for one slow endpoint with `chain.withReadTimeout()`, or mark which methods may be retried. `arguments()` gives the call's arguments, and since Retrofit 2.10.0 `service()` and `instance()` name the interface it was called on. For a value that varies per call rather than per method, a `@Tag` parameter puts an object into the request's tags. A request built outside Retrofit has no `Invocation`, so the lookup must handle null.
code
kotlin · 52 linesimport java.util.concurrent.TimeUnit
import okhttp3.Interceptor
import okhttp3.Response
import okhttp3.ResponseBody
import retrofit2.Invocation
import retrofit2.http.Body
import retrofit2.http.GET
import retrofit2.http.POST
@Target(AnnotationTarget.FUNCTION)
annotation class NoAuth
@Target(AnnotationTarget.FUNCTION)
annotation class SlowEndpoint(val readTimeoutSeconds: Int)
data class LoginRequest(val email: String, val password: String)
data class TokenPair(val accessToken: String, val refreshToken: String)
interface AccountApi {
@NoAuth
@POST("auth/login")
suspend fun login(@Body body: LoginRequest): TokenPair
@SlowEndpoint(readTimeoutSeconds = 60)
@GET("reports/annual")
suspend fun annualReport(): ResponseBody
}
interface TokenStore {
val accessToken: String?
}
class EndpointPolicyInterceptor(private val tokens: TokenStore) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
val method = request.tag(Invocation::class.java)?.method() // null if not from Retrofit
var next = chain
method?.getAnnotation(SlowEndpoint::class.java)?.let {
next = next.withReadTimeout(it.readTimeoutSeconds, TimeUnit.SECONDS)
}
val skipAuth = method?.isAnnotationPresent(NoAuth::class.java) == true
val token = tokens.accessToken
val outgoing = if (skipAuth || token == null) {
request
} else {
request.newBuilder().header("Authorization", "Bearer $token").build()
}
return next.proceed(outgoing)
}
}go deeper
Recall that Retrofit attaches an Invocation to each request, and that an interceptor can read which service method made the call.
Explain reading the Method from the Invocation tag, checking a custom runtime annotation, and how @Tag carries per-call values keyed by type.
Use the tag for per-endpoint auth, timeouts and retry opt-in safely: null handling for non-Retrofit requests, care with mutable arguments, and when a second client is cleaner.
Decide which per-endpoint policies the team expresses as annotations on service methods, so behaviour stays visible in the API declaration rather than scattered across interceptors.
## What Retrofit attaches to each request When a service method is called, Retrofit's request factory builds an OkHttp `Request` and adds a **tag** to it: an `Invocation`, stored under the key `Invocation.class`. A tag is an object carried with the request for the client's own use; it is never sent to the server. OkHttp keeps tags when a request is copied with `newBuilder()`, so later interceptors still see it. `retrofit2.Invocation` exposes: - `method()`: the `java.lang.reflect.Method` of the service-interface method that was called, with all its annotations. - `arguments()`: the arguments of this call, as an unmodifiable list. The list cannot change, but the objects in it may be mutable and are not necessarily safe to share between threads, as the class's own documentation warns. - `service()` and `instance()`: the service interface and the object it was invoked on. Added in Retrofit 2.10.0, they tell apart methods inherited from a shared parent interface. The `Invocation` tag itself dates from Retrofit 2.5.0. ## Reading it in an interceptor The pattern has three parts: 1. Declare a custom annotation for the behaviour, for example `@NoAuth` or `@SlowEndpoint(readTimeoutSeconds = 60)`. Kotlin annotation classes are retained at runtime by default; a Java annotation needs `@Retention(RUNTIME)` for reflection to see it. 2. Put it on the service methods that need the behaviour. 3. In the interceptor, read `request.tag(Invocation::class.java)?.method()` and check the annotation with `getAnnotation()` or `isAnnotationPresent()`. The lookup returns null for any request that Retrofit did not build, such as an image loader sharing the same `OkHttpClient`, so the interceptor must treat "no invocation" as the default case. ## What it is used for - **Skipping the auth header** on login, sign-up and token-refresh calls. - **Per-endpoint timeouts**: `chain.withReadTimeout(seconds, TimeUnit.SECONDS)` returns a chain with a different read timeout for this call only, so one slow report endpoint does not force a long timeout on everything. - **Retry opt-in**: a retry interceptor retries only methods marked as safe to repeat. - **Metrics and tracing**: naming each request after `service().simpleName` and `method().name` instead of a URL full of IDs. ## The Authenticator can read it too An OkHttp `Authenticator` receives the 401 response, and `response.request` still carries the tags of the request that was sent. That matters for login: a 401 from the login endpoint usually means wrong credentials, not an expired token. An Authenticator that finds `@NoAuth` on the invoked method can return null at once, so a mistyped password never triggers a token refresh. ## @Tag for values that change per call An annotation on the method is fixed for every call. When the value differs per call (a trace ID, a priority), declare a parameter annotated with `@Tag`, added in Retrofit 2.6.0: - The argument's type is the key, so the interceptor reads it with `request.tag(TraceId::class.java)`. - A null argument simply omits the tag. - Two `@Tag` parameters of the same type on one method are rejected: Retrofit throws `IllegalArgumentException` when it parses the method. - Primitive types are stored under their boxed class; that works correctly since Retrofit 2.12.0. ## Alternatives and why the tag usually wins | Approach | How | Drawback | |---|---|---| | second client and second `Retrofit` | derive a client with `newBuilder()` without the interceptor and build another `Retrofit` | unauthenticated endpoints need their own service interface, or callers must pick the right instance | | marker header | `@Headers("No-Auth: true")` on the method, which the interceptor reads and removes | a fake header in the API declaration, and forgetting to remove it sends it to the server | | `Invocation` tag | an annotation on the method, read through reflection | needs a null check for requests from outside Retrofit | The second-client approach is still the clean choice when the unauthenticated endpoints already form their own API, such as an auth service. For a handful of exceptions inside a larger interface, the tag keeps the policy next to the method it describes. ## Things to watch - Reflection on every request is cheap compared with network I/O, but keep the interceptor's work small. - Do not rely on argument objects staying unchanged after the call starts. - Keep the annotation's meaning narrow, such as "no auth", so the interceptor stays easy to read.
- Why does the interceptor need to handle a null Invocation?Only requests built by Retrofit carry the `Invocation` tag. If the same `OkHttpClient` also serves an image loader or a hand-built `Request`, `request.tag(Invocation::class.java)` returns null there, so the interceptor must fall back to its default behaviour rather than crash or skip auth.
- When would you use a @Tag parameter instead of an annotation read from the Invocation?When the value changes per call rather than per method, such as a trace ID or a request priority. A `@Tag` parameter stores the argument in the request's tags under its type, the interceptor reads it with `request.tag(Type::class.java)`, and a null argument leaves the tag out.
- Retrofit adds a header naming the service method that the interceptor can read.
- The Invocation tag is only present when you add a @Tag parameter.
- Every request through the client has an Invocation, so no null check is needed.
- Two @Tag parameters of the same type are both kept in a list.
- The only way to skip auth for login is a second OkHttpClient.
Assumes Retrofit 3.0.0; Invocation has been a request tag since 2.5.0, @Tag since 2.6.0, and service() and instance() since 2.10.0.