How to Consume a REST API on Android with Retrofit (Complete JWT Example)

Consuming a REST API on Android with Retrofit and JWT authentication

Quick answer: Add Retrofit, a JSON converter and OkHttp, describe the endpoints in an interface with suspend functions, and build one Retrofit instance with your base URL. Log in to get the JWT, store it, and add it to every request with an OkHttp interceptor (Authorization: Bearer <token>). Call the API from a ViewModel, check response.isSuccessful and handle 401, 422 and network errors separately.

Most Android apps talk to a backend: login, lists, forms, uploads. Retrofit is the standard library for this. It turns an HTTP API into a Kotlin interface, handles JSON conversion and works naturally with coroutines. This guide builds a complete example with JWT authentication, from dependencies to error handling.

Why use Retrofit on Android?

  • Endpoints become simple, typed Kotlin functions;
  • JSON is converted to data classes automatically;
  • It runs on top of OkHttp, so you get interceptors, timeouts, caching and logging;
  • It supports suspend functions, so no callbacks are needed;
  • It is mature, widely used and well documented.

1. Dependencies

In the app module's build.gradle.kts (check for newer versions when you set up the project):

dependencies {
    implementation("com.squareup.retrofit2:retrofit:2.11.0")
    implementation("com.squareup.retrofit2:converter-gson:2.11.0")
    implementation("com.squareup.okhttp3:logging-interceptor:4.12.0")
    implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:2.8.7")
}

And the internet permission in AndroidManifest.xml:

<uses-permission android:name="android.permission.INTERNET" />

Android blocks plain http:// by default, so your API should use HTTPS.

2. The data models

import com.google.gson.annotations.SerializedName

data class LoginRequest(
    val email: String,
    val password: String
)

data class LoginResponse(
    val token: String,
    @SerializedName("token_type") val tokenType: String,
    @SerializedName("expires_in") val expiresIn: Int
)

data class Post(
    val id: Int,
    val title: String
)

@SerializedName maps the API's snake_case fields to Kotlin's camelCase names. If you shrink the app with R8, keep these models (with @Keep or a ProGuard rule), or the field names will be renamed and parsing will fail in the release build.

3. The API interface

import retrofit2.Response
import retrofit2.http.Body
import retrofit2.http.GET
import retrofit2.http.POST

interface ApiService {

    @POST("auth/login")
    suspend fun login(@Body request: LoginRequest): Response<LoginResponse>

    @GET("posts")
    suspend fun getPosts(): Response<List<Post>>
}

Returning Response<T> gives you the status code and the error body, which you need to handle 401 or 422 properly. The token is not passed as a parameter: the interceptor adds it.

4. Storing the token

A simple token store with private SharedPreferences:

import android.content.Context

class TokenStore(context: Context) {

    private val prefs = context.getSharedPreferences("auth", Context.MODE_PRIVATE)

    var token: String?
        get() = prefs.getString("token", null)
        set(value) = prefs.edit().putString("token", value).apply()

    fun clear() = prefs.edit().clear().apply()
}

Never log tokens or keep them in static variables that outlive the session. For a deeper look at storage, see JWT refresh tokens on Android.

5. Sending the JWT automatically with an interceptor

import okhttp3.Interceptor
import okhttp3.Response

class AuthInterceptor(private val tokenStore: TokenStore) : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        val token = tokenStore.token
        val request = if (token != null) {
            chain.request().newBuilder()
                .header("Authorization", "Bearer $token")
                .build()
        } else {
            chain.request()
        }
        return chain.proceed(request)
    }
}

The header is only added when a token exists, so the login request goes out clean.

6. Building the Retrofit client

import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

object ApiClient {

    private const val BASE_URL = "https://api.example.com/v1/" // must end with /

