Skip to content

Write the server

Markdown

The code of an application is one HTTP server, and each of its routes is an action. This page shows what an action receives and how it reaches a site through the user’s browser.

Your entrypoint exports default { fetch(request, env, ctx) }. Apigami calls it with the method and path of the action, as the caller sent them to your address, so a small router is enough. env holds your variables and Apigami’s (Environment variables).

main.ts
import { searchProducts } from './actions/search.ts'
import { readBasket } from './actions/basket.ts'
const routes = {
'POST /search': searchProducts,
'POST /basket': readBasket,
}
export default {
async fetch(request: Request, env) {
const { pathname } = new URL(request.url)
// Every hosted application answers GET /healthz with a 200. Apigami calls it after each deploy and once a
// day, and refuses to publish a version that does not answer: keep it cheap.
if (request.method === 'GET' && pathname === '/healthz') {
return Response.json({ ok: true })
}
const route = routes[`${request.method} ${pathname}`]
// A 404 to a GET lets Apigami serve the file of public/ at that path, when there is one
// (a version whose pages Vite builds serves its files first: see Pages built by Vite).
if (!route) return Response.json({ error: 'no such action' }, { status: 404 })
try {
return await route(request, env)
} catch (error) {
// Never a stack to the caller: a message they can act on, and the details in the log.
console.error('action failed', error)
return Response.json({ error: 'the action failed; see the application logs' }, { status: 500 })
}
},
}

One action per module, imported by a relative path. Every file of the version is there, so ./actions/search.ts resolves the way it does on your own machine.

Schedules. The one way to run code on a schedule is x-apigami.crons, which runs an action. An action of a cron that must act for several people reads the version’s key, env.APIGAMI_KEY, and only after GET /v1/me under its run token answered that action with user_ref null, caller_app_id equal to env.APIGAMI_APP_ID and production true: the key acts for every person connected to your application, at an address as through the API (Emails shows one). Only the version in production has a working key, besides the --staging key of a version deployed there, which acts for your team’s members only, and a version on trial has none.

What does not run here. The validation refuses Deno.serve, Deno.env, Deno.readTextFile, Deno.readFile and Deno.cron (deno_api_refused) and imports of an https: URL (url_import_refused). A node:http or Express server never starts (no_default_fetch), and an entrypoint without the default export fails to load with [apigami] Export default { fetch(request, env, ctx) } from your entrypoint. Apigami’s session stands in front of your code (Who is behind a request).

public/logo.svg is served at /logo.svg, without the prefix, but only when your code answers 404 to that GET or HEAD (a version built by Vite serves its files first): a catch-all route that answers 200, as a single-page app does, hides every file of public/. Answer 404 to the paths you do not serve. Anyone can download what is under public/, so the server’s code never goes there (entrypoint_in_public). A version on trial, not deployed yet, serves no file. A file your code reads is imported, never read from disk: import page from './page.html' with { type: 'text' } works for .html, .txt, .md, .sql, .svg and .css; import model from './model.onnx' with { type: 'bytes' } gives a Uint8Array, whatever the extension (a .bin imports as bytes even without it), and a .wasm imports as a module.

A route of your pages needs no declaration. /taches/42, opened directly or reloaded, answers dist/index.html with a 200 and your router shows the screen: declare no page nor action for a client-side route, /:id included.

A version with index.html at its root and vite in the dependencies or devDependencies of its package.json has its pages built by Vite: no field of the manifest says it. Send the project without dist/ and without node_modules/; the lock is optional. Apigami installs every package, devDependencies included, without running any package’s install scripts, then runs npm run build (your prebuild and postbuild run too) and serves what it writes in dist/. Beside it, Apigami builds the server of the manifest’s entrypoint on its own, as for any version: a package the server imports belongs in dependencies, and one found only in devDependencies is refused. Building a version takes 20 to 30 seconds, waited for by its first try or deployment.

