---
name: integrate-kotlin-client
description: >
  Use the generated Kotlin client in an Android or JVM application. Covers
  Ktor HttpClient and kotlinx.serialization dependencies, instantiation
  with HttpClient and baseUrl string, suspend operation functions in
  coroutine scope, @Serializable data classes, ApiResponse<T>, ApiException
  handling, and content negotiation setup. Load when importing or using a
  generated kotlin-mode client file.
type: framework
library: openapi-client-generator
library_version: "3.0.0"
requires:
  - generate-client
sources:
  - "bazo/openapi-client-generator:src/modes/kotlin/index.ts"
  - "bazo/openapi-client-generator:src/modes/kotlin/query.ts"
  - "bazo/openapi-client-generator:src/modes/kotlin/mutation.ts"
---

This skill builds on generate-client. Read it first for CLI usage.

# Integrate Kotlin Client

## Setup

Add dependencies to `build.gradle.kts`:

```kotlin
plugins {
    kotlin("plugin.serialization") version "2.1.0"
}

dependencies {
    implementation("io.ktor:ktor-client-core:3.1.0")
    implementation("io.ktor:ktor-client-cio:3.1.0")
    implementation("io.ktor:ktor-client-content-negotiation:3.1.0")
    implementation("io.ktor:ktor-serialization-kotlinx-json:3.1.0")
    implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.8.0")
}
```

Instantiate the client:

```kotlin
import io.ktor.client.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.serialization.kotlinx.json.*

val httpClient = HttpClient(CIO) {
    install(ContentNegotiation) {
        json()
    }
}

val api = ApiClient(client = httpClient, baseUrl = "https://api.example.com")
```

The constructor signature is:

```kotlin
class ApiClient(
    private val client: HttpClient,
    private val baseUrl: String
)
```

## Core Patterns

### Call a query operation

```kotlin
runBlocking {
    val result = api.listTasks(page = 1, limit = 10)
    println(result.data.items) // List<Task>
    println(result.status) // 200
}
```

All operations are `suspend` functions. Query parameters map to function parameters with defaults for optional ones.

### Call a mutation operation

```kotlin
runBlocking {
    val result = api.createTask(
        body = CreateTaskRequest(title = "Build feature", status = "todo")
    )
    println(result.data.id) // created task ID
}
```

Mutations take a `body` parameter typed as the corresponding `@Serializable` data class.

### Handle API errors

```kotlin
runBlocking {
    try {
        val result = api.getTask(taskId = "nonexistent")
    } catch (e: ApiException) {
        println("HTTP ${e.statusCode}: ${e.body}")
        println("URL: ${e.responseUrl}")
    }
}
```

Non-success responses throw `ApiException` with `statusCode`, `body`, `responseHeaders`, and `responseUrl`.

### Wire names that are not Kotlin identifiers

A spec is free to name a field `a.b`, `2fa`, `first name` or `@type`. None of those can be a Kotlin
property name, so the generator folds each into a legal one — camel-casing across the characters
Kotlin cannot spell, prefixing a leading digit — and `@SerialName` carries the original key, so
nothing changes on the wire:

```kotlin
@Serializable
data class Thing(
    @SerialName("a.b")
    val aB: String,
    @SerialName("2fa")
    val _2fa: String,
    @SerialName("first name")
    val firstName: String
)
```

Query, header and multipart names are emitted as literal strings, so they are never folded. A `$`
in any of them is escaped (`"\$amount"`), because a bare `$` opens a Kotlin string template — do
not "tidy" that backslash away, it is what keeps the wire name correct. Two field names that would
fold onto the SAME property (`a.b` and `a-b`) are a generation error, not a silent rename — rename
one of them in the spec.

Enum VALUES fold the same way (`Male`, `male` and `MALE` all give `MALE`), but they are NOT an
error: two enum values are not an ambiguity in the spec, so the duplicates are suffixed — `MALE`,
`MALE_`, `MALE__` — and every entry keeps its own `@SerialName`, so all three still round-trip. A
reserved-word entry takes the suffix inside its escape (`` `OBJECT_` ``). Suffixing is
order-dependent, so it is stable for a given spec but a value inserted ahead of a colliding one
shifts the names after it; refer to an entry through the generated identifier, never by assuming a
spelling.

## Union (`oneOf` / `anyOf`) schemas

A union whose every branch is an object schema becomes a `sealed class` with one nested case per
branch. Construct it by wrapping the branch value, and read it back with `when`:

```kotlin
runBlocking {
    val created = api.createNote(NoteBody.TextNoteCase(TextNote(text = "hello", wordCount = 1)))

    when (val body = api.getNote("note-1").data) {
        is NoteBody.TextNoteCase -> println(body.value.text)
        is NoteBody.LinkNoteCase -> println(body.value.url)
    }
}
```

