# Client basics

> Canonical URL: https://docs.mountaya.com/en/sdks/kotlin/client/
> Last updated: 2026-11-27
> Rules for agents: https://docs.mountaya.com/llms.txt#rules-for-agents

Build the Kotlin client, call the Map Studio, Data and Tile APIs by their operation ids, write, select fields, stream events and read each answer.

`Mountaya` is the one type that calls the network. Every method suspends, and is named after the API's operation id.

## Construct a client

Build one client per credential and keep it for the app's lifetime:

```kotlin
import com.mountaya.client.Credential
import com.mountaya.client.Mountaya
import com.mountaya.client.SessionToken

fun frenchClient(publishableKey: String, sessionToken: String): Mountaya =
    Mountaya(
        Credential.Publishable(publishableKey, SessionToken.Value(sessionToken)),
        // Sent as Accept-Language on every request.
        language = "fr",
    )
```

Call `close()` when you are done with it.

- `Mountaya(credential, language, baseUrls, retry, timeout, onResponse, exchange, clock, random, dispatcher)`. Every parameter but `credential` has a default.
- `language` rides every request as `Accept-Language`. A client given none sends `*`, which asks for no language in particular, never the device's: pass the user's own language. A language no header can carry is refused with `ConfigurationException` where the client is built.
- `baseUrls = BaseUrls(rest = Url(…), tiles = Url(…), data = Url(…))` points one API at another origin, a staging deployment or a proxy. An API left out stays Mountaya's (`https://api.mountaya.com`, `https://tiles.mountaya.com`, `https://data.mountaya.com`), and an origin may carry a path prefix. `BaseUrls.standard` is Mountaya's three.
- Every request carries `X-Mountaya-Client: mountaya-kotlin/<version>`; an operation by declaration that names it is refused.
- Each answer is read and decoded on `dispatcher` (`Dispatchers.Default` by default), so a call from `viewModelScope` or a composable parses nothing on the main thread and resumes on the caller's dispatcher.
- `close()` lets the credential's session engine go, so the client no longer keeps it minting. Call it where the client's owner ends (a `ViewModel`'s `onCleared`, a server's shutdown).
- `SCHEMA_VERSION` (`v0.9.0`) and `MODEL_DIGEST`, in `com.mountaya.client.generated`, name the contract tag and files the client was printed from.

## Call the three APIs

The Map Studio API hangs under `studio` and `agent`, the Data API under `data`, and the Tile API under `tiles`:

```kotlin
import com.mountaya.client.Mountaya
import com.mountaya.client.generated.DataSchema

suspend fun tour(mountaya: Mountaya) {
    // Map Studio API: path parameters by name.
    val itinerary = mountaya.studio.itineraries.getItinerary("0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21")
    println(itinerary.data.name)

    // Data API: one input value per query.
    val places = mountaya.data.geocode(DataSchema.GeocodeInput(query = "Chamonix"))
    println(places.places?.firstOrNull()?.name)

    // Tile API: the layers your credential draws.
    val layers = mountaya.tiles.getTileLayers()
    println(layers.data.terrains.map { it.slug })
}
```

- An operation hangs where the contract files it: `client.studio.<resource>` (`itineraries`, `zones`, `collections`, `collab`, `activities`, `layers`, `organizations`), `client.agent.runs`, `client.data.<query>` (`directions`, `geocode`, `reverseGeocode`, `search`, `pois`, `isochrones`, `matrix`, `suggestions`, `analyzeGeometry`, `terrainProfile`, `terrainSamples`, `terrainGrid`, `exportItinerary`, `itinerary`), and `client.tiles.<operation>` directly. The admin unit's operations hang under `client.admin.<resource>` once `com.mountaya.admin.admin` is imported.
- Each method is the contract's `operationId`, verbatim: there is no rename table. Below contract 1.0 a minor release may rename an operation.
- A method takes its path parameters by name, its required query parameters after them, and its body as one `body` value; every optional query parameter, the `Idempotency-Key` (`idempotencyKey`) and the `If-Match` (`ifMatch`) are set in its trailing builder. Every method takes `options = RequestOptions(retry = …, timeout = …)`.
- An enum the contract declares is open: a value class that keeps a value a newer server sends, so a `when` over one ends in `else`. Each member is named by its words in UpperCamelCase, its type's name left off: `TileSchema.TileLayerType.Line`, `DataSchema.ActivitySlug.HikingAndTrail`.
- An operation newer than this build is called by its declaration: `client.send(OperationDeclaration(…), path, dataSerializer, metadataSerializer)`, `client.query(DataOperation(…), input, serializer)`, `client.events(declaration, path)` and `client.walk(declaration, path, serializer)`, each held to every rule a printed method is.

## Write

A body is built by a factory named after its type. Required fields are arguments; optional ones are set in the trailing builder:

```kotlin
import com.mountaya.client.Mountaya
import com.mountaya.client.generated.RestSchema

suspend fun rename(mountaya: Mountaya) {
    val renamed =
        mountaya.studio.itineraries.patchItinerary(
            "0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21",
            body = RestSchema.ItineraryUpdateParams { name = "Tour du Mont-Blanc, summer" },
        )
    println("${renamed.status} ${renamed.data.name}")
}
```

