Skip to Content

Operation Reference

Every operation available through @foir/sdk/data, by model and by namespace. What is on your client is whatever GET /v1/manifest returns for your key — this page is the full vocabulary, not a promise that you hold all of it.

Check yours:

curl -H "x-api-key: foir_pub_..." https://api.foir.dev/v1/manifest | jq '.models | map_values(.ops | keys)'

Model operations

foir.<model>.<op>(args). An op that returns the record accepts include, and either pick or omit (never both), alongside its own arguments. An op marked opaque below returns something other than the model, so it takes its own arguments and nothing else.

OperationReturnsNotes
findUniquerecord or nullBy id or naturalKey
findManyconnectionRelay-style; see pagination
findMinerecord or nullSelf-scoped; needs a user bearer token
findManyMineconnectionSelf-scoped list on a user-owned collection; needs a user bearer token
searchopaqueFull-text search scoped to this model
aggregateopaqueRead scope; on a model with a field it can aggregate
createrecordCreate scope
updaterecordWrite scope
renamerecordWrite scope; changes the natural key the record is addressed by
updateManyopaqueWrite scope; bulk field update
duplicateopaqueWrite scope; copies a record into a new one
refreshopaqueWrite scope; drops the record’s cached answers so its next read resolves it again
revertToVersionopaqueWrite scope; on a versioned model. validateOnly checks the revert without writing
deleteopaqueDelete scope
publishVersionopaquePublish scope. Note the name: the op is publishVersion, not publish
unpublishopaquePublish scope
setMinerecordSelf-scoped write; needs a user bearer token
setOwneropaqueHands a record to another owner; only an operation’s dispatch token can run it
access / setVisibility / grantAccess / revokeAccessopaquePer-record access control. access with principal: 'me' needs only the read scope

Note: This is the vocabulary, not a guarantee. Which of these exist on a given model depends on the model’s configuration and your key’s scopes — GET /v1/manifest is the authority, and foir types generates from it. A publishable key against a read-only storefront project typically sees findUnique and findMany and nothing else.

findUnique

const page = await foir.page.findUnique({ naturalKey: 'homepage', locale: 'en-US' });
ArgumentType
idstringThe record id
naturalKeystringYour stable key
localestringLocale to resolve
previewbooleanInclude drafts — needs drafts:read
contextsResolveContextInputTargeting context dimensions, e.g. { device: 'MOBILE', market: 'us' }

Returns null when nothing matches. The type says so.

findMany

const posts = await foir.post.findMany({ first: 20, where: { status: { eq: 'published' } }, orderBy: { publishedAt: 'DESC' }, });

Adds first, last, after, before, where and orderBy to the arguments above. where and orderBy take the same shapes as the GraphQL API — see Filtering and Sorting, which are the authoritative reference for both.

orderBy is typed: the generated types close both the field and the direction, so a typo is a compile error rather than a 400. The keys are the ones the server will actually sort by, which is not the same as the model’s field list — see argument types. where is unknown and accepts anything.

Pagination

findMany returns a connection, not an array, so pagination stays reachable:

let cursor: string | null = null; do { const page = await foir.post.findMany({ first: 50, after: cursor ?? undefined }); for (const { node } of page.edges) process(node); cursor = page.pageInfo.hasNextPage ? page.pageInfo.endCursor : null; } while (cursor);

access

Returns who can reach one record: its visibility, its grants and every accessor. Pass principal: 'me' for your own access, which any reader of the record may ask for and which names nobody else. Everyone’s access, or one user’s by id, needs the write scope. It does not return the model, so include/omit/pick are not offered and its result type is used verbatim.

const mine = await foir.tilly_block.access({ id: 'a3pr8x0j10rigx8u6t1xthbr', principal: 'me' }); // ^? your own accessors and the public flag, with no grants

A typed call returns the root field’s value, so this is the access object itself rather than a data envelope.

Writes

Only present when your key holds the scope. Under a publishable key they are not on the type at all.

const { record: post } = await foir.post.create({ input: { naturalKey: 'hello', title: 'Hello', body: 'World' }, }); const { record: updated, replayed } = await foir.post.update({ where: { naturalKey: { eq: 'hello' } }, data: { title: { set: 'Hello again' } }, }); await foir.post.delete({ id: post._id });

