# Client basics

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

Build a Mountaya client in Swift, call the Map Studio, Data and Tile APIs, write, select fields and read event streams.

`Mountaya` is the one type that calls the network. Every method is `async throws` and named after the API's operation.

## Construct a client

```swift
import Foundation
import MountayaClient

let environment = ProcessInfo.processInfo.environment
let mountaya = try Mountaya(
  credential: .publishable(
    key: environment["MOUNTAYA_PUBLISHABLE_KEY"] ?? "",
    sessionToken: .value(environment["MOUNTAYA_SESSION_TOKEN"] ?? "")),
  language: "fr")
```

Build one client and share it: it is `Sendable`. `language` asks the API to answer in French.

- `Mountaya.init(credential:language:baseUrls:retry:timeout:onResponse:exchange:clock:random:wallClock:)` throws `MountayaError` where the credential, the language or a base URL cannot be sent: each a `.configuration` before any request.
- `language` rides every request as `Accept-Language`. A client given none sends `Accept-Language: *`, never the device's language; pass `Locale.preferredLanguages.first` to answer in the reader's own.
- `baseUrls: BaseURLs(rest:tiles:data:)` points one or more APIs at another origin (a staging deployment, a proxy); one left out stays `BaseURLs.standard` (`https://api.mountaya.com`, `https://tiles.mountaya.com`, `https://data.mountaya.com`). An origin may carry a path prefix. A URL with no scheme is refused.
- Every request names the SDK in `X-Mountaya-Client: mountaya-swift/0.1.0`, which no call sets. A header value outside printable ASCII is refused before any request.
- `schemaVersion` is the contract tag the build was printed from (`v0.9.0`), and `modelDigest` the exact files.
- `retry:` and `timeout:` are on [errors and retries](https://docs.mountaya.com/en/sdks/swift/errors.md); `onResponse:` too. `exchange:`, `clock:`, `random:` and `wallClock:` are on [testing](https://docs.mountaya.com/en/sdks/swift/testing.md).

## Call the three APIs

An operation hangs where the API files it: `studio` and `agent` for the Map Studio API, `data` for the Data API, `tiles` for the Tile API. Its method is the operation's id:

```swift
import Foundation
import MountayaClient

let environment = ProcessInfo.processInfo.environment
let mountaya = try Mountaya(
  credential: .publishable(
    key: environment["MOUNTAYA_PUBLISHABLE_KEY"] ?? "",
    sessionToken: .value(environment["MOUNTAYA_SESSION_TOKEN"] ?? "")))

let itinerary = try await mountaya.studio.itineraries.getItinerary(
  itinerary_id: "0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21")
let places = try await mountaya.data.geocode(input: .init(query: "Chamonix"))
let layers = try await mountaya.tiles.getTileLayers()
print(itinerary.data.name)
print(places.places?.first?.name ?? "")
print(layers.data.terrains.first?.slug ?? "")
```

A path parameter is an argument by its name, the query is one `query:` value, and a body is one `body:` value.

- Method names are the contract's `operationId`, verbatim, in every SDK: `getItinerary`, `postItinerary`, `patchZone`. There is no rename table.
- Namespaces: `mountaya.studio.<resource>` (itineraries, zones, collections, activities, collab and the rest), `mountaya.agent.<resource>` (runs), `mountaya.data` (Data API operations directly: `search`, `geocode`, `reverseGeocode`, `directions`, `isochrones`, `matrix`, `pois`, `suggestions`, `itinerary`, `exportItinerary`, `analyzeGeometry`, `terrainProfile`, `terrainSamples`, `terrainGrid`), `mountaya.tiles` (`getTileLayers`, the specifications). The admin operations hang under `mountaya.admin` after `import MountayaAdmin` ([manage an organization](https://docs.mountaya.com/en/sdks/swift/admin.md)).
- Every method ends with `options: RequestOptions`. A REST method answers `Response<Value, Metadata>`; a Data API method answers its result type directly.
- An enum member is its words in lowerCamelCase (`RestSchema.TileLayerType.line`, `DataSchema.ActivitySlug.hikingAndTrail`), and every enum is open: a value this build has never seen decodes as itself.
- A web address the contract types `format: uri` is a `URI`: the text the answer sent, never rewritten; `url` reads it as Foundation does.
- An operation newer than this build is called by its declaration: `send(_:path:query:headers:body:idempotencyKey:ifMatch:options:)` with an `OperationDeclaration`, `walk(_:path:…)` for a listing, `query(_:input:select:options:)` with a `DataOperation`, and `events(_:path:query:options:)` for a stream. A call made this way follows every rule a generated method does.
- `TileTemplates` holds the routes a map fetches on its own, each a `URLTemplate` filled with `filled(with:)`.

## Write

A body takes its required fields as arguments and its optional ones in a trailing closure:

```swift
import Foundation
import MountayaClient

let environment = ProcessInfo.processInfo.environment
let mountaya = try Mountaya(
  credential: .publishable(
    key: environment["MOUNTAYA_PUBLISHABLE_KEY"] ?? "",
    sessionToken: .value(environment["MOUNTAYA_SESSION_TOKEN"] ?? "")))

let renamed = try await mountaya.studio.itineraries.patchItinerary(
  itinerary_id: "0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21",
  body: .init { $0.name = "Tour du Mont-Blanc, summer" })
print(renamed.data.name)
```

A field left `nil` is not sent. A nullable one set to `.some(nil)` sends `null`, which clears it: `$0.description = .some(nil)`.

- A property that is optional and nullable in the contract is a `T??`: `nil` leaves it out of the body, `.some(nil)` sends `null`, `.some(value)` sends the value.
- A write acts as a member: its session token is minted for `studio-embedded` and names the member ([act as a member](https://docs.mountaya.com/en/sdks/swift/authentication.md#act-as-member)). Under any other token it is refused `401`.
- Every write that takes an `Idempotency-Key` sends one, yours (`idempotencyKey:`) or one the client draws, on every attempt. `ifMatch:` sends the tag you read. Both are on [pagination and safe writes](https://docs.mountaya.com/en/sdks/swift/pagination.md).
- A form body (an import) is `.multipart([MultipartPart(name: "file", content: .file(bytes, filename: "tour.gpx"))])` through `send`, or the generated multipart body type.

## Ask for fewer fields

A Data API call can name the fields it wants, so the API sends less:

```swift
import Foundation
import MountayaClient

let environment = ProcessInfo.processInfo.environment
let mountaya = try Mountaya(
  credential: .publishable(
    key: environment["MOUNTAYA_PUBLISHABLE_KEY"] ?? "",
    sessionToken: .value(environment["MOUNTAYA_SESSION_TOKEN"] ?? "")))

let places = try await mountaya.data.geocode(
  input: .init(query: "Chamonix"),
  select: ["places": ["name": true, "point": true]])
print(places.places?.first?.name ?? "")
```

Fields you did not select come back `nil`.

- `select:` takes a `FieldSelection`, written as a dictionary literal: `true` selects a leaf, a nested dictionary selects inside an object. Left out, the operation's whole document is asked for.
- Swift has no mapped types, so `select` narrows the document and not the result type: the result type is returned whole, its fields optional, and a field the call did not select is `nil`.
- A selection naming a field the schema lacks throws `MountayaError.selection` before the request leaves; its `SelectionError` carries `path` and a message naming the fields that exist at that level.

## Stream events

A stream is an `EventStream` you read with `for try await`. It opens as you read its first frame:

```swift
import Foundation
import MountayaClient

let environment = ProcessInfo.processInfo.environment
let mountaya = try Mountaya(
  credential: .publishable(
    key: environment["MOUNTAYA_PUBLISHABLE_KEY"] ?? "",
    sessionToken: .value(environment["MOUNTAYA_SESSION_TOKEN"] ?? "")))

for try await frame in try mountaya.studio.collab.getItineraryEvents(
  itinerary_id: "0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21")
{
  switch frame.event {
  case .CollabPresenceJoinEvent(let join): print(join.type.rawValue, join.user_id)
  case .CollabItineraryChangedEvent(let change): print(change.type.rawValue)
  default: print(frame.event)
  }
}
```

The stream reconnects and resumes on its own until you stop reading it.

- A stream method throws but awaits nothing: `for try await frame in try …`. Each frame is an `EventFrame` with `id` and `event`, a case of the operation's event union. In Swift the union (`RestSchema.CollabStreamEvent`) has no `type` of its own: each case's payload carries `type`, so a reader switches on the case. `.unknown` holds an event type newer than this build.
- The collaboration stream takes a session token naming a member who can view the itinerary.
- The stream reopens, waits and resumes from the last event id on the contract's schedule, and ends on its terminal event. Cancelling the task reading it ends it.
- An editor stream (`mountaya.studio.collab.getItineraryEvents(itinerary_id:)`) is read as its member's user; `.reading(asUser:)` names one where the session token names none.
- A stream whose last record's id no header can carry ends with a `ConfigurationError` rather than reopening from it.
- `mountaya.events(_:path:query:options:)` opens a stream by its declaration, each frame carrying an `EventRecord`.

## Read the response

A REST call answers a `Response`: the `data`, the `status`, and the answer's request id and tag.

```swift
import Foundation
import MountayaClient

let environment = ProcessInfo.processInfo.environment
let mountaya = try Mountaya(
  credential: .publishable(
    key: environment["MOUNTAYA_PUBLISHABLE_KEY"] ?? "",
    sessionToken: .value(environment["MOUNTAYA_SESSION_TOKEN"] ?? "")))

let answer = try await mountaya.studio.itineraries.getItinerary(
  itinerary_id: "0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21")
print(answer.status, answer.requestId ?? "", answer.data.etag)
print(answer.header("Content-Language") ?? "")
```

Quote the `requestId` to support.

- The resource's own tag is `data.etag`; the answer's `ETag` header, where sent, is `etag` on the response.
- `Response<Value, Metadata>` carries `data`, `metadata` (a listing's `RestSchema.ListMetadata`, else the envelope's metadata), `status`, `requestId` (`X-Request-Id`), `location` (a created resource's path), `etag`, and `headers`, every header of the answer, read in any letter case with `header(_:)`.
- A Data API method answers its result type directly, with no envelope.
- `getItineraryExport` answers a `BinaryResponse`, the export's bytes.

## Next steps

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