Skip to the page

Reference · SDKs

Swift

Call your deployed queries through the client swift-openapi-generator generates, and the rest of your project’s API over plain 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 and passthrough lockdown

napalm generate --deployed binds your ecosystem’s OpenAPI client to named /query/{name} routes so production endpoints can lock passthrough to keys or none.

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 answer returns a Napalm-Bookmark header marking the commit position on the shard. A read that sends the bookmark back never returns rows older than the caller’s own write, on any replica. napalm generate writes a session helper beside the client. Wire that helper into the client once so every call sends the latest bookmark and records updated bookmarks from responses. See Causal bookmarks.

Bookmarks.swift
// napalm generate writes Session.swift beside the client. Add the session to the client's middlewares.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"))))// The read includes the new note on any replica.let found = try await db.getNote(body: .json(.init(query: Queries.getNote, variables: .init(id: noteId)))) // napalm.reach joins a webhook's Napalm-Position into the session.napalm.reach(position)

Sign-in#

People sign in through your project’s sign-in routes. Start a provider’s sign-in at GET /sign-in/authorize with a PKCE challenge, or post the challenge to an email, code or passkey route. Every route ends in an authorization code. Trade the code and the verifier for a session token, and send that token as the bearer on every call.

Trade the code for a session · 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 stream at POST /subscribe and read it as Server-Sent Events. A result frame carries each query’s rows, and a patch frame carries the rows a commit changed. The caller’s access rules filter both frames. Keep each frame’s lsn to reconnect where the stream left off. See Live queries for every frame, adding and dropping subscriptions and reconnecting.

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=. Give the Napalm-Position header to the session’s reach so replica reads include the commit that fired 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 reads a branch’s committed rows from the change log one page at a time. The caller’s access rules filter the rows. Start from a time with since, then send each page’s next back as after. Delivery is at least once, so save the cursor after you handle a page, not before. See Notifications & webhooks for gaps and for tailing the log from a webhook’s position.

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 query that sets a file’s size returns a file_upload once. The descriptor holds a presigned PUT url and the headers to send with the PUT. For a large file, the descriptor holds a part_size and part_count instead, and part URLs come from POST /uploads/parts.

Set the file’s size · 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))

PUT the bytes to that url with those headers, then finish the upload. POST /uploads/complete checks the stored size, reads the format from the first bytes and marks the file Ready. See File uploads for parts.

Finish 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.