# Server quickstart

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

Mint a session token and route a hike through the Data API from a Swift program on macOS or Linux.

One Swift program, on macOS or Linux: mint a session token with your secret key, list your itineraries, then route a hike from Chamonix to Argentière.

## Before you start

You need Swift 6.2.3 or newer, and two keys from **Organization → API keys** in the [Mountaya app](https://app.mountaya.com/api-keys): a secret key, and a publishable key with the `publishing` and `data` scopes.

```bash
export MOUNTAYA_SECRET_KEY="sk_your_secret_key"
export MOUNTAYA_PUBLISHABLE_KEY="pk_your_publishable_key"
```

## Install

```bash
mkdir trail-server && cd trail-server
swift package init --type executable
```

In `Package.swift`, add the package and link two products:

```swift
// swift-tools-version: 6.2
import PackageDescription

let package = Package(
  name: "trail-server",
  platforms: [.macOS(.v14)],
  dependencies: [
    .package(url: "https://github.com/mountaya/sdk-swift", from: "0.1.0")
  ],
  targets: [
    .executableTarget(
      name: "trail-server",
      dependencies: [
        .product(name: "MountayaClient", package: "sdk-swift"),
        .product(name: "MountayaAdmin", package: "sdk-swift"),
      ]
    )
  ]
)
```

## Mint a session token

Your secret key mints a short-lived session token for the publishable key. Put this in `Sources/trail-server/main.swift` and run `swift run`:

```swift
import Foundation
import MountayaAdmin
import MountayaClient

let environment = ProcessInfo.processInfo.environment
let server = try Mountaya(credential: .secret(key: environment["MOUNTAYA_SECRET_KEY"] ?? ""))
let session = try await server.admin.sessions.postSession(
  body: .init(publishable_key: environment["MOUNTAYA_PUBLISHABLE_KEY"] ?? "")
).data
print("The session expires at", session.expires_at)
```

## Call the Data API

Every other call sends the publishable key with that token. Replace `main.swift` with this:

```swift
import Foundation
import MountayaAdmin
import MountayaClient

let environment = ProcessInfo.processInfo.environment
let publishableKey = environment["MOUNTAYA_PUBLISHABLE_KEY"] ?? ""
let server = try Mountaya(credential: .secret(key: environment["MOUNTAYA_SECRET_KEY"] ?? ""))
let session = try await server.admin.sessions.postSession(
  body: .init(publishable_key: publishableKey)
).data
let mountaya = try Mountaya(
  credential: .publishable(key: publishableKey, sessionToken: .minted(session)))

// Map Studio API: your five most recently updated itineraries.
let itineraries = try await mountaya.studio.itineraries.getItineraries(
  query: .init {
    $0.sort = .updatedAtDescending
    $0.limit = 5
  })
for itinerary in itineraries.data {
  print(itinerary.name, "updated", itinerary.updated_at)
}

// Data API: a hike from Chamonix to Argentière.
let found = try await mountaya.data.directions(
  input: .init(activity: .hikingAndTrail, waypoints: [[6.8712, 45.9231], [6.9271, 45.9822]]),
  select: ["routes": ["distance": true, "duration": true, "summary": true]])
print(found.routes?.first?.summary ?? "")
```

```text
Docs Tour du Mont-Blanc updated 2026-11-09 10:53:23 +0000
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. It posts to your server's `/session` route, and your server answers the session it minted for the user your own sign-in names. Swift has no web server of its own, so your framework's route on `127.0.0.1:8787` calls this function:

```swift
import Foundation
import MountayaAdmin
import MountayaClient

// What the route sends back: a status, its headers and its body.
struct SessionAnswer {
  var status: Int
  var headers: [String: String] = [:]
  var body = Data()
}

func answerSession(method: String, path: String, signedInUser userId: String) async throws
  -> SessionAnswer
{
  guard path == "/session" else { return SessionAnswer(status: 404) }
  guard method == "POST" else { return SessionAnswer(status: 405, headers: ["Allow": "POST"]) }
  let environment = ProcessInfo.processInfo.environment
  let server = try Mountaya(credential: .secret(key: environment["MOUNTAYA_SECRET_KEY"] ?? ""))
  let session = try await server.admin.sessions.postSession(
    body: .init(publishable_key: environment["MOUNTAYA_PUBLISHABLE_KEY"] ?? "") {
      $0.user_id = userId
    })
  return SessionAnswer(
    status: 200,
    headers: ["Content-Type": "application/json", "Cache-Control": "no-store"],
    body: try JSONEncoder().encode(session.data))
}
```

The app decodes that body as a `RestSchema.Session` and hands it to a `SessionTokenEngine`.

- `postSession` is the admin unit's only session operation: `mountaya.admin.sessions.postSession(body: AdminSchema.SessionCreateParams)`. The body takes `publishable_key` as an argument and `user_id` and `surface` in its trailing closure. It answers `Response<RestSchema.Session, …>`: `token`, `expires_at` (a `Date`), `user_id`.
- `RestSchema.Session` is `Codable`: `JSONEncoder().encode(_:)` writes the object the API answered under `data`, and the app's `JSONDecoder().decode(RestSchema.Session.self, from:)` reads it back. The `token` prints `<redacted>`.
- A session minted without `user_id` reaches the Data API and published reads. A write acts as a member: mint it with `$0.surface = .studioEmbedded; $0.user_id = userId` beside a key carrying the `studio-embedded` scope. See [authentication in the SDK](https://docs.mountaya.com/en/sdks/swift/authentication.md#act-as-member).
- A secret key authenticates `postSession` and nothing else: every other call goes through a client built with the publishable key and a session token. The publishable key needs `publishing` for the itineraries and `data` for the Data API.
- `getItineraries(query:)` takes `.init { $0.sort = .updatedAtDescending; $0.limit = 5 }` (`RestSchema.GetItinerariesSort`: `.updatedAt`, `.updatedAtDescending`, `.createdAt`, `.createdAtDescending`, `.name`, `.nameDescending`). `select:` narrows the Data API's document; the result type stays whole, its unselected fields `nil`.
- The session route's contract, as every SDK's sample server keeps it: `POST /session` alone (`405` with `Allow: POST` on another method, `404` on another path), the user read from your own sign-in and never from the request, the session answered as JSON with `Cache-Control: no-store`.
- `SessionToken` cases: `.value(String)` (also a string literal), `.minted(RestSchema.Session)`, `.function(@Sendable () -> String?)` read per request, `.source(any SessionTokenSource)` (a `SessionTokenEngine`).
- `.secret(key:)` exists on macOS and Linux only. `Mountaya` is `Sendable`: build one per process and share it across requests.
- The Trail sample's session server, `Examples/Trail/Session` in the SDK repository (`mise run trail:session`), is a complete macOS server answering `POST /session` on `127.0.0.1:8787`.
- `directions` answers the routes found, each with `distance` (meters), `duration` (seconds), `summary` (a sentence in the client's language), `geometry` and `steps`. Positions are `[longitude, latitude]`.

## Next steps

- [Authentication in the SDK](https://docs.mountaya.com/en/sdks/swift/authentication.md): Keep tokens fresh in the app, and act as a member.
- [Client basics](https://docs.mountaya.com/en/sdks/swift/client.md): Every API, writes, field selection and streams.