A field left unassigned is not sent and keeps its value; one assigned `null` is cleared. A write acts as a member: see [act as a member](https://docs.mountaya.com/en/sdks/kotlin/authentication.md#act-as-member).

- A property optional and nullable in the contract has three states in a builder: unassigned, it is not sent; assigned a value, it replaces the stored one; assigned `null`, it sends `null`, which clears it.
- Every write sends an `Idempotency-Key`, the one you set (`idempotencyKey = "…"`) or one the client draws, on every attempt, so a repeated write lands once. `ifMatch = etag` makes it conditional. See [pagination and safe writes](https://docs.mountaya.com/en/sdks/kotlin/pagination.md).
- A file upload's body is multipart: the printed methods build it, and an operation by declaration takes `RequestBody.Multipart(listOf(MultipartPart.Text(…), MultipartPart.File(name, bytes, fileName, mediaType)))`.
- A `Url` you send is held to a scheme: a web address with none in a body you build is refused before any request.

## Ask for fewer fields

A Data API call can narrow its answer to the fields you select:

```kotlin
import com.mountaya.client.FieldSelection
import com.mountaya.client.Mountaya
import com.mountaya.client.generated.DataSchema

suspend fun placeNames(mountaya: Mountaya) {
    val places =
        mountaya.data.geocode(
            DataSchema.GeocodeInput(query = "Chamonix"),
            select =
                FieldSelection {
                    field("places") {
                        field("name")
                        field("point")
                    }
                },
        )
    println(places.places?.map { it.name })
}
```

Fields you did not select come back `null`.

- Kotlin has no mapped types, so `select` narrows the document the API answers and not the result type (a divergence this SDK records in its specification, section 11): the result type is returned whole, every field nullable, and a field you did not request is `null`.
- A selection naming a field the schema lacks throws `SelectionException` before the request leaves; its `path` names where, and the message names the fields that exist at that level.
- Without `select`, the client asks for the operation's whole document.

## Stream events

A stream method answers an `EventStream`, a cold `Flow` of frames. Collect it to open the itinerary's collaboration events:

```kotlin
import com.mountaya.client.Mountaya

suspend fun watchEditors(mountaya: Mountaya) {
    mountaya.studio.collab.getItineraryEvents("0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21").collect { frame ->
        // Each event is a class of its type, such as CollabPresenceJoinEvent.
        println(frame.event::class.simpleName)
    }
}
```

The stream closes when its collector leaves.

- An `EventStream` reopens, waits and resumes from the last event id on the contract's schedule, and ends on the stream's terminal event. A `503` with `Retry-After` before any event reopens it after the wait.
- Cancelling the coroutine that collects ends the stream. A collector that stops early (`first`, `take`) closes it.
- An editor stream, `client.studio.collab.getItineraryEvents(id)`, is read as its member's user: apply `readingAsUser(userId)` before any other operator, so the member's own arrival is not read as the stream moving on. The user a minted session or an engine names wins.
- Each frame carries `id` and `event`, a typed event class (`RestSchema.CollabPresenceJoinEvent`, `RestSchema.CollabCursorEvent`…), each with its `type` (`RestSchema.CollabStreamEventType`); the base `RestSchema.CollabStreamEvent` carries none, so branch with `when`. An event type this build does not know arrives as `RestSchema.CollabStreamEvent.Unknown`, holding its JSON, so a `when` keeps an `else`.
- The agent's run stream reads the same way: `client.agent.runs.getAgentRunEvents(runId)`, ending on its `done` event (`RestSchema.AgentDoneEvent`).

## Read the response

A Map Studio API or Tile API method answers a `Response`:

```kotlin
import com.mountaya.client.Mountaya

suspend fun readAnswer(mountaya: Mountaya) {
    val answer = mountaya.studio.itineraries.getItinerary("0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21")
    println("${answer.status} ${answer.requestId} ${answer.data.etag}")
    println(answer.header("Content-Language"))
}
```

A Data API method answers its result type directly.

- `Response<T, M>` carries `data`, `metadata` (a listing's `RestSchema.ListMetadata` with its cursor, else the envelope's metadata), `status`, `requestId` (the answer's `X-Request-Id`), `location`, `etag`, and `headers`, every header the answer sent with its name in lowercase, which `header(name)` reads in any letter case.
- An export answers its bytes: `getItineraryExport(id, RestSchema.ExportFormat.Gpx)` carries `bytes`, `contentType`, `status` and `requestId`.
- A printed type holding a secret (a session's token, a webhook endpoint's signing secret, a share link's token) prints it as `<redacted>`; the value stays readable.
- Every timestamp the wire carries is a `kotlin.time.Instant`; `parseTimestamp(text)` reads one you hold as text by the same rule.

## Next steps

- [Errors and retries](https://docs.mountaya.com/en/sdks/kotlin/errors.md): The exception ladder, codes, retries and cancellation.
- [Pagination and safe writes](https://docs.mountaya.com/en/sdks/kotlin/pagination.md): Whole listings, idempotency keys, `ifMatch`.
