# Server quickstart

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

Mint a session token with your secret key, call the Data API, and hand tokens to your app, from a Dart program on the VM.

One Dart program on the VM: mint a session token, list your itineraries, and route a hike from Chamonix to Argentière.

## Before you start

You need Dart 3.10 or newer, the one Flutter carries included. Create a publishable key with the `publishing` and `data` scopes and a secret key, both under **Organization → API keys** in the [Mountaya app](https://app.mountaya.com/api-keys).

## Install

```bash
dart create -t console trail_server && cd trail_server
dart pub add mountaya_client mountaya_admin
export MOUNTAYA_PUBLISHABLE_KEY=pk_your_publishable_key
export MOUNTAYA_SECRET_KEY=sk_your_secret_key
```

## Mint a session token

Replace `bin/trail_server.dart` with this:

```dart
import 'dart:io';

import 'package:mountaya_admin/admin_schema.dart' as admin_schema;
import 'package:mountaya_admin/mountaya_admin.dart';
import 'package:mountaya_client/mountaya_client.dart';

Future<void> main() async {
  final environment = Platform.environment;
  final server = Mountaya(
    credential: SecretCredential(environment['MOUNTAYA_SECRET_KEY'] ?? ''),
  );

  // The secret key mints a token for the publishable key. It lasts five minutes.
  final minted = await server.admin.sessions.postSession(
    body: admin_schema.SessionCreateParams(
      publishable_key: environment['MOUNTAYA_PUBLISHABLE_KEY'] ?? '',
    ),
  );
  print('A session token, valid until ${minted.data.expires_at}.');
  await server.close();
}
```

Importing `mountaya_admin` adds `admin` to the client. Run it with `dart run`.

## Call the Data API

Every other call sends the publishable key with the token:

```dart
import 'dart:io';

import 'package:mountaya_admin/admin_schema.dart' as admin_schema;
import 'package:mountaya_admin/mountaya_admin.dart';
import 'package:mountaya_client/data_schema.dart' as data_schema;
import 'package:mountaya_client/mountaya_client.dart';
import 'package:mountaya_client/rest_schema.dart' as rest_schema;

Future<void> main() async {
  final environment = Platform.environment;
  final publishableKey = environment['MOUNTAYA_PUBLISHABLE_KEY'] ?? '';
  final server = Mountaya(
    credential: SecretCredential(environment['MOUNTAYA_SECRET_KEY'] ?? ''),
  );
  final minted = await server.admin.sessions.postSession(
    body: admin_schema.SessionCreateParams(publishable_key: publishableKey),
  );
  final mountaya = Mountaya(
    credential: .publishable(key: publishableKey, sessionToken: .minted(minted.data)),
  );

  // Map Studio API: your five most recently updated itineraries.
  final itineraries = await mountaya.studio.itineraries.getItineraries(
    query: rest_schema.GetItinerariesQuery(
      limit: 5,
      sort: rest_schema.GetItinerariesSort.updatedAtDescending,
    ),
  );
  for (final itinerary in itineraries.data) {
    print('${itinerary.name}, updated ${itinerary.updated_at}');
  }

  // Data API: a hike from Chamonix to Argentière.
  final found = await mountaya.data.directions(
    input: data_schema.DirectionsInput(
      activity: data_schema.ActivitySlug.hikingAndTrail,
      waypoints: [
        [6.8712, 45.9231],
        [6.9271, 45.9822],
      ],
    ),
    select: {
      'routes': {'distance': true, 'duration': true, 'summary': true},
    },
  );
  print(found.routes?.firstOrNull?.summary);

  await mountaya.close();
  await server.close();
}
```

```text
Docs Tour du Mont-Blanc, updated 2026-11-09 10:53:23.814Z
9.0 km, ~2h40m, +277m / -56m elevation, 67% path, 12% track, 8% road.
```

## Hand tokens to your app

An app never holds the secret key. Your server mints a token for its signed-in user on each request:

```dart
import 'dart:convert';
import 'dart:io';

import 'package:mountaya_admin/admin_schema.dart' as admin_schema;
import 'package:mountaya_admin/mountaya_admin.dart';
import 'package:mountaya_client/mountaya_client.dart';

// The member your own sign-in says made the request.
String userIdOf(HttpRequest request) =>
    throw UnimplementedError('Read the user from your own session.');

Future<void> main() async {
  final environment = Platform.environment;
  final publishableKey = environment['MOUNTAYA_PUBLISHABLE_KEY'] ?? '';
  final mountaya = Mountaya(
    credential: SecretCredential(environment['MOUNTAYA_SECRET_KEY'] ?? ''),
  );
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 8787);
  print('POST http://127.0.0.1:8787/session');
  await for (final request in server) {
    final response = request.response;
    if (request.uri.path != '/session') {
      response.statusCode = HttpStatus.notFound;
    } else if (request.method != 'POST') {
      response.statusCode = HttpStatus.methodNotAllowed;
    } else {
      final minted = await mountaya.admin.sessions.postSession(
        body: admin_schema.SessionCreateParams(
          publishable_key: publishableKey,
          user_id: userIdOf(request),
        ),
      );
      response
        ..headers.contentType = ContentType.json
        ..headers.set(HttpHeaders.cacheControlHeader, 'no-store')
        ..write(jsonEncode(minted.data.toJson()));
    }
    await response.close();
  }
}
```

The app keeps its token fresh by calling this route, as [Authentication in the SDK](https://docs.mountaya.com/en/sdks/dart/authentication.md#rotate) shows.

- `SecretCredential` exists on the Dart VM only: the core's conditional export leaves it out of every Flutter build, so an app has no symbol to hold a secret key. A Flutter app that names it does not compile.
- A secret key authenticates `postSession` and nothing else. The client refuses it on any other operation with `ConfigurationException` before the request leaves: keep one secret-key client that mints, and make every other call with a client built from `.publishable(key:, sessionToken:)`.
- `postSession` is `POST /v1/sessions`, under `admin.sessions` once `package:mountaya_admin/mountaya_admin.dart` is imported. Body `admin_schema.SessionCreateParams`: `publishable_key` (required), `user_id` (the member the token acts as), `surface` (`rest_schema.SessionSurface.api`, the default, or `studioEmbedded`). It answers a `rest_schema.Session`: `token`, `expires_at` (a UTC `DateTime`), `user_id`.
- A token minted without `user_id` reads only what the organization published: `getItineraries` lists published itineraries. Mint for a member to list drafts.
- `.minted(session)` holds one minted session: it is not refreshed. A long-running program hands the client a `SessionTokenEngine` instead ([authentication](https://docs.mountaya.com/en/sdks/dart/authentication.md#rotate)).
- `getItineraries` takes `query.limit` (1 to 100, default 50) and `query.sort`; its rows are `response.data`, a `List<rest_schema.Itinerary>`. Read every page with `walkGetItineraries` ([pagination](https://docs.mountaya.com/en/sdks/dart/pagination.md)).
- `mountaya.data.directions` resolves to the operation's own result (`DirectionsResult`), not a `Response`. `select` narrows the GraphQL document; Dart has no mapped types, so the result type comes back whole, every field nullable, and a field not selected is `null`.
- The route answers the `rest_schema.Session` JSON at the top level (`{"token": …, "expires_at": …, "user_id": …}`), which an app reads back with `rest_schema.Session.fromJson`. Never cache it: `Cache-Control: no-store`.
- Trail's session server, `examples/trail_session` (`mise run trail:session`), is this route minting without `user_id`, with `502` where a mint fails, naming no key or token. Trail's app reaches it at `http://localhost:8787/session` from the iOS simulator and `http://10.0.2.2:8787/session` from the Android emulator.
- `user_id` is the member every request made with the token acts as: read it from your own sign-in, never from the request's body or query. Leave it out for a token that reads only what is published.
- A refusal throws a class of the `MountayaException` ladder; see [errors](https://docs.mountaya.com/en/sdks/dart/errors.md).

## Next steps

- [Client basics](https://docs.mountaya.com/en/sdks/dart/client.md): Every namespace, writes and `select`.
- [Errors and retries](https://docs.mountaya.com/en/sdks/dart/errors.md): What a failed call throws.
- [Authentication in the SDK](https://docs.mountaya.com/en/sdks/dart/authentication.md): Tokens for members and apps.
