Skip to the page

Reference · SDKs

Swift

Generate a typed Swift client for your deployed queries with swift-openapi-generator, and call the rest of the Project API over standard HTTP.

In the schema
—

Installation and generation#

Run napalm generate from your project folder after you write your query files. The SDKs overview covers the generated files and how deployed queries are called.

Deployed query codegen

Generated clients call named deployed queries so production endpoints can disable passthrough.

The Swift client targets Apple’s swift-openapi-generator plugin (napalm generate notes --lang swift -o Sources/App).

Package.swift
.package(url: "https://github.com/apple/swift-openapi-generator", from: "1.0.0"),.package(url: "https://github.com/apple/swift-openapi-runtime", from: "1.0.0"),.package(url: "https://github.com/apple/swift-openapi-urlsession", from: "1.0.0"),
Sources/App/Notes.swift
import Foundationimport OpenAPIURLSession let db = Client(    serverURL: URL(string: "https://<label>.napalmdata.com")!,    transport: URLSessionTransport(),    middlewares: [BearerMiddleware(token: session)]) let response = try await db.getNote(body: .json(.init(    query: Queries.getNote,    variables: .init(id: noteId))))let rows = try response.ok.body.json.data

Causal bookmarks across replicas#

Every query response returns a Napalm-Bookmark header with the shard’s commit position. Echoing that bookmark on subsequent requests guarantees read-your-own-writes consistency across every engine and replica. napalm generate emits a Session transport helper alongside your generated client. Attach that helper once so every call sends the latest bookmark and records updated bookmarks automatically. See Causal bookmarks.

Bookmarks.swift
// napalm generate emits Session.swift alongside the client as an OpenAPI middleware.let napalm = Session(address: URL(string: "https://<label>.napalmdata.com")!)let db = Client(    serverURL: URL(string: "https://<label>.napalmdata.com")!,    transport: URLSessionTransport(),    middlewares: [BearerMiddleware(token: session), napalm]) _ = try await db.addNote(body: .json(.init(query: Queries.addNote, variables: .init(title: "Plan"))))// Subsequent reads observe the new note on every replica.let found = try await db.getNote(body: .json(.init(query: Queries.getNote, variables: .init(id: noteId)))) // Merge an external bookmark (such as a webhook's Napalm-Position) into the session.napalm.reach(position)

Sign-in#

Authenticate end users through your project’s sign-in routes. Redirect OAuth users to GET /sign-in/authorize with a SHA-256 PKCE challenge, or POST the challenge to an email/password, magic-link or WebAuthn passkey route. Every factor returns a one-time authorization code that you exchange with your PKCE verifier at GET /sign-in/token for a bearer session.

Exchange the authorization code · Swift
import Foundation let code = ProcessInfo.processInfo.environment["CODE"] ?? ""let verifier = ProcessInfo.processInfo.environment["VERIFIER"] ?? "" var request = URLRequest(url: URL(string: "https://notes.napalmdata.com/sign-in/token?code=\(code)&verifier=\(verifier)")!)let (data, _) = try await URLSession.shared.data(for: request)print(String(decoding: data, as: UTF8.self))

Live queries#

Open a multiplexed Server-Sent Events stream at POST /subscribe. Initial snapshots arrive in result frames and subsequent commits emit incremental diffs in patch frames, both filtered by the caller’s access policies. Persist the latest lsn token to resume monotonically on reconnect. See Live queries for frame schemas and dynamic subscription changes.

Open a live stream · Swift
import Foundation let session = ProcessInfo.processInfo.environment["SESSION"] ?? "" var request = URLRequest(url: URL(string: "https://notes.napalmdata.com/subscribe")!)request.httpMethod = "POST"request.setValue("Bearer \(session)", forHTTPHeaderField: "Authorization")request.setValue("application/json", forHTTPHeaderField: "Content-Type")request.httpBody = Data(    """    {      "subscriptions": [        {          "id": "notes",          "query": "select Note { title, done } filter .owner = global caller order by .title"        },        {          "id": "note",          "name": "getNote",          "variables": {            "id": "8f2c1e64-0b7a-4f4e-9d2b-3a6c5e1f7d90"          }        }      ]    }    """.utf8)let (bytes, _) = try await URLSession.shared.bytes(for: request)for try await line in bytes.lines {    print(line)}

Webhooks#

When you attach a webhook to a schema notify trigger, Napalm POSTs a signed payload whenever matching writes commit. Compute the HMAC-SHA256 hex digest of the raw request body with your signing secret and compare it in constant time against Napalm-Signature after stripping sha256=. Pass the Napalm-Position header to your session helper’s reach method so replica reads observe at least the commit that triggered the webhook. Acknowledge promptly with a 2xx status. Full payload schemas are in /openapi.yaml.

