โ† Integrations

Mobile app ยท Kotlin

A daily nakshatra card in Kotlin: OkHttp, kotlinx.serialization, your backend

The app asks your server for today's reading for the user's Moon nakshatra; the server calls AstroNode with the key. Two Kotlin files - one on the JVM backend, one in the app - and the three errors Android developers usually hit on the way.

Updated

How this page was checked: The Kotlin code was not executed - there is no Kotlin toolchain on the build machine. The backend request was executed as a Java 17 java.net.http twin with the same URL, headers and body, against the in-memory API (both the 200 and the 400 below are from that run).

The backend call (any JVM server)

A BuildConfig field or a string resource is part of the APK and can be read with standard tools, so the key lives on your server. This object uses the JDK's own HttpClient, so it works unchanged in Ktor, Spring or http4k; sendAsync(...).await() keeps it non-blocking inside a coroutine.

kotlin
import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
import java.time.Duration
import kotlinx.coroutines.future.await

object AstroNode {
    private val base = System.getenv("ASTRONODE_BASE_URL") ?: "https://api.astronode.dev"
    private val key = System.getenv("ASTRONODE_API_KEY")
    private val http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build()

    suspend fun post(path: String, json: String): HttpResponse<String> {
        val req = HttpRequest.newBuilder(URI.create(base + path))
            .timeout(Duration.ofSeconds(15))
            .header("Authorization", "Bearer $key")
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(json))
            .build()
        return http.sendAsync(req, HttpResponse.BodyHandlers.ofString()).await()
    }
}

// Ktor route: the app posts {"nakshatra": "...", "date": "YYYY-MM-DD"}
fun Route.dailyNakshatra() = post("/daily-nakshatra") {
    val res = AstroNode.post("/v1/horoscope/nakshatra", call.receiveText())
    call.respondText(res.body(), ContentType.Application.Json, HttpStatusCode.fromValue(res.statusCode()))
}

The data that came back for {"nakshatra": "Uttara Ashadha", "date": "2026-12-01"}:

json
{
  "type": "nakshatra_horoscope",
  "version": "1.6.0",
  "language": "en",
  "verbosity": "standard",
  "nakshatra": "Uttara Ashadha",
  "date": "2026-12-01",
  "weekday": "Tuesday",
  "summary": "Lasting victories. Patient effort outperforms quick wins today.",
  "disclaimer": "Vedic astrology is offered here for cultural and informational purposes only. ..."
}

The app: OkHttp off the main thread

kotlin
import java.io.IOException
import java.util.concurrent.TimeUnit
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody

@Serializable
data class NakshatraDay(
    val nakshatra: String,
    val date: String,
    val weekday: String,
    val summary: String,
    val disclaimer: String,
)

@Serializable
private data class Envelope(val data: NakshatraDay)

private val json = Json { ignoreUnknownKeys = true }
private val client = OkHttpClient.Builder().callTimeout(20, TimeUnit.SECONDS).build()

suspend fun dailyForNakshatra(nakshatra: String, date: String): NakshatraDay =
    withContext(Dispatchers.IO) {
        val body = buildJsonObject {
            put("nakshatra", nakshatra)
            put("date", date)
        }.toString().toRequestBody("application/json".toMediaType())
        val request = Request.Builder()
            .url(BuildConfig.BACKEND_URL + "/daily-nakshatra")
            .post(body)
            .build()
        client.newCall(request).execute().use { res ->
            if (!res.isSuccessful) throw IOException("HTTP " + res.code)
            json.decodeFromString<Envelope>(res.body!!.string()).data
        }
    }

BuildConfig.BACKEND_URL is your server's address - fine to ship. Call dailyForNakshatra from a viewModelScope.launch { ... } and render summary plus the disclaimer; the disclaimer is part of the response for a reason, so keep it visible.

The mistakes that bite first

  • `Unknown key` from kotlinx.serialization. The JSON parser is strict by default and the envelope carries request_id, interpretation, meta, and data has type, version, verbosity - none of which are in the model. Without Json { ignoreUnknownKeys = true } the first response throws. It also keeps the app working when the API adds response fields - additive changes are listed on the changelog.
  • Reformatting the nakshatra name. The value must match the API's spelling exactly. Take it straight from the user's chart (/v1/charts/birth returns the Moon's nakshatra, e.g. "Uttara Ashadha") - "uttara ashadha" came back as 400 VALIDATION_ERROR listing the 27 accepted names.
  • `CLEARTEXT communication ... not permitted` in development. Android 9+ blocks plain http:// by default, so a dev backend at http://10.0.2.2:8080 fails. Allow cleartext for that host in a debug-only network security config rather than app-wide.
  • `NetworkOnMainThreadException`. OkHttp's execute() blocks; the withContext(Dispatchers.IO) wrapper is what keeps it off the main thread.

Questions

Which AstroNode endpoints does the Kotlin (Android) example call?
2 endpoints: Nakshatra Daily Horoscope (POST /v1/horoscope/nakshatra); Birth Chart (Kundli) (POST /v1/charts/birth).
Was the Kotlin (Android) code on this page actually run?
The Kotlin code was not executed - there is no Kotlin toolchain on the build machine. The backend request was executed as a Java 17 java.net.http twin with the same URL, headers and body, against the in-memory API (both the 200 and the 400 below are from that run).