On the wire the value is the **bare branch object** — the generated `KSerializer` writes the
branch's own JSON with no type discriminator added. Do not add `@JsonClassDiscriminator` or
register the sealed class in a `SerializersModule`; the generated serializer is already wired up
via `@Serializable(with = ...)`.

Branch selection when reading:

- **If the spec declares a `discriminator`**, that property picks the branch (honouring
  `discriminator.mapping`, falling back to the schema name for branches the mapping omits). A
  decode error under the chosen branch is raised as-is — a payload the spec says is branch A will
  never come back as branch B. This holds even when the union carried sibling `properties` and the
  branches were therefore emitted under generated `<Union>OneOfN` names: the mapping is resolved
  against the name the SPEC uses, not the name we emit.
- **Otherwise** each branch is tried in declaration order and the first that decodes wins. Note
  that under `ignoreUnknownKeys = true` a branch whose required fields are a subset of another's
  payload will match first, so declaration order matters for structurally overlapping branches.
  Add a `discriminator` to the spec if that is a risk.

OpenAPI 3.1's `kind: { type: string, const: "system" }` is read as a one-value enum, so such a
branch's discriminator is a real `enum class` (`ConstSystemEventKind.SYSTEM`) rather than an open
`String` — the wrong branch then fails to decode at all, and the union is unambiguous even without
the `when (tag)` fast path. Only a STRING `const` narrows this way: a boolean, integer or `null`
`const` stays a plain `Boolean`/`Int`/`JsonElement`, because a one-value enum of those cannot
decode the bytes they actually arrive as.

When nothing matches, the thrown `SerializationException` carries each branch's own failure in
`suppressedExceptions`, so a payload that is *almost* one branch tells you which field was wrong.

A union with any non-object branch (`oneOf: [string, integer]`, a `$ref` to an enum, an array
branch) stays a `typealias X = kotlinx.serialization.json.JsonElement` — inspect it with
`jsonPrimitive` / `jsonObject` as before.

### A schema with both `properties` and a `oneOf`

`{ type: object, properties: { album }, oneOf: [Song, Podcast] }` means "an object with `album`
that additionally satisfies one of the branches". The generator distributes the top-level
properties over every branch, so each `<Branch>Case` wraps a data class carrying them alongside
that branch's own fields:

```kotlin
data class SleeveOneOf1(val album: String, val track: String)
data class SleeveOneOf2(val album: String, val episode: String)
sealed class Sleeve {
    data class SleeveOneOf1Case(val value: SleeveOneOf1) : Sleeve()
    data class SleeveOneOf2Case(val value: SleeveOneOf2) : Sleeve()
}
```

Pick a case and fill in both halves; there is no separate slot for the shared properties. All five
modes distribute identically, so the parts on the wire are the same from each. (A `type: "null"`
branch of a nullable `anyOf` is left alone, and a schema that also carries `allOf` or `enum` is
not distributed — a schema carrying both already reads inconsistently (the type-annotation
resolvers test `allOf` before the union, the Swift and Kotlin declaration generators test the union
first), and distributing would only change which of those two pre-existing readings wins, in some
modes and not others. A sibling `allOf` is
instead MERGED: the top-level properties become one more `allOf` member, so they reach the
generated type rather than being dropped.)

Two consequences worth knowing. The branch types are **generated** (`<Union>OneOf1`, `<Union>OneOf2`),
so the original branch schemas stay declared but are no longer referenced by the union — and if a
spec of yours already used this shape, the case names change (`NamedUploadCase(NamedUpload)` →
`SleeveOneOf1Case(SleeveOneOf1)`). And because distribution reaches **response** schemas too, the
shared properties are now required in every branch: a response that omits one fails to decode where
it previously did not. That is what the spec asks for, but it is stricter than before.

## File uploads (multipart)

An operation whose request body is `multipart/form-data` takes a generated `@Serializable` request data class where each `format: binary` field is typed `FilePart(bytes, filename, contentType)`:

```kotlin
runBlocking {
    val body = UploadTaskAttachmentMultipartFormDataRequest(
        file = FilePart(File("invoice.pdf").readBytes(), "invoice.pdf", "application/pdf"),
        description = "Q3 invoice",
    )
    val result = api.uploadTaskAttachment(taskId = "42", body = body)
}
```

