Claude API Kotlin Android App Integration Guide
Integrating the Claude API into a Kotlin Android app comes down to three decisions: how you call the API over HTTPS, how you keep your API key out of the compiled APK, and how you handle streaming responses on a mobile network. This guide walks through all three with working Kotlin code.
The short answer: never embed your Anthropic API key directly in an Android app. Any string in your APK can be extracted with basic reverse engineering tools, even if you obfuscate it. Instead, your app talks to a backend endpoint (your own server or a managed gateway like SubToAPI), and that backend holds the real credentials. The rest of this article shows the networking code for both the client side and the proxy side.
Why you can't call Claude directly from Android
Anthropic's API keys are meant for server-side use. If you ship one inside your app:
- It's extractable via
apktoolor a simple string dump, even with ProGuard/R8. - You lose any ability to rate-limit, log, or revoke access per user.
- You can't attribute usage or costs to individual app users or app versions.
- A single leaked key can run up unbounded usage charges.
The standard pattern is a thin backend layer between the app and Anthropic. That backend can be a Spring Boot or Node service you write yourself, or a hosted layer like SubToAPI that gives you per-application sub_live_... keys, usage metadata, and team seats without you building and maintaining auth, rate limiting, and logging from scratch.
Project setup in Kotlin
Add the networking dependencies in your module's build.gradle.kts:
dependencies {
implementation("com.squareup.retrofit2:retrofit:2.11.0")
implementation("com.squareup.retrofit2:converter-gson:2.11.0")
implementation("com.squareup.okhttp3:okhttp:4.12.0")
implementation("com.squareup.okhttp3:logging-interceptor:4.12.0")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.8.0")
}
Define the Retrofit interface. If you're proxying through SubToAPI, the endpoint shape matches the Messages API:
interface ClaudeApiService {
@Headers("Content-Type: application/json")
@POST("v1/messages")
suspend fun sendMessage(
@Header("Authorization") auth: String,
@Body request: MessageRequest
): MessageResponse
}
data class MessageRequest(
val model: String = "claude-sonnet-4-5",
val max_tokens: Int = 1024,
val messages: List<ChatMessage>
)
data class ChatMessage(val role: String, val content: String)
data class MessageResponse(
val id: String,
val content: List<ContentBlock>,
val usage: Usage
)
data class ContentBlock(val type: String, val text: String?)
data class Usage(val input_tokens: Int, val output_tokens: Int)
Build the Retrofit client:
object RetrofitClient {
private val logging = HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.BASIC
}
private val client = OkHttpClient.Builder()
.addInterceptor(logging)
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.build()
val api: ClaudeApiService = Retrofit.Builder()
.baseUrl("https://api.subtoapi.app/")
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(ClaudeApiService::class.java)
}
Calling it from a ViewModel using coroutines:
class ChatViewModel : ViewModel() {
private val apiKey = "Bearer ${BuildConfig.SUBTOAPI_KEY}"
fun sendPrompt(prompt: String, onResult: (String) -> Unit) {
viewModelScope.launch {
try {
val response = RetrofitClient.api.sendMessage(
apiKey,
MessageRequest(messages = listOf(ChatMessage("user", prompt)))
)
val text = response.content.firstOrNull { it.type == "text" }?.text ?: ""
onResult(text)
} catch (e: Exception) {
onResult("Error: ${e.message}")
}
}
}
}
Store the key in local.properties and inject it via BuildConfig rather than hardcoding it in source — this keeps secrets out of version control, though note it's still inside the compiled app. For a hosted gateway key this is far less risky than a raw Anthropic key, since you can scope, rotate, and revoke it from a dashboard without a new app release.
Handling streaming responses
Chat UIs feel much better with token-by-token streaming instead of waiting for the full response. Claude and gateways like SubToAPI support server-sent events for this. On Android, OkHttp can consume an SSE stream directly without a dedicated SSE library:
fun streamMessage(prompt: String, onToken: (String) -> Unit) {
val json = """
{"model":"claude-sonnet-4-5","max_tokens":1024,"stream":true,
"messages":[{"role":"user","content":"$prompt"}]}
""".trimIndent()
val request = Request.Builder()
.url("https://api.subtoapi.app/v1/messages")
.addHeader("Authorization", "Bearer ${BuildConfig.SUBTOAPI_KEY}")
.addHeader("Content-Type", "application/json")
.post(json.toRequestBody("application/json".toMediaType()))
.build()
OkHttpClient().newCall(request).execute().use { response ->
response.body?.source()?.let { source ->
while (!source.exhausted()) {
val line = source.readUtf8Line() ?: continue
if (line.startsWith("data:")) {
onToken(line.removePrefix("data:").trim())
}
}
}
}
}
Run this on Dispatchers.IO inside a coroutine, and emit each token through a Flow or StateFlow so your Compose or XML UI updates incrementally. Full event format details are in the streaming docs.
Architecture options for your backend
You have three realistic paths for the server side of this integration:
- Build your own proxy — a small Spring Boot, Express, or Ktor service that holds your Anthropic key, forwards requests, and adds auth. More control, more maintenance.
- Use a managed gateway — SubToAPI converts your existing Claude access into an HTTPS API with its own application keys (
sub_live_...), so your Android app never touches Anthropic's raw credentials. You get streaming, tool use, usage metadata per key, and team seats out of the box. - Hybrid — a lightweight auth layer in front of a gateway, useful if you need custom per-user rate limiting beyond what the gateway provides.
For most indie and small-team Android apps, option 2 is the fastest path to production: sign up, generate a key, point Retrofit at https://api.subtoapi.app/v1/messages, and ship. See the quickstart and Messages API reference for request/response details, and pricing if you're estimating costs across Solo, Team, and Scale plans.
Tool use from a mobile app
If your Android app needs Claude to call functions — looking up order status, querying a local database proxy, or triggering app actions — define tools in the request body and parse tool_use blocks from the response in your ContentBlock list, then execute the action client-side or server-side and send the result back as a follow-up message. The tool use docs cover the schema for defining tool parameters.
Questions
Can I call the Claude API directly from an Android app without a backend? Technically yes with a raw HTTP request, but your API key would be extractable from the APK. Use a backend proxy or gateway to keep credentials server-side.
What's the best way to handle streaming in Kotlin? Read the HTTP response body as a buffered source with OkHttp and parse data: lines as they arrive, pushing each chunk into a Flow for your UI layer to collect.
Do I need a separate Anthropic account if I use SubToAPI? No — SubToAPI turns your existing Claude access into an API with its own keys, so you manage billing and seats through SubToAPI's dashboard instead of juggling raw Anthropic credentials in your app.