WebhookVerifier.swift
import CryptoKitimport Foundation func verifyWebhook(rawBody: Data, signatureHeader: String, secret: Data) -> Bool {    guard signatureHeader.hasPrefix("sha256="),          let sent = Data(hexEncoded: String(signatureHeader.dropFirst(7))) else {        return false    }    let key = SymmetricKey(data: secret)    return HMAC<SHA256>.isValidAuthenticationCode(sent, authenticating: rawBody, using: key)}

The change log#

GET /changes pages through committed transactions from the branch’s change log under the caller’s read access policies. Start from an RFC 3339 timestamp with since, then pass each page’s next bookmark back as after. Delivery is at-least-once, so persist your cursor after processing each page. See Notifications & webhooks for gap handling and webhook-driven tailing.

Read the change log · Swift
import Foundation let napalmKey = ProcessInfo.processInfo.environment["NAPALM_KEY"] ?? "" var request = URLRequest(url: URL(string: "https://notes.napalmdata.com/changes?since=2026-11-08T00:00:00Z&types=Note&limit=100")!)request.setValue("Bearer \(napalmKey)", forHTTPHeaderField: "Authorization")let (data, _) = try await URLSession.shared.data(for: request)print(String(decoding: data, as: UTF8.self))

File uploads#

A mutation that sets file_size returns a one-time file_upload descriptor containing a presigned PUT url and required headers. For multipart uploads, the descriptor returns part_size and part_count instead, and POST /uploads/parts issues presigned part URLs.

Create the file record · Swift
import Foundation let session = ProcessInfo.processInfo.environment["SESSION"] ?? "" var request = URLRequest(url: URL(string: "https://notes.napalmdata.com/query")!)request.httpMethod = "POST"request.setValue("Bearer \(session)", forHTTPHeaderField: "Authorization")request.setValue("application/json", forHTTPHeaderField: "Content-Type")request.httpBody = Data(    """    {      "query": "select (insert Scan { owner := global caller, file_name := <str>$name, file_size := <int64>$size }) { id, file_upload }",      "variables": {        "name": "lease.pdf",        "size": 2431604      }    }    """.utf8)let (data, _) = try await URLSession.shared.data(for: request)print(String(decoding: data, as: UTF8.self))

Upload the raw bytes to url with the returned headers, then call POST /uploads/complete to verify the stored byte length and magic-byte format and mark the record Ready. See File uploads for multipart transfers and error codes.

Complete and verify the upload · Swift
import Foundation let session = ProcessInfo.processInfo.environment["SESSION"] ?? "" var request = URLRequest(url: URL(string: "https://notes.napalmdata.com/uploads/complete")!)request.httpMethod = "POST"request.setValue("Bearer \(session)", forHTTPHeaderField: "Authorization")request.setValue("application/json", forHTTPHeaderField: "Content-Type")request.httpBody = Data(    """    {      "token": "up_Y4_FLCcYYXRfsAgv1nz3jN2…"    }    """.utf8)let (data, _) = try await URLSession.shared.data(for: request)print(String(decoding: data, as: UTF8.self))

Search and questions#

POST /search ranks objects of one type by combined semantic and keyword relevance. POST /ask synthesizes a single EdgeQL statement for a natural-language question and runs it read-only. Both routes execute under the caller’s access rules.

Search · Swift
import Foundation let session = ProcessInfo.processInfo.environment["SESSION"] ?? "" var request = URLRequest(url: URL(string: "https://notes.napalmdata.com/search")!)request.httpMethod = "POST"request.setValue("Bearer \(session)", forHTTPHeaderField: "Authorization")request.setValue("application/json", forHTTPHeaderField: "Content-Type")request.httpBody = Data(    """    {      "type": "Note",      "query": "launch timeline and milestones",      "limit": 5    }    """.utf8)let (data, _) = try await URLSession.shared.data(for: request)print(String(decoding: data, as: UTF8.self))
Ask · Swift
import Foundation let session = ProcessInfo.processInfo.environment["SESSION"] ?? "" var request = URLRequest(url: URL(string: "https://notes.napalmdata.com/ask")!)request.httpMethod = "POST"request.setValue("Bearer \(session)", forHTTPHeaderField: "Authorization")request.setValue("application/json", forHTTPHeaderField: "Content-Type")request.httpBody = Data(    """    {      "question": "Which of my notes mention the launch?"    }    """.utf8)let (data, _) = try await URLSession.shared.data(for: request)print(String(decoding: data, as: UTF8.self))

Type a word or two to search every docs page.