# Pagination and safe writes

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

Read a whole listing as an async sequence in Swift, repeat a write safely with an idempotency key, and write only if nothing changed.

A listing reads as one async sequence. A write can be repeated without landing twice, and can refuse to overwrite a change.

## Read a whole listing

Every listing has a walk beside it, `walk` before the operation's name. It asks for each page as you read its rows:

```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 itineraries = try mountaya.studio.itineraries.walkGetItineraries(
  query: .init { $0.sort = .updatedAtDescending }, pageSize: 50, maxPages: 10)
for try await itinerary in itineraries {
  print(itinerary.name)
}
```

Break out of the loop to stop asking. `PageWalk` walks any listing the same way, a call of your own included.

- A walk takes the method's own path parameters and query, `pageSize` (the operation's default, 50, unless you name another) and `maxPages` (the most pages it requests before it ends without an error). It answers a `PageWalk<Query, Row>`, an `AsyncSequence` of the listing's rows.
- A walk method is synchronous and `throws(MountayaError)`: it refuses a page size out of range (`PageWalk.maxPageSize`) where it is called, before any request. Each page is requested as the rows before it are read.
- `PageWalk(query:pageSize:maxPages:page:)` walks any paged call you hand it; `mountaya.walk(_:path:query:headers:pageSize:maxPages:options:)` walks a listing this build prints no method for, answering an `AsyncThrowingStream` of the rows you name.
- Cancelling the task reading a walk ends it. A failed page throws from the `for try await`, after the client's own retries.
- To read one page yourself, call the method (`getItineraries(query:)`) and read `metadata`, a `RestSchema.ListMetadata` with the cursor.

## Retry a write safely

Every write sends an `Idempotency-Key`, the same one on each attempt, so a repeated write lands once. Generate your own and keep it with the work, to send it again when you try again later:

```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"] ?? "")))

// Generated once, and stored with the itinerary you are about to create.
let key = UUID().uuidString
let body = RestSchema.ItineraryCreateParams(
  activity_id: "a1c4e7b2-3d59-4f08-8b6a-2e5c9d0f7134", is_private: true,
  name: "Tour du Mont-Blanc")

let created: Response<RestSchema.ItineraryWithDetails, [String: JSONValue]?>
do {
  created = try await mountaya.studio.itineraries.postItinerary(body: body, idempotencyKey: key)
} catch MountayaError.connection {
  // No answer: send the same write with the same key, and it lands once.
  created = try await mountaya.studio.itineraries.postItinerary(body: body, idempotencyKey: key)
}
print(created.status, created.data.name)
```

- Without `idempotencyKey:`, the client draws a key from the platform's cryptographic random source and sends it on every attempt of that call. With yours, a repeat from another process or launch is recognized too.
- A repeat while the first request is still running is a `409` coded `IDEMPOTENCY_KEY_IN_USE`, which the client asks again for as long as the retry policy's `waitBudget` lasts, then throws `.api` with `kind == .idempotencyKeyInUse`.
- A repeat whose first request made its write but whose answer cannot be given again is `kind == .idempotentAnswerUnavailable`: read the resource (at `unavailableAnswer?.location` when the write created one). Never send the write again under a new key: that makes it twice.
- An answer replayed from the key reaches `onResponse` with `isReplayed == true`.
- Only operations that declare the header take `idempotencyKey:`; the generated method has the argument exactly where the contract declares it.

## Write only if nothing changed

Send the tag you read the resource under. The write is refused if someone changed it since:

```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 id = "0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21"
let read = try await mountaya.studio.itineraries.getItinerary(itinerary_id: id)
do {
  _ = try await mountaya.studio.itineraries.patchItinerary(
    itinerary_id: id, body: .init { $0.name = "Tour du Mont-Blanc, summer" },
    ifMatch: read.data.etag)
} catch MountayaError.api(let failure) where failure.kind == .preconditionFailed {
  // Someone changed it since: read it again, and decide with what is there now.
  let current = try await mountaya.studio.itineraries.getItinerary(itinerary_id: id)
  print("Changed since you read it; it is now named", current.data.name)
}
```

- `ifMatch:` sends `If-Match`. A stale tag fails with `.api` whose `kind` is `.preconditionFailed` (`412`, the contract's `PreconditionFailedError`), carrying the resource's current tag in `etag`, and is never repeated.
- Send the resource's own tag, `data.etag`, from the read; a write's answer carries the new one in its `data.etag`.
- Only conditional operations take `ifMatch:`: those the contract declares, `OperationDeclaration.isConditional` for one called by its declaration.

## Next steps

- [Manage an organization](https://docs.mountaya.com/en/sdks/swift/admin.md): Members, keys, sessions and webhook endpoints.
- [Errors and retries](https://docs.mountaya.com/en/sdks/swift/errors.md): The error cases, codes, retries and cancellation.
