# Client basics

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

Construct Mountaya once, call the Map Studio, Data and Tile APIs by operation id, write, select fields, read event streams and every response.

`Mountaya` is the one type that calls the network. Build one per credential, hand it to everything that needs it, and close it when you are done.

## Construct a client

```dart
import 'package:mountaya_client/mountaya_client.dart';

const publishableKey = String.fromEnvironment('MOUNTAYA_PUBLISHABLE_KEY');
const sessionToken = String.fromEnvironment('MOUNTAYA_SESSION_TOKEN');

final mountaya = Mountaya(
  credential: .publishable(
    key: publishableKey,
    sessionToken: const .value(sessionToken),
  ),
  // Answers come in French where the API has French.
  language: 'fr',
);
await mountaya.close();
```

Whoever made the client closes it. In a Flutter app, the `State` that makes it closes it in `dispose`.

- `Mountaya({required Credential credential, String? language, BaseUrls? baseUrls, RetryPolicy retry = RetryPolicy.standard, Duration timeout = const Duration(seconds: 30), Client? httpClient, void Function(ResponseReport)? onResponse, int decodeOffIsolateAbove = 256 * 1024, RandomSource? random})`.
- `language` rides every request as `Accept-Language`. A client given none sends `*`, never the device's language: pass `Localizations.localeOf(context).toLanguageTag()` to answer in the reader's.
- Every request carries `X-Mountaya-Client: mountaya-dart/<version>`, the packages' version, which no call may set.
- `baseUrls: BaseUrls(rest:, tiles:, data:)` points each API at another origin (a staging deployment or a proxy); one left out stays Mountaya's, and an origin may carry a path prefix. Defaults: `https://api.mountaya.com`, `https://tiles.mountaya.com`, `https://data.mountaya.com`.
- A body larger than 256 KiB (`decodeOffIsolateAbove`) is decoded off the calling isolate, so a large GeoJSON answer costs a Flutter app no frames.
- `close()` ends the client's subscription to its session engine and its hold on the shared HTTP client. A client handed `httpClient:` leaves that client open. No redirect is ever followed, so no credential reaches a host the contract never named.
- A credential or language no request could carry is refused where the client is built, as `ConfigurationException`.

## Call the three APIs

Each method is named by the API's operation id, and hangs where the API files it:

```dart
import 'package:mountaya_client/data_schema.dart' as data_schema;
import 'package:mountaya_client/mountaya_client.dart';

const publishableKey = String.fromEnvironment('MOUNTAYA_PUBLISHABLE_KEY');
const sessionToken = String.fromEnvironment('MOUNTAYA_SESSION_TOKEN');

final mountaya = Mountaya(
  credential: .publishable(key: publishableKey, sessionToken: const .value(sessionToken)),
);

// Map Studio API, under studio and agent.
final itinerary = await mountaya.studio.itineraries.getItinerary(
  itinerary_id: '0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21',
);
print(itinerary.data.name);

// Data API, under data: the operation's own result.
final places = await mountaya.data.geocode(
  input: data_schema.GeocodeInput(query: 'Chamonix'),
);
print(places.places?.firstOrNull?.name);

// Tile API, under tiles.
final layers = await mountaya.tiles.getTileLayers();
print(layers.data.terrains.length);
await mountaya.close();
```

Path parameters are named as the API names them, `itinerary_id:`. A query is one `query:` value, and a body one `body:` value.

