OpenAI from Kotlin / Android

SDK examples · All languages and providers · API reference

The official Java SDK com.openai:openai-java works from Kotlin: you set the base URL and pass the user's token as the API key. Your OpenAI key stays on the server; the app holds only a token that expires in one hour.

1. Set up the service

In the dashboard, create an app, add a service and store your OpenAI key in it:

openai  →  https://api.openai.com/v1

2. Get a token for the user

The app asks MyAppToken for a token with its app ID and your identifier for the user. The token lasts one hour; rate limits and analytics are tied to that user.

import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject

const val API = "https://api.myapptoken.com/api/v1"
const val APP_ID = "<app-id>"
private val http = OkHttpClient()

// Blocking: call it off the main thread, e.g. withContext(Dispatchers.IO).
fun sessionToken(userId: String): String {
    val body = JSONObject().put("app_id", APP_ID).put("user_id", userId).toString()
        .toRequestBody("application/json".toMediaType())
    val request = Request.Builder().url("$API/auth/simple").post(body).build()
    http.newCall(request).execute().use { res ->
        check(res.isSuccessful) { "auth failed: ${res.code}" }
        return JSONObject(res.body!!.string()).getString("access_token")
    }
}

Renew it before it expires with POST /auth/refresh (send the current, still-valid token as Authorization: Bearer); if that fails, request a new one. With Firebase App Check enabled, also send the App Check header on proxy calls.

3. Call OpenAI

import com.openai.client.okhttp.OpenAIOkHttpClient
import com.openai.models.chat.completions.ChatCompletionCreateParams

const val PROXY = "https://api.myapptoken.com/api/v1/proxy/<app-id>"

// Before: .apiKey("sk-…")
val client = OpenAIOkHttpClient.builder()
    .apiKey(jwt)
    .baseUrl("$PROXY/openai")
    .build()

val chat = client.chat().completions().create(
    ChatCompletionCreateParams.builder()
        .model("gpt-4o-mini")
        .addUserMessage("Hello")
        .build())

// After a token refresh:
val fresh = client.withOptions { it.apiKey(newJwt) }

These are blocking calls: run them off the main thread (for example withContext(Dispatchers.IO)) or use the SDK's async client.

Checked against the official OpenAI Java SDK 4.117: it sends /chat/completions under the base URL with Authorization: Bearer.

What changed

Direct to the providerThrough MyAppToken
Base URLhttps://api.openai.com/v1https://api.myapptoken.com/api/v1/proxy/<app-id>/openai
Credentialprovider key (sk-…)the user's token from /auth/simple

More: OpenAI guide · rate limits · async jobs.

Start free — no credit card; the Free plan covers 10,000 requests a month.