    fun create(tokenStore: TokenStore): ApiService {
        val logging = HttpLoggingInterceptor().apply {
            level = if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY
                    else HttpLoggingInterceptor.Level.NONE
        }

        val client = OkHttpClient.Builder()
            .addInterceptor(AuthInterceptor(tokenStore))
            .addInterceptor(logging)
            .connectTimeout(15, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .build()

        return Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(ApiService::class.java)
    }
}

Create it once (in your Application class or with dependency injection) and reuse it: each OkHttp client has its own connection pool. Body logging only in debug builds, because it would print passwords and tokens. To use BuildConfig.DEBUG, enable buildFeatures { buildConfig = true } in Gradle.

7. Logging in from a ViewModel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import java.io.IOException

class LoginViewModel(
    private val api: ApiService,
    private val tokenStore: TokenStore
) : ViewModel() {

    private val _message = MutableStateFlow<String?>(null)
    val message: StateFlow<String?> = _message

    fun login(email: String, password: String) {
        viewModelScope.launch {
            try {
                val response = api.login(LoginRequest(email, password))
                if (response.isSuccessful) {
                    tokenStore.token = response.body()?.token
                    _message.value = "Logged in"
                } else {
                    _message.value = when (response.code()) {
                        401 -> "Wrong email or password."
                        422 -> "Check the fields and try again."
                        429 -> "Too many attempts. Wait a moment."
                        else -> "Server error (${response.code()})."
                    }
                }
            } catch (e: IOException) {
                _message.value = "No connection. Check your internet."
            }
        }
    }
}

Retrofit runs suspend calls off the main thread for you, so no Dispatchers.IO is needed here. The ViewModel survives screen rotation, and viewModelScope cancels the request if the screen is closed. See Kotlin coroutines and Flow on Android.

8. Handling errors correctly

There are three kinds of failure, and each needs different handling:

SituationHow it shows upWhat to do
HTTP error (401, 403, 422, 500...)response.isSuccessful is falseRead response.code() and response.errorBody()
No network, timeout, DNS failureIOExceptionShow a connection message and offer to retry
Unexpected JSONParsing exceptionUsually an API contract change; log it and fix the model

A 401 on an authenticated request means the token expired or is invalid: clear it and send the user to login, or refresh it automatically. Reading the API's JSON error message:

data class ApiError(val success: Boolean, val message: String?)

val error = response.errorBody()?.string()?.let {
    runCatching { Gson().fromJson(it, ApiError::class.java) }.getOrNull()
}
_message.value = error?.message ?: "Unexpected error."

This works best when the backend always returns errors in the same JSON shape. See error handling in a PHP API.

Best practices

  • One Retrofit/OkHttp instance for the whole app;
  • HTTPS only;
  • Short-lived access tokens with refresh tokens;
  • No sensitive data in logs or release builds;
  • Timeouts set explicitly;
  • Network calls in a repository, called from the ViewModel, never from the Activity directly.

The backend side

This client works with any REST API that returns JSON and accepts a Bearer token. If you build the backend in PHP, see how to build a REST API in plain PHP and JWT authentication in PHP.

Conclusion

With Retrofit, coroutines and one OkHttp interceptor, consuming an authenticated REST API on Android takes little code and stays easy to maintain: endpoints in an interface, the token added automatically, calls in the ViewModel and errors handled by type. The next step is renewing the token without forcing the user to log in again: automatic JWT refresh on Android.

Frequently asked questions

Should I use Call or suspend functions with Retrofit?

For Kotlin code, suspend functions. They are simpler, cancel automatically with the ViewModel and avoid nested callbacks.

Why does my request fail with "CLEARTEXT communication not permitted"?

Android blocks plain HTTP by default. Use HTTPS on the API.

Gson or Moshi or kotlinx.serialization?

All three work with Retrofit. Gson is the most common in examples; Moshi and kotlinx.serialization handle Kotlin null safety better.

Why does parsing fail only in the release build?

R8 renamed the model fields. Keep the models with @Keep or ProGuard rules, or use @SerializedName on every field.

How do I add the token to every request?

With an OkHttp interceptor that adds the Authorization: Bearer header, as shown above.

More in Android development