create, update and rename return { record, replayed }. The record has the same complete-by-default shape as a read, so pick and omit apply to it. replayed is true when the call’s idempotencyKey was already used by an earlier attempt of the same write: that attempt’s record came back and nothing was written this time. See Retrying safely.

Namespace operations

foir.ns.<namespace>.<op>(args). Namespaces have no model behind them, so there is no include/omit and the result type is used verbatim.

The separate .ns accessor exists because the client has no runtime schema to work out whether foir.search means a model called search or the search namespace. The addressing carries it instead.

The list of namespaces is fixed by the platform rather than by your project: auth, events, files, marketplace, middleware, notes, notifications, operations, project, records, schedules, search, secrets, users. Their members are listed in full below.

The manifest is not this list. GET /v1/manifest shows the part of each namespace your key may reach and omits the rest, so a namespace can look far smaller than it is. A storefront key typically sees two members of users, and may see no files namespace at all. It is a projection of scopes, not of the key’s kind: a publishable key granted files:read is published files. The manifest answers what may I do, never what exists. This page is the second question.

Nor can you probe for the answer. A real op you lack the scope for and a name that was never real fail identically, because neither is in the description your types were generated from:

[foir] no namespace "files" in this credential's surface — re-run `foir types` [foir] the namespace "users" has no op "totallyMadeUp" for this credential — re-run `foir types`

Both are raised by the client before anything is sent. An op you cannot reach and an op that does not exist are the same fact from where you are standing, and that is deliberate.

Namespace results are unknown

A namespace op’s selection is published — that is how the client prints its document — but its argument and result types are not, so foir types emits args: Record<string, unknown>; result: unknown for each one and an awaited namespace call is unknown:

const hits = await foir.ns.search.searchRecords({ query: 'note' }); // hits: unknown — reading a property off it is a compile error

Narrow it yourself when you need the fields, with an assertion at the call site:

const coverage = (await foir.ns.search.embeddingCoverage({ modelKey: 'product' })) as Array<{ modelKey: string; totalRecords: number; embeddedRecords: number; pendingRecords: number; }>;

The assertion is the same unchecked claim foir.raw<T>() would have let you make, so nothing is lost by preferring the typed call — and the op name is checked, which raw does not do. Model ops are different: they carry real generated field types and need no assertion.

Where a namespace’s shapes are the platform’s rather than your project’s, @foir/sdk/data ships them so the assertion has something to point at instead of a hand-written interface. notes is the one that does today.

const hits = await foir.ns.search.searchRecords({ query: 'note' });

Returns a list, not a connection:

[ { "content": { "_id": "zsmjfj8xlgmxmc410gxuoaha", "_modelKey": "tilly_prompt_template", "_naturalKey": "prompt-qa_system", "content": "You are a helpful assistant…" } } ]
Operation
searchRecordsFull-text search across models
searchEmbeddingsVector search by embedding
searchByLocationGeospatial search
findNearbyRecordsRecords near a point
findSimilarRecordsRecords similar to a given one
embeddingsForRecordRead one record’s embeddings
embeddingCoverageHow much of a model is embedded
embeddingDigestsEmbedding content digests
writeEmbeddingsPush precomputed vectors — embeddings:write
generateEmbeddingQueue server-side generation for one record — embeddings:write
deleteEmbeddingsRemove a record’s embeddings — embeddings:write

The three writes are members of search like the reads, and whether you see them is a scope question rather than a question of the key’s kind: a publishable key granted embeddings:write is published all twelve. If the namespace looks read-only on your client, that is the projection of what your key holds, not the shape of the namespace.

The AI-search guides cover what these mean and when to use them — see AI Search.

auth

const me = await foir.ns.auth.whoami();

whoami describes the credential the request carried — its type, its effective authority, and how that authority was derived.

{ "credential": { "kind": "apiKey", "keyPrefix": "foir_pub_", "keyType": "PUBLISHABLE", "active": true }, "authority": { "effective": ["records:read", "search:read", "embeddings:read"], "branch": "anonymousReadOnlyBaseline" } }

The rest of the namespace is the user auth surface, and it is typed like everything else:

ReadsWrites
authConfig, authProviders, defaultAuthProviderlogin, register, requestOTP
currentUser, myProviderToken, signupContextrefreshToken, logout, joinWaitlist
whoami, myAuthorizedAppsrequestPasswordReset, updatePassword
mySessions, mySignInMethods, myFactorsdeleteMyAccount, leaveMembership, updateMyProfile, revokeAuthorizedApp
myAddresses, exportMyDataendMySession, signOutEverywhere, createPersonalAccessToken
myOrganizations, myOrganizationChoices, organizationMembersaddMyAddress, makeMyAddressPrimary, removeMyAddress
connectSignInMethod, disconnectSignInMethod
stepUp, beginFactorEnrollment
removeFactor, renameFactor, makeRecoveryCodes
registerOrganization, addOrganizationMember, removeOrganizationMember
signInWithProvider

Redeeming a reset link, bringing a code back, finishing a provider sign-in, keeping an added address and registering a factor are no operations here. resetPasswordAndSignIn in @foir/sdk/auth posts the link’s token to the reset’s own route, POST /v1/password-resets/redeem, signInWithOTP posts a code to its step’s route, POST /v1/sign-ins/{id}/code, and finishProviderSignIn, confirmProviderLink and resendProviderLinkCode post to the provider sign-in step’s routes, each with the step’s token. proveMyAddress posts the code an added address was sent to POST /v1/address-proofs/{id}, and completeFactorEnrollment what an authenticator made to POST /v1/factor-enrollments/{id}, each with the step’s token in the body. None sends a key.

Use @foir/sdk/auth for anything that is part of a session. It calls these same operations underneath and owns what they do not: storing the token, scheduling the refresh, handling the provider redirect, and the React context. Calling them directly is the right move for a single read on a server route, and the wrong one for a sign-in flow.

This namespace projects the project’s configuration as well as your key’s scopes. A project with password and OTP sign-in disabled publishes no login, register or requestOTP. A project configured that way was checked: its manifest carries none of the three, and its authConfig reports passwordEnabled: false. Ask before you branch:

const config = (await foir.ns.auth.authConfig()) as { passwordEnabled: boolean; otpEnabled: boolean; providers: Array<{ key: string; name: string; type: string }>; };
{ "otpEnabled": false, "passwordEnabled": false, "providers": [{ "key": "shopify", "name": "Shopify", "type": "OIDC" }] }

notifications

await foir.ns.notifications.markNotificationRead({ id: notificationId }); await foir.ns.notifications.markAllNotificationsRead();

Those two are ungated and are what a publishable key sees. The namespace has twelve members:

ReadsWrites
myNotifications, myUnreadCountsendNotification, sendBulkNotifications
notificationPreferences, webPushConfigregisterDeviceToken, unregisterDeviceToken, updateNotificationPreference
markNotificationRead, markAllNotificationsRead, setUserConsent

notes

Feedback against the records your pages render from. Four members:

ReadsWrites
myNotes, noteConfigwriteNote, createMyNote

myNotes asks notes:read and writeNote asks notes:create. myNotes refuses a request with no user session rather than returning an empty list, so pass bearerToken. writeNote takes a signed-in user and a visitor alike.

const mine = (await foir.ns.notes.myNotes({ first: 20 })) as FoirMyNotesResult; await foir.ns.notes.writeNote({ subjectType: 'record', subjectId: 'kx7p2m9q4wr8n3vt6ybc1zjd', subjectModelKey: 'article', body: 'My order arrived with a different courier than the page says.', } satisfies FoirWriteNoteArgs);

A visitor with no account

The same call, with no bearerToken. It is taken where the key gives notes:create to whoever comes through it and the project takes visitors’ notes (Notes settings → “Accept anonymous notes”):

const receipt = (await foir.ns.notes.writeNote({ subjectType: 'record', subjectId: 'kx7p2m9q4wr8n3vt6ybc1zjd', subjectModelKey: 'article', body: 'The size chart on this page contradicts the one in the FAQ.', contactEmail: 'visitor@example.com', pick: ['id', 'createdAt'], })) as FoirNoteReceipt;

Write-only. Nothing reads a visitor’s note back on the public plane. A visitor is answered with the note’s id and createdAt, and asking for more is refused before anything is written, which is why the call picks those two. Nothing on the public plane takes the id to read the note, so do not store it expecting a read that takes it.

createMyNote is the older name of writeNote for a signed-in user. It is the same create and still answers, until the callers that name it have moved.

contactEmail is optional and never verified — nothing is sent to it to confirm it, and the platform does not treat it as proof of who wrote the note.

