Kotlin developers use OkHttp on the JVM (Android, server-side) and Ktor for multiplatform projects (Android + iOS shared code). Both work fine with the GoRest API. This guide covers OkHttp + kotlinx.serialization first, then shows the Ktor client equivalent.
Dependencies
Add OkHttp, kotlinx-serialization, and coroutines to your build. The serialization plugin is what generates the @Serializable glue code at compile time.
// build.gradle.kts
dependencies {
implementation("com.squareup.okhttp3:okhttp:4.12.0")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.3")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.8.1")
}
plugins {
kotlin("plugin.serialization") version "2.0.21"
}Setup
One OkHttpClient per process is enough; it has its own thread pool and connection pool. Read the token from env so it does not end up in source control.
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.HttpUrl.Companion.toHttpUrl
import kotlinx.serialization.json.Json
import kotlinx.coroutines.*
object GoRest {
const val API = "https://gorest.co.in/public/v3"
val token: String = System.getenv("GOREST_TOKEN")
?: error("Set GOREST_TOKEN")
val http = OkHttpClient.Builder()
.callTimeout(15, java.util.concurrent.TimeUnit.SECONDS)
.build()
val json = Json { ignoreUnknownKeys = true }
}Define a DTO
A @Serializable data class is the cleanest way to bind the JSON. Ids are UUID strings. Use one class for what you read and a separate one for what you send, so you never send server-assigned fields like id. A list answers { "data": [...], "meta": {...} }, so a small Page class holds both.
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class User(val id: String, val name: String, val email: String, val status: String)
@Serializable
data class NewUser(val name: String, val email: String) // status is "active" by default
@Serializable
data class Meta(
@SerialName("has_more") val hasMore: Boolean,
@SerialName("next_cursor") val nextCursor: String? = null,
)
@Serializable
data class Page<T>(val data: List<T>, val meta: Meta)GET with coroutines
Wrap blocking I/O in withContext(Dispatchers.IO) so the call works inside a coroutine. The .use { } block makes sure the response is closed.
// Pass the previous page's meta.nextCursor as `after` to get the next page.
suspend fun listUsers(status: String = "active", after: String? = null): Page<User> = withContext(Dispatchers.IO) {
val url = "${GoRest.API}/users".toHttpUrl().newBuilder()
.addQueryParameter("filter[status]", status)
.addQueryParameter("page[size]", "25")
.apply { if (after != null) addQueryParameter("page[after]", after) }
.build()
val req = Request.Builder()
.url(url)
.header("Authorization", "Bearer ${GoRest.token}")
.header("Accept", "application/json")
.build()
GoRest.http.newCall(req).execute().use { res ->
if (!res.isSuccessful) error("List -> ${res.code}")
GoRest.json.decodeFromString<Page<User>>(res.body!!.string())
}
}Create, update, delete
The three writes use post, patch, delete on the OkHttp builder (v3 has no put), and the token needs the users:write scope. Always include the Content-Type header on requests with a body.
private val jsonMedia = "application/json".toMediaType()
suspend fun createUser(input: NewUser): User = withContext(Dispatchers.IO) {
val payload = GoRest.json.encodeToString(input)
val req = Request.Builder()
.url("${GoRest.API}/users")
.header("Authorization", "Bearer ${GoRest.token}")
.header("Content-Type", "application/json")
.header("Accept", "application/json")
.post(payload.toRequestBody(jsonMedia))
.build()
GoRest.http.newCall(req).execute().use { res ->
if (res.code != 201) error("Create -> ${res.code}: ${res.body?.string()}")
GoRest.json.decodeFromString<User>(res.body!!.string())
}
}
suspend fun updateUserStatus(id: String, status: String) = withContext(Dispatchers.IO) {
val req = Request.Builder()
.url("${GoRest.API}/users/$id")
.header("Authorization", "Bearer ${GoRest.token}")
.header("Content-Type", "application/json")
.patch("""{"status":"$status"}""".toRequestBody(jsonMedia))
.build()
GoRest.http.newCall(req).execute().use { check(it.isSuccessful) }
}
suspend fun deleteUser(id: String) = withContext(Dispatchers.IO) {
val req = Request.Builder()
.url("${GoRest.API}/users/$id")
.header("Authorization", "Bearer ${GoRest.token}")
.delete()
.build()
GoRest.http.newCall(req).execute().use { check(it.code == 204) }
}Retry on rate limits
OkHttp interceptors run on every request. Add one to retry on 429 without the caller knowing, so your callers do not have to handle it:
class RateLimitInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
repeat(3) { attempt ->
val res = chain.proceed(chain.request())
if (res.code != 429) return res
val wait = res.header("Retry-After")?.toIntOrNull() ?: 1
res.close()
Thread.sleep(maxOf(wait, 1) * 1000L)
}
return chain.proceed(chain.request())
}
}
// wire it on the client:
val http = OkHttpClient.Builder()
.addInterceptor(RateLimitInterceptor())
.build()Same calls in Ktor
If you are writing multiplatform code (Android + iOS shared module, or KMP web), Ktor is the right client. The shape is similar, but the framework handles more of the setup: automatic content negotiation, authentication plugins, and engines for each platform.
// build.gradle.kts
// implementation("io.ktor:ktor-client-core:2.3.12")
// implementation("io.ktor:ktor-client-cio:2.3.12")
// implementation("io.ktor:ktor-client-content-negotiation:2.3.12")
// implementation("io.ktor:ktor-serialization-kotlinx-json:2.3.12")
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.engine.cio.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.client.plugins.defaultRequest
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.serialization.kotlinx.json.*
val client = HttpClient(CIO) {
defaultRequest {
header("Authorization", "Bearer ${System.getenv("GOREST_TOKEN")}")
header("Accept", "application/json")
}
install(ContentNegotiation) { json() }
}
suspend fun listUsers(): Page<User> =
client.get("https://gorest.co.in/public/v3/users") {
parameter("filter[status]", "active")
}.body()Tips
- Use
.use { }on every OkHttp response. Skipping it leaks connections. Json { ignoreUnknownKeys = true }does not fail when the API adds new fields, so your code keeps working. The default rejects unknown keys.- In Android, configure OkHttp with
Cacheto keep recent responses on disk; it greatly lowers your rate-limit usage on screens that read the same data often. - The Ktor
defaultRequestblock sets headers on every call without repeating them at each call site.
Keep going
JavaScript (Fetch API)
Browser-native fetch with async/await, bearer-token auth, error handling, and pagination.
Node.js
Server-side requests with global fetch and axios: retries, env-loaded tokens, streaming JSON.
Python (requests)
Calls with the requests library, JSON bodies, query filtering, and dataclass parsing.