Reference · SDKs
Dart & Flutter
Call your deployed queries through a generated Dart client, and use napalm_client for sessions, live streams, webhooks, uploads and search.
- 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.
Sessions, streams and uploads
The client library manages sessions, bookmarks, live streams, local sync and uploads.
Generated query bindings
Code generation turns each query file into typed calls and live subscriptions.
Generate into lib/napalm (napalm generate notes --lang dart -o lib/) and wire up swagger_dart_code_generator with build_runner.
dart pub add chopper json_annotationdart pub add --dev build_runner chopper_generator json_serializable swagger_dart_code_generatortargets: $default: builders: swagger_dart_code_generator: options: input_folder: "lib/napalm/" output_folder: "lib/napalm/client/"Run dart run build_runner build, then pass napalm.httpClient to the generated client so requests carry the active session and causal bookmark.
final napalm = NapalmClient(Uri.parse('https://<label>.napalmdata.com'), token: () => session);final db = Openapi.create( baseUrl: Uri.parse('https://<label>.napalmdata.com'), // Attaches the current bearer token and tracks Napalm-Bookmark across requests. httpClient: napalm.httpClient,); final found = await db.queryGetNotePost( body: GetNoteRequest(query: Queries.getNote, variables: GetNoteVariables(id: id)),);Sign-in#
SignIn (in napalm-client and napalm_client) wraps your project’s sign-in routes. Every method runs the PKCE flow for you by generating a verifier, sending its SHA-256 challenge, exchanging the authorization code at GET /sign-in/token and saving the resulting session in your chosen store. Pass the SignIn instance to NapalmClient so every request carries the active session, including typed calls made through napalm.fetch (or napalm.httpClient in Dart). When the user signs in, signs out or switches accounts, the client clears active live-query rows immediately and resubscribes as the new caller. (If you supply a custom token callback instead of SignIn, call napalm.restart() whenever the bearer token changes.)
final signIn = SignIn(Uri.parse('https://<label>.napalmdata.com'), store: keychain, passkeys: devicePasskeys);final napalm = NapalmClient(Uri.parse('https://<label>.napalmdata.com'), signIn: signIn); await signIn.sendCode(email); // sends a one-time code and magic linkawait signIn.withCode(email, typedCode); // exchanges the code and persists the session // OAuth redirect flow: launch the provider URL, then complete sign-in from the callback deep link.final back = Uri.parse('https://app.example.com/signed-in');await launchUrl(await signIn.providerUrl('builtin::oauth_google', redirectTo: back));await signIn.finish(openedAt);- Email and password
signUp,withPassword,verify,resendVerification,sendPasswordReset,resetPassword.- OAuth and OpenID Connect
- Call
providerUrlto start the redirect, thenfinishon the callback URL or deep link. - Magic links
- Call
sendCodeto email a one-time code and link, thenwithCodefor a typed code orfinishon the callback link. - Passkeys
addPasskeyandwithPasskeyin the client. For server-held sessions, callbeginon the server,passkeyCodeoraddPasskeyCodein the browser andfinishon the server.- Session state
session(),token,signOut(),signOutEverywhere(),pageToken()andonChange(TypeScript) orchanges(Dart).
metadata() returns the application name, branding and enabled providers so your sign-in UI can render the configured sign-in methods dynamically. Redirect and email flows (OAuth providers, magic links and verification emails) persist their PKCE verifier in the configured store. Call finish against that same store on return, or the exchange throws no_verifier. When the project requires email verification, signUp and addPasskey return null until the user confirms the email address.
Pass store to choose where the session persists: webStore() uses localStorage and syncs sign-in and sign-out across browser tabs, memoryStore() keeps the session in memory, and any custom { get, set } adapter works for Keychain or Keystore storage. A session’s token lasts an hour and renews automatically, while revoked or expired sessions read as signed out. In React, useSession(signIn) from napalm-client/react subscribes to session changes.
In browsers, TypeScript passkey flows call navigator.credentials directly. On React Native, pass a native WebAuthn adapter in the passkeys option, and in Dart pass a Passkeys adapter backed by your platform’s passkey plugin. Authentication failures throw NapalmError (NapalmException in Dart) with a stable error code: no_identity_found (invalid email or password), verification_required, user_already_registered, verification_failed (invalid or expired code) and passkey_declined.
Live query streams#
Every read-only query file also generates a typed live subscription helper. NapalmClient multiplexes all active subscriptions in your app onto a single SSE connection to POST /subscribe and applies incremental row patches as transactions commit. See Live queries for wire protocol details.
Multiplexed live queries
Active subscriptions share one SSE stream, apply diffs and clear on sign-out.
Offline device sync
Sync stores render cached rows offline and fetch only changes on reconnect.
In Dart and Flutter (--lang dart), live.dart exposes a typed Stream for each read query.
final napalm = NapalmClient(Uri.parse('https://<label>.napalmdata.com'), token: () => session); Live.getNote(napalm, GetNoteVariables(id: noteId)).listen((note) => render(note.rows));Rows on the device#
sync caches a deployed query’s rows in a local store on the device so views render immediately, even offline. The store records the rows’ bookmark, requests only the diff since that bookmark on reconnect and applies incoming patches by id (removing any cached row omitted from the current result IDs, or replacing the cache with a full result when the change log no longer covers that bookmark). When the signed-in user changes, the client clears every open sync store. Offline caches & reconnect sync builds an app on sync.
import 'package:napalm_client/napalm_client.dart'; import 'napalm/client/openapi.models.swagger.dart';import 'services/sqflite_sync_store.dart'; // Create one persistent sync store per query.final notesStore = SqfliteSyncStore(database, 'notes'); // Emits cached rows immediately, then applies live diffs. Cancel the subscription to close.final notes = napalm .sync( const LiveQuery.deployed('listNotes'), notesStore, decode: (row) => ListNotesDataItem.fromJson(row as Map<String, dynamic>), ) .listen((synced) => render(synced.rows, isStored: synced.isStored));SyncStore wraps your local database without adding a storage dependency to napalm_client. See the offline guide for a sqflite adapter, or use MemorySyncStore for in-memory caching. Each SyncedRows event sets isStored to true until the first live snapshot or diff arrives.
Queries that return scalars or objects without top-level id fields fail with ids_required and leave the local store unchanged. Concurrent sync calls for the same query and variables share one subscription and store.
Webhooks#
When you attach a webhook to a schema notify trigger, Napalm POSTs a signed payload whenever matching writes commit. Use readDelivery to verify the Napalm-Signature HMAC-SHA256 header over the raw request bytes in constant time and parse the typed delivery. The delivery carries a kind (ping, rows, gap or test), an id for idempotency, the event and a causal position.
final delivery = readDelivery(await request.read().expand((chunk) => chunk).toList(), request.headers, signingSecret);if (delivery.kind == 'ping') queue.add((event: delivery.event, position: delivery.position)); // In the background worker: advance the session bookmark before querying.napalm.reach(job.position);final found = await db.queryListUnsentOrdersPost(body: const ListUnsentOrdersRequest());Acknowledge the webhook promptly with a 2xx status and run heavy work in a background queue. Unacknowledged deliveries retry with exponential backoff. Pass delivery.position to napalm.reach(...) so subsequent worker reads observe at least the commit that triggered the webhook, even on a read replica.
The change log#
changes pages through a branch’s committed transactions via GET /changes, filtered by the caller’s read access policies. Each item either lists committed row mutations (type, op, id and fields) or reports a gap when requested history predates retention. Start from an RFC 3339 timestamp with since, then pass each page’s next bookmark back as after. Because delivery is at-least-once, persist the cursor only after processing each page.
await for (final page in napalm.changes(types: ['Order'], after: cursor, reach: delivery.position)) { await warehouse.apply(page.items); if (page.next case final next?) cursor = await saveCursor(next);}Pass reach to read through a target bookmark and stop (waiting briefly if the log has not caught up yet). Pairing reach with a ping webhook lets a worker tail the change log up to each ping’s position without polling. Omit reach in scheduled batch jobs to drain all available pages and return. To receive committed rows directly over HTTPS instead, bind a service key to the webhook.
File uploads#
Setting file_size in a mutation returns a one-time file_upload descriptor, and upload runs the rest of the upload lifecycle. Small files upload in one presigned PUT directly to object storage, while large files stream four parts in parallel, fetch part URLs on demand and retry failed transfers automatically. Once all bytes arrive, POST /uploads/complete verifies the byte size and header format and merges the new bookmark into the client session so immediate reads see the Ready file.
Interrupted multipart uploads resume from the last completed part. Each part uploads with a SHA-256 digest recorded by object storage, so calling upload again with the same file_upload descriptor and file transfers only missing parts. Keep the file_upload descriptor until verification succeeds.
final file = File(path);final added = await db.queryAddScanPost( body: AddScanRequest(variables: AddScanVariables(name: name, size: await file.length())),);final facts = await napalm.upload( added.body!.data.first.fileUpload, UploadSource(await file.length(), file.openRead), onProgress: (sent, total) => progress.value = sent / total,);Bytes that fail a schema format constraint throw the constraint’s message with code not_accepted, and the file_upload descriptor remains reusable until expiry. An UploadSource streams chunks on demand so large files never load into memory all at once.
Search and questions#
search calls POST /search to rank objects of one type by combined semantic and keyword relevance under the caller’s access rules. ask calls POST /ask, where a model synthesizes one EdgeQL statement for the question, runs it read-only as the caller and returns the rows alongside the statement. Both methods share the client’s session and causal bookmark.
final notes = await napalm.search('Note', 'plans for the launch', limit: 5, fields: ['title']);final found = await napalm.ask('Which of my notes mention the launch?');Streamed action answers#
streamAction calls an action and reads the handler’s answer as a stream. The call yields each frame as it arrives with its event name, raw text and parsed JSON. If the handler returns plain JSON instead of SSE, streamAction yields one answer frame. An error frame throws NapalmError (NapalmException in Dart), and an interrupted connection throws stream_ended. The stream’s bookmark merges into the client session so subsequent reads observe the handler’s writes.
// Read streamed SSE frames from the action handler. Cancelling the subscription aborts the request.await for (final frame in napalm.streamAction('summarizeNote', variables: {'note': noteId})) { if (frame.json case final String text) summary.write(text);}