Refused Why
build_script_missing package.json has no build script: add "build": "vite build", or "tsc -b && vite build" when the project has a tsconfig.json and typescript
hosting_plugin_refused vite.config.* imports a hosting’s own Vite plugin, or package.json asks for a hosting’s command-line tool: remove it, Apigami serves the pages and builds the server itself
dist_index_missing npm run build wrote no dist/index.html: keep Vite’s default output
dist_path_reserved a file under dist/__apigami/, which Apigami serves itself, or a file name over 300 characters
dist_too_large a file over 16 MiB, more than 2 000 files, or a _headers or _redirects over 128 KiB; the server and dist/ together compress to 32 MiB at most, past which the version is refused with bundle_too_large
action_shadows_dist_file a file of dist/ sits under the first segment of an action’s path, such as /api/, and would never be served
action_path_takes_pages an action at /, or whose first segment is a parameter, such as /{slug}: it would take every page
queue_path_not_an_action a queue relays to a path outside the first segment of every action, refused when the queue is written

What answers which path. Every path under the first segment of an action’s path reaches your server, whatever its method: with an action at /api/notes/{id}, all of /api and /api/…, declared or not, so a route the manifest forgot answers your server’s 404. /healthz and /__apigami/… reach it too. Any other path answers the file of dist/ at that path when there is one, else dist/index.html with a 200, so that a route of your pages opened directly loads the page. A method other than GET or HEAD on such a path answers 405, without reaching your server: a webhook, a form or an OAuth callback goes under an action’s first segment.

Keep the actions under a prefix of their own, such as /api/, and no route of your pages under it: that route would reach your server and answer its 404. A version has at most 49 such first segments, each 97 characters at most.

From a page, apigami.call(action, input, { params }) calls the action on the method its manifest declares: for a get, input goes in the query string, for a post in a JSON body (How an action receives its input). A CSS plugin such as Tailwind goes in devDependencies, like Vite: @tailwindcss/vite in the plugins of vite.config.ts.

A project made by create-vite. Its "build": "tsc -b && vite build" type-checks every file tsconfig.app.json includes, src/ whole, with the browser’s types: keep the server out of it, in server/ for instance with the entrypoint pointing there, or build with "vite build" alone.