A visitor’s note is refused, with the reason, when the project has not opted in. Rate limits and quotas are per project and per IP, and the user’s toggle is a kill switch: turning it off refuses new submissions immediately.

noteConfig answers exactly the callers writeNote takes: a signed-in user, and a visitor on a project that takes their notes. Its signedIn says which one is asking, and anonymousAccepted whether the project takes visitors’ notes. The feedback widget reads it and takes a visitor’s note through this lane, so you only send a writeNote yourself for a form of your own.

Unlike every other namespace, the shapes here are shipped rather than asserted by hand. FoirUserNote, FoirMyNotesArgs, FoirMyNotesResult, FoirNoteConfig, FoirNoteReceipt, FoirWriteNoteArgs, FoirCreateMyNoteArgs and FoirNoteSubjectType are exported from @foir/sdk/data — the note shape is the platform’s and identical in every project, so writing it out per consumer only creates chances to get a field name wrong.

You do not have to work out subjectId yourself: the client can tell you which record the page fetched. See Subjects & Annotations, and Notes & Comments for the role a write needs.

users

const invitation = await foir.ns.users.validateInvitation({ token }); await foir.ns.users.acceptInvitation({ token, password });

Those two are the members a publishable key sees. The namespace holds:

ReadsWrites
users, usercreateUser, updateUser, suspendUser, deleteUser, mergeUsers
invitations, invitationsetUserFirstPassword, provisionOrganization, scheduleOrganizationDeletion
validateInvitationcreateInvitation, revokeInvitation, resendInvitation, acceptInvitation
joinRequestsapproveJoinRequest, declineJoinRequest

The account-lifecycle writes are on the SDK deliberately: someone who can invite a user over the data client but has to change transport to create one is a split the platform removed on purpose. The audience boundary is the users:read.all / users:write.all scope pair, not the transport.

files

Gated on the files:* scopes, per scope rather than per kind of key: a key with files:read is published the reads, and only a key holding the writes sees those. Its members are fixed by the platform:

ReadsWrites
file, filesuploadFile, updateFile, setFileVisibility, deleteFile, undeleteFile, purgeFile
const upload = (await foir.ns.files.uploadFile({ filename: 'hero.jpg', mimeType: 'image/jpeg', size: 482910, })) as { uploadId: string; uploadUrl: string; landed: { token: string; endpoint: string } };

See Files API for the upload flow these belong to.

schedules

schedules, schedule, triggerSchedule, createSchedule, updateSchedule, deleteSchedule, pauseSchedule, resumeSchedule.

secrets

getSecret, listSecrets, putSecret, deleteSecret, rotateSecret, restoreSecret.

project

Reads and writes about the project itself rather than about a record:

ReadsWrites
designTokens, locales, resolvedLocaleupdateDesignTokens, publishDesignTokens (designtokens:write)
models, projectSchemas (schemas:read)createSignInProvider, updateSignInProvider, deleteSignInProvider, publishSignInProvider, makeSCIMToken (signinproviders:write)
resolveOrganizationAddressstartOrganizationPool, dropOrganizationPool (organizations:write)
signInProviders, verifiedDomains (signinproviders:read)updateOrganization (orgsettings:write)
organizationPool (organizations:read)addVerifiedDomain, checkVerifiedDomain, removeVerifiedDomain, setVerifiedDomainJoining (signinproviders:write)

designTokens is your project’s design tokens, as one complete-by-default read.

const tokens = await foir.ns.project.designTokens();

No arguments, no narrowing: tokens are a whole-project asset rather than a record, so every group comes back together. See Design Tokens API for the shape.

records

record, records, recordVersions and batchRecordOperations: the untyped record surface. Each takes a model key as a string and returns an untyped result, so prefer the per-model operations when you know the model. They are on a client only when its key holds the two-part records:read / records:write; a key narrowed to one model does not see them.

events

events, the project’s event log read page by page from a cursor. It needs events:read, which a publishable or a server key cannot hold. See Event Log.

marketplace

marketplaceListings, marketplaceListing and validateAppManifest. The published app catalogue is the same for every project and is readable with any key, a publishable one included.

middleware

integrationConfig, appCredential, userRecordByIdentity, userIdentitiesById, userByIdentity, appConsoleSettings, writeAppCredential, reportIntegrationStatus, upsertRecord, saveUserRecord, eraseUserRecord, setAppConsoleSettings and startOperation. This is an installed app’s own surface, reached with the app’s scoped token; no API key of yours can call it.

