Build an application
MarkdownAn application is code Apigami hosts for you. It answers HTTP, it can hold a database, it can run on a schedule, and it can use the session of a user who approved it — or call another application that already knows how. You write it, push it, run it and publish it without a server, a domain or a development machine of your own.
One object carries all of it: a version.
An application is an HTTP server with several routes. A version holds all of its files and all of its actions. Naming an action only ever means running that one.
There is no separate source, no build pipeline to track, no channel to point at. You write a version, you run one of its actions, you deploy it, you put it in production. Rolling back is putting an earlier version in production — the same call.
If your AI assistant is connected to Apigami over MCP, every step in these pages is one tool call
(app_settings, app_version_write, app_run, app_deploy, app_publish). Everything those tools
do, the /v1 routes in these pages do, so nothing is available only through an assistant.
The credentials in the examples
Section titled “The credentials in the examples”$TOKEN is the credential of a member of your team, sent as Authorization: Bearer $TOKEN to the
/v1/apps routes that create, write, deploy and publish: an agent token from an agent
sign-in, which is how an AI assistant in a terminal, on a server or in CI
gets one (in a hosted chat or a sandbox, the person adds the
connector instead), or the access token of a signed-in session. Running an action over HTTP takes
$API_KEY instead, an API key of the application, which the MCP tool
app_keys_write creates; an assistant holding an agent token runs actions with the MCP tool app_run. $APP_ID
is the id that creating the application returns.
Starter template: hello world without a browser
Section titled “Starter template: hello world without a browser”The smallest complete application: GET /healthz, one action that answers JSON, and a home page. It
reaches no site through a browser, so a person connects to it with their email alone, from any
device. Three files; replace the slug with a name of your own first, since a slug is unique on all
of Apigami.
An application a team will rely on starts from the
CRM starter: apigami_docs with the query
crm starter.
{ "openapi": "3.1.0", "info": { "title": "Hello", "description": "Greets the person using it, by name.", "version": "1.0.0" }, "x-apigami": { "manifest_version": 2, "slug": "acme-hello", "entrypoint": "main.ts", "pages": [{ "kind": "home", "id": "home", "title": "Hello", "page_url": "/" }] }, "paths": { "/hello": { "post": { "operationId": "sayHello", "summary": "Say hello", "description": "Answers a greeting for the name given, and the user_ref of the person it serves.", "requestBody": { "required": false, "content": { "application/json": { "schema": { "type": "object", "properties": { "name": { "type": "string", "maxLength": 80, "description": "Who to greet, world when left out" } } } } } }, "responses": { "200": { "description": "The greeting", "content": { "application/json": { "schema": { "type": "object", "required": ["message", "user_ref"], "properties": { "message": { "type": "string" }, "user_ref": { "type": ["string", "null"], "description": "The person served, null when nobody is connected" } } }, "example": { "message": "Hello, Ada!", "user_ref": "usr_3f9c1a0e7b2d4c58a61e9f0b2d7c4e13" } } } } } } } }}main.ts exports default { fetch(request, env) }, reads APIGAMI_API_URL from env and imports
home.html as text: nothing reaches the network while the module loads.
import home from './home.html' with { type: 'text' }
const PAGE_HEADERS = { 'content-type': 'text/html; charset=utf-8', 'x-content-type-options': 'nosniff', 'referrer-policy': 'no-referrer', 'cross-origin-opener-policy': 'same-origin-allow-popups',}
const sayHello = async (request: Request, env) => { // Who is asking comes from the run token Apigami hands the action, never from its input. const token = request.headers.get('X-Apigami-Run') const me = await fetch(`${env.APIGAMI_API_URL}/v1/me`, { headers: { Authorization: `Bearer ${token}` } }) if (!me.ok) return Response.json({ error: 'unauthorised' }, { status: 401 }) const { user_ref } = await me.json() const input = await request.json().catch(() => ({})) const name = typeof input?.name === 'string' && input.name.trim() ? input.name.trim().slice(0, 80) : 'world' return Response.json({ message: `Hello, ${name}!`, user_ref })}
export default { async fetch(request: Request, env) { const { pathname } = new URL(request.url) if (request.method === 'GET' && pathname === '/healthz') return Response.json({ ok: true }) if (request.method === 'GET' && pathname === '/') return new Response(home, { headers: PAGE_HEADERS }) if (request.method === 'POST' && pathname === '/hello') return sayHello(request, env) return Response.json({ error: 'not found' }, { status: 404 }) },}<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Hello</title><h1>Hello</h1><form id="hello"> <input id="name" placeholder="Your name" maxlength="80"> <button>Say hello</button></form><p id="answer"></p><script src="https://api.eu.apigami.com/apigami.js"></script><script type="module"> // Nothing personal is rendered here: the greeting comes from the action, under the person's session. // ready() waits for the session, sending a visitor through Apigami's connect page and back first. document.getElementById('hello').addEventListener('submit', async (event) => { event.preventDefault() try { await apigami.ready() const { message } = await apigami.call('sayHello', { name: document.getElementById('name').value }) document.getElementById('answer').textContent = message } catch (error) { document.getElementById('answer').textContent = String(error) } })</script>With the MCP tools: app_settings with a name, then app_version_write with the three files, then
app_run with the action sayHello and extension_id, app_deploy, app_run again with version
on the deployed version, and app_publish, which refuses a version never run once deployed. Over
HTTP, create the application, then write the version from the three files in one call:
APP_ID=$(curl -s -X POST https://api.eu.apigami.com/v1/apps \ -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \ -d '{"name":"Hello"}' | jq -r .id)
jq -n --rawfile manifest manifest.json --rawfile main main.ts --rawfile home home.html '{ base_version_id: null, changes: [ { op: "write", path: "manifest.json", content: $manifest }, { op: "write", path: "main.ts", content: $main }, { op: "write", path: "home.html", content: $home } ]}' | curl -s -X POST "https://api.eu.apigami.com/v1/apps/$APP_ID/versions" \ -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' --data-binary @-The answer carries the version_id; then run, deploy and publish it as
Run it, deploy it, publish it shows. The address to give people is
https://app.apigami.com/connect?app_id=APP_ID: it connects them, then opens the home page. The home page’s own
address works too: when the page needs a person, it sends a visitor through the same connection, and back.
Vite project: React pages and a Hono server
Section titled “Vite project: React pages and a Hono server”The same greeting, its page written in React and built by Vite, its server in Hono. index.html at the root
and vite in package.json are what make Apigami run npm run build and serve dist/
(Pages built by Vite). The server’s action lives under /api/, so no
route of the pages falls under it. Seven files; replace the slug first.
{ "openapi": "3.1.0", "info": { "title": "Hello", "description": "Greets the person using it, by name, from a page built by Vite.", "version": "1.0.0" }, "x-apigami": { "manifest_version": 2, "slug": "acme-hello-vite", "entrypoint": "src/server.ts", "pages": [{ "kind": "home", "id": "home", "title": "Hello", "page_url": "/" }] }, "paths": { "/api/hello": { "post": { "operationId": "sayHello", "summary": "Say hello", "description": "Answers a greeting for the name given, and the user_ref of the person it serves.", "requestBody": { "required": false, "content": { "application/json": { "schema": { "type": "object", "properties": { "name": { "type": "string", "maxLength": 80, "description": "Who to greet, world when left out" } } } } } }, "responses": { "200": { "description": "The greeting", "content": { "application/json": { "schema": { "type": "object", "required": ["message", "user_ref"], "properties": { "message": { "type": "string" }, "user_ref": { "type": ["string", "null"], "description": "The person served, null when nobody is connected" } } } } } } } } } }}hono is in dependencies, since the server imports it; what only the pages import goes in devDependencies.
{ "name": "acme-hello-vite", "private": true, "type": "module", "scripts": { "build": "vite build" }, "dependencies": { "hono": "^4.10.0" }, "devDependencies": { "@vitejs/plugin-react": "^5.0.0", "react": "^19.1.0", "react-dom": "^19.1.0", "vite": "^7.1.0" }}import { defineConfig } from 'vite'import react from '@vitejs/plugin-react'
// `base` stays /, the default: every file index.html names is then a file of dist/.export default defineConfig({ plugins: [react()] })<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Hello</title> <script src="https://api.eu.apigami.com/apigami.js"></script> </head> <body> <div id="root"></div> <script type="module" src="/src/main.tsx"></script> </body></html>import { useState, type FormEvent } from 'react'import { createRoot } from 'react-dom/client'
// A tab opened before a deployment asks for chunks the new version no longer has, which answer index.html.window.addEventListener('vite:preloadError', () => window.location.reload())
declare const apigami: { ready(): Promise<unknown>; call(action: string, input: unknown): Promise<{ message: string }> }
const App = () => { const [name, setName] = useState('') const [answer, setAnswer] = useState('') const sayHello = async (event: FormEvent) => { event.preventDefault() try { await apigami.ready() setAnswer((await apigami.call('sayHello', { name })).message) } catch (error) { setAnswer(String(error)) } } return ( <form onSubmit={sayHello}> <h1>Hello</h1> <input value={name} onChange={(event) => setName(event.target.value)} placeholder="Your name" maxLength={80} /> <button>Say hello</button> <p>{answer}</p> </form> )}
createRoot(document.getElementById('root')!).render(<App />)import { Hono } from 'hono'
const app = new Hono<{ Bindings: { APIGAMI_API_URL: string } }>()
app.get('/healthz', (c) => c.json({ ok: true }))
app.post('/api/hello', async (c) => { // Who is asking comes from the run token Apigami hands the action, never from its input. const me = await fetch(`${c.env.APIGAMI_API_URL}/v1/me`, { headers: { Authorization: `Bearer ${c.req.header('X-Apigami-Run')}` } }) if (!me.ok) return c.json({ error: 'unauthorised' }, 401) const { user_ref } = await me.json() const input = await c.req.json().catch(() => ({})) const name = typeof input?.name === 'string' && input.name.trim() ? input.name.trim().slice(0, 80) : 'world' return c.json({ message: `Hello, ${name}!`, user_ref })})
export default appVite copies public/ into dist/, and _headers there sets the headers of the files: the names under
/assets/ change with their content, so they are kept for a year.
/assets/* Cache-Control: public, max-age=31536000, immutableSend it with app_version_upload in archive mode, without what the build writes:
zip -r - . -x 'node_modules/*' 'dist/*' | curl -X PUT --data-binary @- "$URL". Its first app_run or
app_deploy waits 20 to 30 seconds for the build. app_run with sayHello and extension_id tries
the action; the page is served once the version is deployed.
CRM starter: a team app with pages, a database and mail
Section titled “CRM starter: a team app with pages, a database and mail”A complete business app to copy, public and under the MIT license: github.com/apigami-tech/crm-starter. Contacts in a list the server sorts, filters and paginates, a team invited by email, the mails exchanged with each contact, full-text search, a side panel, and an MCP server for the team’s AI. React pages built by Vite, a Hono server, SQL by hand on SQLite.
Start from it for an application a team will rely on: its mails are sound, its contract is checked, and its 146
tests keep each change safe. Only a small shared list is quicker written directly. Its README.md lists each
pattern with its file, how to add a field or an object, and how to take the mails or the Gmail panel out.
To take it: git clone https://github.com/apigami-tech/crm-starter, or “Use this template” on GitHub. Replace the
slug acme-crm in manifest.json, run npm install && npm run build && npm test, create the application with
app_settings, then write the version from the sources, without node_modules/ and dist/, with
app_version_upload in archive mode. It calls two published applications, the Connectors hub and Mails et
agenda: both are public, available to everyone.
Without git: curl -L https://github.com/apigami-tech/crm-starter/archive/refs/heads/main.zip -o starter.zip.
Taking it needs a session that runs commands and reaches GitHub and Apigami. Where yours cannot, build directly, or offer the person to go on in the code mode of their AI tool, with the prompt to paste there.
The five patterns that are easy to get wrong, as the starter writes them.
Who calls comes from GET /v1/me under the request’s run token, on every call: a page, an MCP tool, a trial
and a cron alike.
export const identifyCaller = createMiddleware<AppEnvironment>(async (c, next) => { const me = await fetch(`${c.env.APIGAMI_API_URL}/v1/me`, { headers: { Authorization: `Bearer ${c.req.header('X-Apigami-Run')}` }, }) if (!me.ok) throw new ActionError(401, 'This action answers a request Apigami relays, with its run token.') const run: Run = await me.json()An event is a notice, a task does the work. The action that receives message.* serves nobody, so it queues
a task for the person of the event; the task reads the mail again and stores it, and may run twice.
// The run of an event serves nobody, so it cannot read the mail: a task run for the person of the event does. const payload: ActionInput<'internal.sync_message'> = { grant_id: reference.data.grant_id, message_id: reference.data.id } await addTasks(c, 'incoming_messages', [{ id: `message:${payload.grant_id}:${payload.message_id}`, user_ref: event.user_ref, payload }]) return c.json({ outcome: 'queued' } satisfies ActionOutput<'internal.receive_message_event'>)})messageRoutes.post('/api/internal/sync_message', async (c) => { const input = await inputOf(c, 'internal.sync_message') const ignored = () => c.json({ outcome: 'ignored' } satisfies ActionOutput<'internal.sync_message'>) // A mailbox not known yet is not an error: once listed, its history brings this mail. const mailbox = await findTaskMailbox(c, input.grant_id) if (!mailbox) return ignored() const mail = await getMailMessage(mailbox.grant_id, input.message_id) const storedMessageId = mail && await storeMailMessage(c.env.DB, mailbox, mail) return storedMessageId ? c.json({ outcome: 'stored' } satisfies ActionOutput<'internal.sync_message'>) : ignored()})A sub-app is called by a plain fetch at its address, with no header of yours: Apigami carries the person
the request serves. One place turns a busy sub-app into a 503 a task waits on.
const MAIL_APP_ORIGIN = 'https://email-calendar.apigami.tech'/** The mailboxes of the person served, the revoked ones included. One page: nobody attaches fifty mailboxes. */export const listMailConnections = async () => { const response = await requestMailApp('/connection/list', postJson({})) const { items } = z.object({ items: z.array(z.unknown()) }).parse(await response.json()) // A connection still without a grant has nothing to read yet: it comes back by its event. return items.flatMap((item) => mailConnectionSchema.safeParse(item).data ?? [])}The connectors page is the hub’s own, framed. The manifest aliases
the hub’s home at /connectors, and a page of the app frames that address.
{ "kind": "page", "id": "connectors", "title": "Connectors", "page_url": "/connectors", "alias": { "app_id": "70dbe736-08dd-433c-954e-38cf54c131aa", "page": "home" } } <iframe src={CONNECTORS_ALIAS_PATH} title="Connectors" className="min-h-0 w-full flex-1 rounded-md border" />An MCP tool is an action marked is_mcp_tool, its description written for the person’s AI: when to call it
rather than its neighbour, and what it answers.
"/api/contact/get": { "post": { "operationId": "contact.get", "summary": "Read one contact with its notes", "x-apigami": { "is_mcp_tool": true, "is_read_only": true },The guide, page by page
Section titled “The guide, page by page”Read them in this order the first time; each one stands on its own afterwards.
- The manifest:
manifest.json, the sites an application reaches and the name it goes by. - Write the server: the HTTP server whose routes are the actions, what an action receives and how it reaches a site.
- Push and publish a version: send the files, fix what the validation found, try an action, put a version in production, find out what failed.
- Publish from GitHub: let GitHub Actions check every pull request and publish every merge, with no secret to store.
- Side panel, home and settings pages: the screens an application serves.
- The person behind a page: which person a page serves, on the server and in the page, and how long a page keeps its access.
- Support conversations: the people who use your application write to its team, and you answer them, for all your applications, over MCP.
- Database and schedules: a SQLite database per application, PostgreSQL when it needs one, and actions that run on their own.
- Files: file storage per application, served and received by its own routes.
- Sign in to other services: a person’s account elsewhere, and asking them to set up or reconnect.
- Call other applications: use what another application already does, and show its settings.
- Your own address: serve production at an address of yours.
- Example: watch a page and show what is new: a complete application, a trigger reading a page through the person’s browser, its database and a home page.