Headers and redirects. public/_headers and public/_redirects, which Vite copies into dist/, set the headers and redirects of the files. A file is served with an ETag and Cache-Control: public, max-age=0, must-revalidate unless _headers says otherwise; the starter makes /assets/*, whose names change with their content, immutable. Neither applies to what your server answers.

After a deployment. A tab opened before it still asks for the old version’s chunks, which now answer index.html: listen for vite:preloadError and reload the page, as the Vite project of the guide does.

A try with app_run runs actions only and serves no page: the pages are served once the version is deployed, at the address of the version being tried. public/ is not served apart: Vite copied it into dist/, and the server reads no file of it.

Nothing at the top level of a file may wait on the outside: no fetch, no query, no timer. The version then fails to load, with your code does input or output while it loads. Do it inside fetch(). A database client or a connection is created there too, for each request: one created outside and reused by another request fails with a database client or a connection was created outside the request handler and reused.

Import packages as npm:name@version or jsr:@scope/name, or list them in a package.json. Apigami resolves them once, when the version is created, and keeps the lock with the version. Install scripts never run (only your own npm run build scripts do, on a version built by Vite), a native module (.node) is refused (native_module_refused), and so is a package that npm’s security advisories mark as malicious, named with its version in the refusal. A package version must have been published at least 3 days ago, and the modules of a version weigh 64 MB at most. Node’s built-in modules, such as node:crypto and node:buffer, are there. What a version runs on is set when it is created and never changes afterwards.

Limit
Memory 128 MB of memory per instance, shared by the requests it serves at once, not adjustable
Computing time 300 seconds per request, page or action; time spent waiting on a fetch does not count
Duration of an action At its address, no limit while the caller stays connected: the answer streams as your code writes it, and nobody gets a 202. Your code’s calls back to Apigami for the person stop after an hour (The person’s context). A run Apigami starts itself, a cron, a queue’s task, a subscription or app_run, has 900 seconds of wall clock at most
Outgoing connections 6 open at once per request
A site that sends nothing cut off after about 125 seconds without a first byte
Body of a request to an action 64 MiB at your address, 413 past it; 25 MB for a run Apigami starts itself
Targets no literal IP address, no port 25: a fetch to one rejects with a TypeError, from your code or any library it imports. Call another application at its address, https://{slug}.apigami.tech/…, with a plain fetch (Call another application)

Past the computing time or the memory, an action’s run fails with a sentence that names the limit, and a page answers 503 This page took too long or This page was stopped. A page whose code throws answers 502 This page failed.

actions/search.ts
export const searchProducts = async (request: Request, env) => {
const API = env.APIGAMI_API_URL
// 1. Check the invocation. Apigami routes a declared path to your code only with x-apigami-action and
// x-apigami-credential set, but the routing alone proves nothing: refuse a request without them.
if (!request.headers.get('x-apigami-action') || !request.headers.get('x-apigami-credential')) {
return Response.json({ error: 'not an action call' }, { status: 401 })
}
// GET /v1/me tells you what the token in X-Apigami-Run is worth: which application, which action,
// which version, whether that version serves production, and the person, the same user_ref as the
// x-apigami-user-ref header your action also receives.
const token = request.headers.get('X-Apigami-Run')
const me = await fetch(`${API}/v1/me`, { headers: { Authorization: `Bearer ${token}` } })
if (!me.ok) return Response.json({ error: 'unauthorised' }, { status: 401 })
const run = await me.json()
// A publication that landed mid-flight would otherwise run your new code under an old contract.
if (run.version_id !== env.APIGAMI_VERSION_ID) {
return Response.json({ error: 'this version is no longer the one being called' }, { status: 409 })
}
// 2. Validate the input yourself. The manifest documents the schema; it does not enforce it.
const input = await request.json().catch(() => null)
if (!input || typeof input.query !== 'string' || !input.query.trim()) {
return Response.json({ error: '`query` is required and must be a non-empty string' }, { status: 400 })
}
const limit = Math.min(Math.max(Number(input.limit ?? 10), 1), 50)
// 3. Do the work. Here, through the shopper's own browser: same token, same API. No `user_ref` in the
// body: the token already names the person, and naming one answers 400.
const answer = await fetch(`${API}/call`, {
method: 'POST',
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
Accept: 'application/octet-stream',
'Accept-Encoding': 'gzip',
},
body: JSON.stringify({
op: 'request.fetch',
params: {
domain: 'example.com',
url: `https://example.com/api/search?q=${encodeURIComponent(input.query)}&n=${limit}`,
responseType: 'binary',
},
}),
})
if (!answer.ok) return Response.json({ error: await answer.text() }, { status: 502 })
// The site's own status and headers ride beside the body; the body is the site's bytes.
const status = Number(answer.headers.get('X-Apigami-Status') ?? 0)
if (status !== 200) return Response.json({ error: `the site answered ${status}` }, { status: 502 })
return Response.json({ products: await answer.json() })
}

Key per-person data on user_ref. An action that stores a third-party token per person selects it by run.user_ref, never by a field of its input: whoever calls the action chooses its input. A full example is under Its database. run.locale is that person’s language, en, fr, es or de, the one they read Apigami in: write your answers and emails in it. It is null when the run serves nobody. run.identity is their { name, email } when the version running declares identity and they granted it, null otherwise, and null under a run whose root, or an application that called on its way, is of another group; a cron or a task reads it with GET /v1/users/{user_ref}.

The same token reaches everything else the browser offers. An identifier the site keeps in its own tab, a store or a cart, is read with tabs.storage, from a tab open on the site:

const stored = await fetch(`${API}/call`, {
method: 'POST',
headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ op: 'tabs.storage', params: { domain: 'example.com', key: 'store_id', area: 'local' } }),
})
const { result } = await stored.json() // { tabId, url, area, key, value, length }

With no tab open on the site it answers no open tab for example.com: open one with tabs.open and pass the tabId it returns. A key whose name looks like a credential is never returned, see tabs.storage.

Make an action answer in under 30 seconds, every wait it makes included, and sooner whenever it can: a person is waiting on a page, an AI on its tool call. Thirty seconds is a rule for your code, not a cut by Apigami: it is when the MCP tool app_run stops waiting, keeping the answer for app_runs. Your address does not cut an action off and never answers 202 for it, so any other caller that gives up loses the answer: there is no run to come back to. When a site imposes a pace, wait inside the action only while the whole action, all its spaced calls added up, still answers in under 30 seconds; otherwise answer 429 with a Retry-After header and one sentence the AI can act on, such as “The site allows one search a minute: try again in 40 seconds.” Long work goes to a queue: the action adds a task with POST /v1/apps/{app_id}/tasks under its run token and answers at once, the queue’s worker does the work, and Apigami tells its end. You set the queue up with your MCP tools, or from your code with PUT /v1/apps/{app_id}/queues/{name}, whose body is the settings of configure; its refusals are in Errors.

Adding a task. Up to 1,000 per call, under the run token of the action:

actions/avatars.ts
const added = await fetch(`${env.APIGAMI_API_URL}/v1/apps/${env.APIGAMI_APP_ID}/tasks`, {
method: 'POST',
headers: { Authorization: `Bearer ${request.headers.get('X-Apigami-Run')}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ tasks: [{ queue: 'avatars', id: `avatar:${photoId}`, action: 'renderAvatar', payload: { photoId } }] }),
})
// → { "queued": ["avatar:42"], "replaced": [], "refused": [], "running": [] }
Field Meaning
queue a queue configured in this environment, else 400 unknown queue
id yours, unique in the application’s environment: added again while it waits, the task is replaced (replaced), or kept with "replace": false beside tasks (refused), so the same id never queues the work twice
action the operationId of the action declared at the queue’s internal_app_path, which its worker receives as Apigami-Event-Type; for an external_url queue, a name of yours
user_ref the person the task is done for; by default the person of the run token, none under the application’s key
payload any JSON up to 8 KB, {} by default: all the worker receives

scheduled_at (30 days ahead at most), expires_at, tags (8 at most), queue_order and install_ref are optional.

What a queue’s path receives, and the retry its answer sets

Section titled “What a queue’s path receives, and the retry its answer sets”

Each task arrives at internal_app_path, on the method of the action declared there, never GET or HEAD, with the payload alone as its JSON body and these headers: X-Apigami-Task-Id, X-Apigami-Queue, X-Apigami-Task-Attempt (1 first), Apigami-Event-Type (the task’s action), X-Apigami-Run, the person’s context as on any call for them (GET /v1/me answers their user_ref), and X-Apigami-Install when the task names a browser. It carries no x-apigami-action nor x-apigami-credential: your code tells a task by X-Apigami-Task-Id, which no caller can send, and answers 403 to a request without it, since that path is an action any caller of yours can reach. On a version built by Vite, that path is under the first segment of an action, else the queue is refused with queue_path_not_an_action (Pages built by Vite). Its answer, within the queue’s timeout_seconds:

Answer What becomes of the task
2xx done; its JSON body is the result of task.completed
2xx with X-Apigami-Continue: <JSON> goes on, sent again with that JSON as its payload
429 or 503 with Retry-After sent again after that delay
408 or 5xx, a 429 or 503 without Retry-After included retried as the queue’s retry says, then abandoned
any other 4xx abandoned at once

A 429 or 503 your code answers itself always carries Retry-After: it says when to come back.

A queue per person, held while their Chrome is offline

Section titled “A queue per person, held while their Chrome is offline”

Work that needs one person’s Chrome goes to that person’s own queue, named {user_ref}:<name>, with hold_while_user_offline set to that user_ref. While their Chrome is closed or asleep, Apigami refuses the task itself with extension offline before your code runs, holds it and pauses that queue: nothing runs. When that Chrome comes back, the queue resumes at once. A task that names a browser (install_ref) is held by hold_while_installs_offline: [install_ref] instead.

One queue shared by everyone cannot do this: a hold names one person, and a queue held for one would stop the others. In a queue that holds for nobody, the same extension offline defers the task about 2 seconds, then again, for up to 24 hours: a person whose Chrome stays closed costs a run every 2 seconds, all day. That retry is Apigami’s; your own 429 or 503 carries Retry-After and is sent again after that delay.

A cron that adds this work again at each pass gives each task a stable id, watch:{user_ref} rather than one per pass: added again while it waits, the task is replaced, so a closed Chrome leaves one task waiting, not one more every pass. Configure a person’s queue with env.APIGAMI_KEY or under a run that serves nobody, such as the cron’s: a run that serves a person is refused 403 queue settings require app scope. Do it once, or when adding answers 400 unknown queue: PUT it, then add again.

actions/kick.ts
// The cron's action: one task per person, each in that person's queue. Its run token serves nobody, so it may
// configure queues.
const api = `${env.APIGAMI_API_URL}/v1/apps/${env.APIGAMI_APP_ID}`
const headers = { Authorization: `Bearer ${request.headers.get('X-Apigami-Run')}`, 'Content-Type': 'application/json' }
const add = (userRef: string) => fetch(`${api}/tasks`, {
method: 'POST', headers,
body: JSON.stringify({ tasks: [{ queue: `${userRef}:watch`, id: `watch:${userRef}`, action: 'checkPage', user_ref: userRef }] }),
})
for (const userRef of people) {
const added = await add(userRef)
if (added.status === 400 && (await added.json()).error === 'unknown queue') {
await fetch(`${api}/queues/${encodeURIComponent(`${userRef}:watch`)}`, {
method: 'PUT', headers,
body: JSON.stringify({ internal_app_path: '/check', hold_while_user_offline: userRef }),
})
await add(userRef)
}
}

Apigami announces the end of every task once, as the event task.completed, to the application the task was done for: the one that called the run which added it, else yours, in the environment that asked, so a task your --staging asked for ends there, never in your production. Subscribe to it in x-apigami.subscriptions with { "type": "task.completed", "action": "…" }, whether the task is in your own queue or in a sub-app’s: the event’s app_id names the application whose queue it is. A webhook of yours hears your own tasks’ ends only when it names the type or task.*, never through an empty filter. An end that no such webhook or subscription takes is not journaled: GET /events does not return it. An application that no longer reaches the person of the task does not hear its end. It ends when the worker’s answer finishes it (a 2xx without X-Apigami-Continue, a refusal, the retries used up), when it expires, or when it is removed; a continuation is no end. Its data:

Field Value
task_id, queue the task
status succeeded, failed (logged abandoned in the queue logs, which requeue takes; a logged failed is an attempt to be retried), expired, or cancelled (logged removed)
http_status the status of the attempt that ended it; absent when no attempt did (removed, or expired while waiting)
result the JSON the worker answered that attempt; absent when the answer is over 16 KB or not JSON

The person of the task is the event’s own user_ref, and its install_ref when the task names a browser, as in any event; data never carries them.

So the worker’s answer is the result: it emits nothing to say it is done. A task added again with the same id goes to whoever added it last. When a person moves to another browser, move their waiting tasks without taking them from the application they are done for: send PATCH /v1/apps/{app_id}/tasks with { "where": { "user_ref": "usr_…", "install_ref": "ins_old…" }, "set": { "install_ref": "ins_new…" } }. where names one person and may narrow by install_ref (null for tasks naming no browser), queue, tag, action or up to 1,000 task_ids; set.install_ref is a browser attached to that person, or null. Each task keeps its id, payload, tags, place and attempts, and a queue held for the old browser starts again. The answer is { "updated", "skipped_running", "remaining" }: running tasks are skipped, one call moves up to 50,000, and remaining counts what is left, running tasks included, since a try at the old browser comes back waiting. Send the same body again while remaining is not 0, a few seconds later when nothing moved. task.* is Apigami’s, like each of its namespaces: declaring one in x-apigami.events is refused with event_type_reserved, and emitting one answers 400. A task never expires unless you give it an expires_at. A person who disconnects keeps their tasks: Apigami deletes none, and each one ends failed when it runs. Remove the ones you no longer want on app_user.removed.

Your code sends POST {env.APIGAMI_API_URL}/call with the run token, as above. When the browser reached the site, Apigami answers 200, whatever the site answered: the site’s status travels beside its body. So check Apigami’s status first (answer.ok), then the site’s.

  • Raw, with Accept: application/octet-stream on the call and responseType: "binary", as in searchProducts: the body is the site’s bytes, with no envelope. X-Apigami-Status is the site’s status, X-Apigami-Headers its headers as a JSON object, and Content-Type is always application/octet-stream, even for HTML. With Accept-Encoding: gzip too, the body may come compressed, with Content-Encoding: gzip, which fetch decodes for you.
  • JSON, without that Accept: the result in an envelope. body is the site’s text decoded as UTF-8 with the default responseType: "text"; with "base64", or "binary" without the Accept, it is base64 and encoding: "base64" is added. headers names the site’s headers in lowercase.
200, the JSON envelope
{
"result": {
"status": 404,
"headers": { "content-type": "text/html; charset=utf-8", "date": "Thu, 08 Oct 2026 09:00:00 GMT" },
"body": "<!doctype html><title>Not found</title>…"
}
}

Redirects are followed inside the declared domain; neither shape gives the address the request ended on.

When Apigami refuses, the status is not 2xx and the body is JSON, { "error": "…" }, never the site’s answer:

Status error What it means
400 a run token already names the person: … Remove user_ref from the body
403 install_ref is not a browser of this user The install_ref you named is not one of the run’s person’s browsers
401 bad run token Unknown, ended or expired: use the token of the run in progress
403 example.com is not a domain this application declares as reached through the browser params.domain is not one of your x-apigami.domains with via: "extension"
403 consent requested, with consentPending: true The approval window was open 45 seconds without an answer: run again once the person clicks Authorize. A run of a queue or a cron, and every run it calls, answers at once, since nobody waits on it: the window opens all the same
403 no grant The person refused the site; send them to settings_url (Refusals)
403 not paired The person is no longer connected to your application
403 no install in this run The run has no browser: an application trigger, or a run started without one
502 What the browser reported: url is outside the granted domain example.com: …, a network error, its 30-second timeout With "outcome": "unknown", the browser received the call and its answer was lost: a write may have reached the site
503 extension offline or extension outdated, with online and last_seen_at The person’s browser is closed or asleep: Apigami waited up to 35 seconds for it to come back

Your code reads every variable on env, as env.NAME. Apigami sets APIGAMI_API_URL, APIGAMI_APP_ID and APIGAMI_VERSION_ID; APIGAMI_KEY, the version’s own key, on a deployed version only, never on a trial; DB, the SQLite database, with "database": "sqlite"; DATABASE_URL and DIRECT_URL with "database": "postgres", or with "postgres-external", whose address a human types on a link (A PostgreSQL database of your own); and FILES, the file storage, with "files": true. The names your own code needs are declared in x-apigami.env, and the MCP tool app_environment_write fills them. An assistant writes a plain value itself; a secret one, it never sees: the tool answers one link for the names it passes, and a human types the values there — anything that passes through a conversation with a model has stopped being secret. Until a declared name has a value, deploying a version and running an action both answer 409 with the names that are missing. Each entry is { "name": "API_KEY", "description": "…" }, with "secret": true for a value nobody is shown again once typed, and "required": false for a name your code does without: the page offers it, it never counts as missing, nothing waits for its value, and your code handles its absence itself (env.NAME is then undefined). Every name starting with APIGAMI_ is reserved, like DATABASE_URL, DIRECT_URL, DB, FILES and ASSETS. A value holds 5,120 bytes at most, and none may hold an Apigami key (apg_…) or run token (rn_…).

An action is called at your address on the method and the path your manifest declares, with the concrete values of a path template: GET /v3/grants/abc/messages?limit=5 for /v3/grants/{grant_id}/messages. Your code receives that request as it came: the method, the path, the query string minus every apigami_ parameter, the caller’s headers minus Apigami’s own, and the body byte for byte, streamed, with its Content-Type. It reads the parameters of a template from the path itself. A get, head or delete takes its input in the query string; apigami.call(action, input, { params }) puts input there for those methods and sends it as a JSON body for the others, params filling the template. A run Apigami starts itself, a cron, a task or app_run, sends its input as a JSON body, and app_run takes path, the concrete path of a templated action, and query for a get.

Every action of every version is served at its application’s address, https://{slug}.apigami.tech, with no path prefix, on its --staging host and on each domain of its own:

Terminal window
curl -s "https://email-calendar.apigami.tech/v3/grants/abc/messages?limit=5" \
-H "Authorization: Bearer $API_KEY" -H "X-Apigami-User-Ref: usr_…"

Apigami checks the credential, finds the action by its method and path, checks that the caller may call it for that person, then hands the request to your code and streams the answer back: your status, your headers and your bytes, Content-Encoding included, minus every X-Apigami-* header you set, plus X-Apigami-Request-Id.

One Apigami credential per request:

Credential Who calls For whom
none, on an action listed in open_actions anyone nobody, whoever calls
the session cookie, a page of the same address calling it (apigami.call does) your application the person of the session
a page token in Authorization: Bearer, from the side panel your application the person of the token, only from its page’s origin
nothing to add: your code’s own fetch to another application’s address the version that sent it the person your code is serving, if any
your application’s API key, apg_…, or the version’s env.APIGAMI_KEY your application nobody, or the person named in X-Apigami-User-Ref (Calling for a person from your server); under the --staging key, a member of your team only

An Authorization carrying an Apigami credential wins: the cookie is then ignored, never mixed in. A run token, an agent token, a GitHub Actions token, a person’s own Apigami token (the one their AI assistant or their Apigami space holds) or X-Apigami-Extension answers 400 this credential is not taken at an application's address, and X-Apigami-User-Ref without a key 400 one Apigami credential per request. A key of another application calls yours only while that application’s production declares yours in x-apigami.subapps. Your --staging address serves your application alone: its key, the --staging version’s key, a member’s session there, and the key of an application of your group whose production declares it, when it is private. The --staging version’s key also calls the production of a sub-app that version declares, as your production’s key does.

Your --staging acts for your team only. Its code was never reviewed, so under its key, and under any key at your --staging address, X-Apigami-User-Ref naming someone outside your team answers 403 a --staging version acts for its team's members only. On the API, its key gets the same 403 for a person named in the body of POST /call or POST /requests, or in the path of /v1/users/{user_ref}; GET /v1/users and GET /v1/installs list your members alone, the queue routes hold your staging queues, never production’s, and GET /events and GET /v1/users/unreached answer 403: reading the journal and erasing people is production’s job.

A cookie counts on an action only for a request of the same origin (Sec-Fetch-Site: same-origin, or else an Origin equal to your address): a link, a form or a fetch from anywhere else answers 403 cross-site request: call this action from a page of this address. An action, a GET included, never runs from another site’s link.

Header Value
x-apigami-action the action’s operationId
x-apigami-request-id one id per request, also given to the caller in X-Apigami-Request-Id
x-apigami-credential session, subapp, app_key, version_key, run for a run Apigami starts itself, none for an open action
x-apigami-caller-app-id the application calling: the key’s, the token’s, or the one whose code called; absent on an open action
x-apigami-root-app-id the application the person connected to, on a call for a person
x-apigami-user-ref the person, as your group knows them, on a call for a person and on a run Apigami starts itself for one
x-apigami-install-ref the browser the caller named, when it is one of your group’s
x-apigami-key-id the key, on a call with a key
X-Apigami-Run on a call for a person, what your code sends back to Apigami for them (The person’s context)

Nobody forges them: every x-apigami-* header a caller sends is taken out first, and so is an Authorization carrying an Apigami credential. The routing alone proves nothing. A path your manifest declares is served only to a credential, unless it is in open_actions; a path it does not declare is a page, served to anyone. So an action that serves a person refuses a request without x-apigami-action and x-apigami-credential, and your code tells an action from a page by x-apigami-action, never by a missing x-apigami-user-ref.

How a path is matched. A literal segment wins over a parameter: /v3/grants/me before /v3/grants/{grant_id}. One trailing slash is ignored, and your code receives the path as it was sent. HEAD on a get action is that action, with the same checks. OPTIONS reaches your code with no credential, so the code that serves your CORS goes on serving it. Any other method on a declared path answers 405 with Allow. A parameter that is empty, or decodes to /, \ or a control character, answers 400 bad path parameter.

On a call for a person, X-Apigami-Run holds a handle that stands for this request only. Your code calls Apigami back with it as it always did, in X-Apigami-Run or in Authorization: Bearer: /call, GET /v1/me, events, tasks. It is worth nothing sent anywhere else, and nothing after the request. Apigami checks the person again every five minutes; an hour after the request arrived, or once the person is no longer served, those calls answer 401 this request's context has ended. The action itself goes on: only its calls for the person stop. An open action gets no X-Apigami-Run: it calls Apigami with Authorization: Bearer ${env.APIGAMI_KEY}, which writes to your team ("to": "team") or asks the AI, never for a user_ref taken from the request.

A key revoked, or a person removed from your application, stops working at your address within two minutes; a page’s session within five.

Call another application: a plain fetch to its address

Section titled “Call another application: a plain fetch to its address”

Your code calls an application it declares the way any client does, at its address, with no Apigami header:

const numbers = await fetch('https://connectors-aircall.apigami.tech/number/list', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({}),
})

Apigami recognises a request your code sends, during a request it serves, to an application’s address, a domain of its own, or env.APIGAMI_API_URL: the sub-app is called by your version, for the person your code serves, under the application they connected to. A cron or a task calls its sub-apps the same way. Sent outside a request, such as work left running after the answer, or from code hosted elsewhere, the request carries nothing: call with env.APIGAMI_KEY, and X-Apigami-User-Ref for a person. An Authorization your code sets itself, a key or a run token, is kept as it is.

Every refusal at an address is JSON, { "error": "…" }, sometimes with hint, and carries X-Apigami-Platform: 1, a header your code can never send: an answer with it is Apigami saying no, an answer without it is the action’s own. Troubleshooting lists them. 503 this address cannot be reached right now: retry in a few seconds is the one to retry, after its Retry-After. A refusal also carries Access-Control-Allow-Origin: *, so a caller from another origin can read it; your code serves the CORS of its own answers. Too many calls for one key and one person answer 429 with Retry-After.

These routes no longer exist: since 10 November 2026, every action answers at its application’s address only.

Before Now
POST https://api.eu.apigami.com/v1/apps/{app}/actions/{action} the action at its application’s address, on its method and path
X-Apigami-Path for a templated action the concrete path itself, at the address
X-Apigami-Version to try a version its --staging address with your key, or app_run with version (Run it, deploy it, publish it)
202 { run_id } and GET /v1/runs/{run_id}/answer nothing to come back for: the answer streams; long work goes to a queue
no X-Apigami-Run-Id on an answer, to spot Apigami’s refusal X-Apigami-Platform: 1 on the refusal
POST /__apigami/token, a page reading its own token the session cookie, which no script reads; apigami.call calls the same origin
an open action calling Apigami with X-Apigami-Run Authorization: Bearer ${env.APIGAMI_KEY}
an action never gets x-apigami-user-ref it does, on a call or a run for a person: read x-apigami-action to tell an action from a page

A version whose code still follows one of them is refused when it is written, each error with its fix: calling /v1/apps/…/actions/… (core_action_route), reading /v1/runs/…/answer (core_run_answer), sending X-Apigami-Version (version_header), a page holding a run token or calling /__apigami/token (page_run_token), an open action calling Apigami under X-Apigami-Run (open_action_run_token).

A server that Apigami does not host, yours, calls an action at its application’s address with your application’s API key, and with X-Apigami-User-Ref for a person, the user_ref the code exchange gave you. That is the one way: there is no token per person for a server.

Terminal window
curl -s -X POST "https://acme-basket.apigami.tech/search" \
-H "Authorization: Bearer $API_KEY" -H "X-Apigami-User-Ref: usr_…" \
-H 'Content-Type: application/json' -d '{"query":"coffee"}'

Your key acts for every person connected to your application, at its address as through the API: anyone holding it can call any action for any of them. Keep it on your server, and revoke it with app_keys_write the moment it leaks. X-Apigami-Install-Ref names one of the person’s browsers, as on POST /call.

The same key and header open your application’s MCP server, https://api.eu.apigami.com/mcp/{slug}, for that person: your server’s AI lists and calls the tools theirs would. It takes your application’s own keys only, never a version key nor another application’s, answers 400 without X-Apigami-User-Ref and 429 past about 5,000 calls per key in 10 seconds, and never sends WWW-Authenticate. It does not read X-Apigami-Install-Ref: a tool runs in the browser Apigami picks for the person.

A user_ref or a key made in the last two minutes may answer 404 unknown user_ref or 401 bad client credentials at the address, with a hint that says so: try again shortly. When Apigami’s own API is down, the address keeps serving with what it last knew, and a person you never called before may get the retryable 503.