The client builds a Ktor `MultiPartFormDataContent` for you. Field encoding rules: scalar fields become one part; arrays of scalars become repeated parts under the same field name; objects and array-of-object fields become a single part carrying their JSON as a plain text field — no filename and no `Content-Type: application/json`, so a strict multipart parser reads it as a field whose value is the JSON text, exactly as the full and playwright clients send it; nullable fields that are `null` are omitted entirely. A multipart body parameter that is itself nullable (`body: SomeRequest? = null`) still sends a well-formed (empty) multipart body when omitted, not a bodyless request. A `oneOf`/`anyOf` body of all-object branches is a generated `sealed class` with one `<Branch>Case` per branch; the client matches on the case and sends that branch's own fields, which are the same parts the other four modes send for the same branch. A union body's branches must each have a field set of their own: if any branch has none — a primitive, an array, or an object with no declared properties — the whole body falls back to sending no parts at all, in every mode alike. The same fallback applies to a union the Kotlin generator cannot express as a sealed class (most reachably when a schema named `<UnionName>Serializer` already exists, but also when the union carries a sibling `enum` or is an `anyOf` of one type plus `null`), because Kotlin then has no sum type to dispatch on and the five modes only stay in step by all sending nothing. A `oneOf`/`anyOf` **urlencoded** body dispatches on the branch in exactly the same way, sending that branch's own fields as `k=v` pairs — an array field as repeated keys, an object-valued field as one JSON-encoded value — and it takes the same fallback, with the same explanatory comment, only when the branches cannot be described. A SINGLE-variant `anyOf` (`anyOf: [$ref Only]`) is not a union at all: it is simply its branch, typed and sent as that object in every mode. A schema carrying BOTH top-level `properties` and an `allOf` means "an object with those properties that ALSO satisfies every member of the allOf": the generator folds the properties in as one more `allOf` member, so they appear in the generated type and on the wire alongside the composed base's fields (they used to be dropped from the type while the form walk still emitted a part for them). The folded properties go LAST, so they WIN any name they share with the base: a sibling `count: { type: string }` over a base's `count: { type: integer }` types the field `string`. That has always been this mode's reading; the full and playwright clients now agree, where before they emitted an intersection no payload could satisfy. A `nullable` field is treated exactly like an omitted one: a `nullable` scalar sends no part when it is `null` even if the spec marks it required, and a `nullable`-item array (`List<String?>`) is `filterNotNull()`-ed rather than letting `encodeParam` append the literal text `null`.

Form-urlencoded bodies (`application/x-www-form-urlencoded`) build a Ktor `FormDataContent` from the request data class — arrays become repeated keys, an object field is JSON-encoded into a single value, and a `format: binary` field is a plain `String`, not a `FilePart` (a urlencoded body cannot carry a file); raw binary bodies (`application/octet-stream`, `image/*`, …) take a `FilePart` directly as the body and send its `bytes`:

```kotlin
runBlocking {
    val result = api.uploadRawBlob(body = FilePart(File("blob.bin").readBytes(), "blob.bin", "application/octet-stream"))
}
```

A `text/*` body whose schema is a `string` is a plain `String` parameter, sent verbatim under the
declared media type (`contentType(ContentType.parse("text/plain"))`), never JSON-encoded.

## Common Mistakes

### CRITICAL Missing Ktor or kotlinx.serialization dependencies

Wrong:

```kotlin
// build.gradle.kts — missing ktor and serialization deps
dependencies {
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.9.0")
}
```

Correct:

```kotlin
dependencies {
    implementation("io.ktor:ktor-client-core:3.1.0")
    implementation("io.ktor:ktor-client-cio:3.1.0")
    implementation("io.ktor:ktor-client-content-negotiation:3.1.0")
    implementation("io.ktor:ktor-serialization-kotlinx-json:3.1.0")
    implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.8.0")
}
```

The generated file imports `io.ktor.client.*` and `kotlinx.serialization.*`. Both Ktor client (with a chosen engine like CIO) and kotlinx-serialization-json must be in the project dependencies.

Source: src/modes/kotlin/index.ts generateImports

### HIGH Calling suspend functions outside coroutine scope

Wrong:

```kotlin
fun main() {
    val result = api.getTask(taskId = "123") // Compilation error
}
```

Correct:

```kotlin
suspend fun main() {
    val result = api.getTask(taskId = "123")
}
```

All generated operations are `suspend` functions. They must be called from a coroutine scope, a `suspend` function, or a builder like `runBlocking`.

Source: src/modes/kotlin/query.ts

### HIGH Editing the generated file directly

Wrong:

```kotlin
// Adding a custom method directly in ApiClient.kt
class ApiClient(private val client: HttpClient, private val baseUrl: String) {
    // ...generated code...
    suspend fun customMethod() { /* hand-written */ }
}
```

Correct:

```kotlin
// Extend via extension functions in a separate file
suspend fun ApiClient.customMethod() {
    /* hand-written */
}
```

The generated output is meant to be regenerated from the spec. Manual edits are overwritten on the next generation run. Use Kotlin extension functions in a separate file for custom methods.

Source: maintainer interview

See also: generate-client/SKILL.md — CLI usage for regenerating the client