- Namespaces: `studio` (`activities`, `collab`, `collections`, `itineraries`, `layers`, `organizations`, `zones`) and `agent` (`runs`) on the Map Studio API; `tiles` on the Tile API; `data` on the Data API. `admin` appears once a server imports `package:mountaya_admin/mountaya_admin.dart` ([manage an organization](https://docs.mountaya.com/en/sdks/dart/admin.md)).
- A REST or Tile method takes its path parameters as required named parameters, then `query:` (a `…Query` value), `body:` (a `…Params` value), then `idempotencyKey:` and `ifMatch:` where the operation takes them, and `options:` (`RequestOptions`). It returns `Future<Response<D, M>>`. A Data API method takes `input:`, `select:` and `options:`, and returns its result type.
- An operation id is the method name verbatim, with no rename table; below contract 1.0 a minor may rename one.
- Every method returns a `Future`, but an event stream's and a listing walk's, which return a `Stream`.
- An operation this build prints no method for is called by its declaration: `mountaya.send(OperationDeclaration(...), decodeData:, decodeMetadata:)`, `mountaya.events(...)`, `mountaya.walk(...)` and `mountaya.query(DataOperation(...), input:, decodeResult:)`, each held to every rule a printed method is.

## Write

A body takes its fields as named parameters:

```dart
import 'package:mountaya_client/mountaya_client.dart';
import 'package:mountaya_client/rest_schema.dart' as rest_schema;

const publishableKey = String.fromEnvironment('MOUNTAYA_PUBLISHABLE_KEY');
const sessionToken = String.fromEnvironment('MOUNTAYA_SESSION_TOKEN');

final mountaya = Mountaya(
  credential: .publishable(key: publishableKey, sessionToken: const .value(sessionToken)),
);

final renamed = await mountaya.studio.itineraries.patchItinerary(
  itinerary_id: '0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21',
  body: rest_schema.ItineraryUpdateParams(name: 'Tour du Mont-Blanc, summer'),
);
print('${renamed.status} ${renamed.data.name}');
await mountaya.close();
```

A write acts as the member its token was minted for, as [Authentication in the SDK](https://docs.mountaya.com/en/sdks/dart/authentication.md#act-as-member) shows.

- A body takes its required fields as required named parameters and its optional ones as optional named parameters whose `null` is left out. A property optional and nullable in the contract has three states, so it is a setter on the built value, written in a cascade (`ItineraryUpdateParams(name: …)..description = null`): left unassigned it is not sent, assigned a value it replaces the stored one, assigned `null` it sends `null`, which clears it.
- A write to an itinerary, a collection or a zone takes a session token minted for `studio-embedded` naming the member, beside a key carrying the `studio-embedded` scope.
- A value its own `toJson` refuses (a `Url` with no scheme among them) fails the future the method answers, before any request; it is never thrown out of the call.
- Writes carry an `Idempotency-Key` on every attempt, and take `ifMatch:`: see [pagination and safe writes](https://docs.mountaya.com/en/sdks/dart/pagination.md#idempotency).

## Ask for fewer fields

A Data API call narrows its answer to the fields `select:` names, `true` selecting a field whole:

```dart
import 'package:mountaya_client/data_schema.dart' as data_schema;
import 'package:mountaya_client/mountaya_client.dart';

const publishableKey = String.fromEnvironment('MOUNTAYA_PUBLISHABLE_KEY');
const sessionToken = String.fromEnvironment('MOUNTAYA_SESSION_TOKEN');

final mountaya = Mountaya(
  credential: .publishable(key: publishableKey, sessionToken: const .value(sessionToken)),
);
final places = await mountaya.data.geocode(
  input: data_schema.GeocodeInput(query: 'Chamonix'),
  select: {
    'places': {'name': true, 'point': true},
  },
);
print(places.places?.firstOrNull?.point);
await mountaya.close();
```

The result type comes back whole: a field you did not select is `null`.

- `select:` is a `FieldSelection` (`Map<String, Object?>`) written as the contract writes one. A field outside the operation's tree throws `SelectionException` before any request, with the `path` it refused.
- The narrowed document is sent in the tree's order whatever order you wrote, so two selections of the same fields send the same bytes.
- Dart has no mapped types, so `select` narrows the document and not the result type: every field of the result is nullable, and a field not selected is `null`. Leave `select:` out for the full selection.
- The Data API answers a publishable key only beside a session token: a Data API call with no token is a `ConfigurationException` before it is sent.

## Stream events

A stream method answers an `EventStream`, a `Stream` of frames you read with `await for`:

```dart
import 'package:mountaya_client/mountaya_client.dart';

const publishableKey = String.fromEnvironment('MOUNTAYA_PUBLISHABLE_KEY');
const sessionToken = String.fromEnvironment('MOUNTAYA_SESSION_TOKEN');

final mountaya = Mountaya(
  credential: .publishable(key: publishableKey, sessionToken: const .value(sessionToken)),
);

// The itinerary's collaboration events: presence, locks and changes.
await for (final frame in mountaya.studio.collab.getItineraryEvents(
  itinerary_id: '0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21',
)) {
  print(frame.event.toJson()['type']);
}
await mountaya.close();
```

The stream reopens on its own. A `break` out of the loop closes the stream.

- An `EventStream<E>` is a single-subscription `Stream<EventFrame<E>>`, opened when listened to. Each `EventFrame` carries the decoded `event` and its `id`. Pausing a subscription pauses the socket; cancelling it, or a `break` out of `await for`, closes it.
- A stream reopens, waits and resumes from its last event on the contract's schedule; an agent run's stream (`mountaya.agent.runs.getAgentRunEvents`) ends on the run's `done`. An event this build cannot type arrives as the stream's unknown event (`rest_schema.UnknownCollabStreamEvent`, `rest_schema.UnknownAgentRunEvent`).
- Each event is a class of its own (`rest_schema.CollabPresenceJoinEvent`, `CollabLockAcquiredEvent`, `CollabItineraryChangedEvent`…), read with a `switch`. The base `CollabStreamEvent` declares no `type` getter, only `toJson()`: each concrete class has its `type`, so a loop over every event reads `toJson()['type']`.
- A stream is withdrawn by `options: RequestOptions(signal: signal)` too, and ends with the signal's reason.
- The collaboration streams (`mountaya.studio.collab.getItineraryEvents`, `getZoneEvents`, `getOrganizationEvents`) take `.readingAsUser(userId)` before you listen, naming the member a `.value(...)` token was minted for, so that member's own arrival is not read as the stream moving on. Only a collaboration stream takes it.
- The agent and collaboration streams act as a member: mint the token with `user_id`.

## Read the response

A REST or Tile call answers a `Response`: its `data`, the `status`, the headers and the request id.

```dart
import 'package:mountaya_client/mountaya_client.dart';

const publishableKey = String.fromEnvironment('MOUNTAYA_PUBLISHABLE_KEY');

final mountaya = Mountaya(credential: .publishable(key: publishableKey));
final itinerary = await mountaya.studio.itineraries.getItinerary(
  itinerary_id: '0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21',
);
print('${itinerary.status} ${itinerary.requestId} ${itinerary.data.etag}');
print(itinerary.header('Content-Language'));
await mountaya.close();
```

Quote `requestId` to support: it is the id the API recorded the request under.

- `Response<D, M>`: `data` (the envelope's `data`), `metadata` (its `extensions.metadata`: a `ListMetadata` for a listing), `status`, `headers` (names in lower case), `requestId` (`X-Request-Id`), and the getters `etag` and `location`. `header(name)` reads one header in any letter case, `null` where the answer sent none.
- A file answers a `BinaryResponse` (`getItineraryExport`), read as `application/octet-stream` where its answer names no type; it reads its headers the same way, `Content-Disposition` among them.
- Dates are UTC `DateTime`s, read by the contract's anchor (`parseTimestamp` publishes the reader). Distances are meters, durations seconds.

## Next steps

- [Errors and retries](https://docs.mountaya.com/en/sdks/dart/errors.md): What a failed call throws, and how it retries.
- [Pagination and safe writes](https://docs.mountaya.com/en/sdks/dart/pagination.md): Whole listings, idempotency keys, `ifMatch`.