operations

The one namespace whose op names are not its GraphQL root field names.

Reading, listing, cancelling and subscribing to runs with a publishable or a server key requires a signed-in user. Forward the user token; only that user’s runs are accessible. This includes foir.ns.operations.onExecution. A visitor through such a key has only what the key gives, so executing an operation with one also needs a signed-in user whose role grants operations:execute (or that operation by name), unless what the key gives names the operation (operations:execute:<op>), which lets a caller with nobody signed in run that one operation.

Three platform fields keep their own names:

const execution = await foir.ns.operations.operationExecution({ id: 'exec_abc123' }); await foir.ns.operations.operationExecutions({ operationKey: 'contact-form-handler', first: 20 }); await foir.ns.operations.cancelOperationExecution({ id: 'exec_abc123' });

Your project’s own operations are addressed by key, prefixed. An operation keyed contact-form-handler generates the GraphQL mutation executeContactFormHandler, and the data client op execute.contact-form-handler — which is not a legal property name, so it takes bracket access:

const payload = await foir.ns.operations['execute.contact-form-handler']({ input: { name: 'Jane Doe', email: 'jane@example.com' }, mode: 'SYNC', });

foir types emits one execute.<key> entry per operation your key can execute, read straight from namespaces.operations.execute in the manifest. Passing the generated field name instead of the key is a compile error, and would be a 400 at runtime — nothing on the server derives a field name from what you send. KIND_QUERY operations use the query.<key> prefix on the same rule.

Check what your key holds:

curl -H "x-api-key: foir_adm_..." https://api.foir.dev/v1/manifest | jq '.namespaces.operations'

raw — your own document

foir.raw(document, variables?, options?) executes a GraphQL document you wrote yourself, on the credential this client holds.

const { costBreakdowns } = await foir.raw<{ costBreakdowns: { totalCount: number }; }>( 'query Recent($n: Int) { costBreakdowns(first: $n, orderBy: { createdAt: DESC }) { totalCount } }', { n: 5 }, );

It reaches everything the credential reaches and, unlike a typed call, it can name several root fields in one round trip. So it returns the whole data object rather than one root field’s value.

Everything else is identical to a typed call: the same routing, the same persisted-query handshake, the same FoirRequestError. It does not bypass authorization — the executor checks scopes on your document exactly as it would from any other client, so an operation your key cannot perform still fails.

Reach for it when you want field-level control the selection verbs do not offer, or several roots in one request. Everywhere else the typed call is the better default: it checks the operation name, types the result, and prints the selection for you.

options.strict

The third argument controls what happens when the server cannot serve part of your document. It runs in both directions, and the default differs between them.

A malformed selection throws by default. If the server strips a selection for a reason that means the document is wrong — a field that does not exist, sub-selections on a scalar, or sub-selections missing where they are required — raw throws a FoirRequestError naming each stripped path. Pass strict: false to get the partial answer instead:

const data = await foir.raw(DOCUMENT, variables, { strict: false });

This default is the opposite of the typed path’s, on purpose. A generated selection cannot name a field that does not exist, so the typed path has already caught that class before the request leaves. A hand-written document has nothing to catch it, and a stripped selection returns every other field successfully — so a typo reads as a missing feature, and your hand-written result type asserts the response was fine.

A partial response returns by default. A response carrying errors and data is warned about and the data returned, so one field the server could not resolve does not blank a whole page. strict: true turns that into a throw as well, with the data still available on partialData so you can log what you declined to render.

The two are separate switches on one flag, and the strip check runs first: on a malformed document you get the prune error, not the partial-response error.

The prune error carries prunedSelections and not partialData — the two belong to different branches, and the prune throw happens before the partial-response branch is reached.

Note: if you would rather write documents as the normal way of working, @foir/sdk/client is the package for it — a typed request function meant to be paired with graphql-codegen. Same endpoint, same credentials. See Choosing an API Style.

Root fields outside the model operations

Some root fields belong to no model. The untyped record/records escape hatches are foir.ns.records.*, schema introspection (models, projectSchemas) is foir.ns.project.*, and the async-operation callback lifecycle sits in operations for the extension running the call. Choosing an API Style says when to reach for each.

Last updated on