Everything you need to build a backend on Gipity: serverless functions, databases, and REST APIs. This is the guide for the web-fullstack template (frontend in src/ + functions + a migrations/ database) and the api template (functions only, no frontend). Both are blank-but-wired: they deploy green as-is, so gipity add → gipity deploy is a working baseline before you write a line. Anything named example is a disposable placeholder - overwrite it or delete it, no ceremony. Deleting functions/<name>.js and redeploying deregisters that function and takes its endpoint down.
Templates install real files - Read one before you change it. web-fullstack/api write a full set of files (gipity.yaml, frontend, and more); they already exist on disk. To change one, read it first, then edit it. Don't treat template files as new.
Workflow
For every new function:
- Write the function in
functions/{name}.js - Add it to
gipity.yamlunderfunctionsinside thetype: functionsphase, never at the root (deploy rejects that):deploy: phases: - name: functions type: functions source: functions functions: - name: my-todos auth: user tables: [todos] - Write tests in
tests/api/{name}.test.js - Deploy:
gipity deploy - Run tests:
gipity test
Strongly recommended: write a test file for every new function. Use your judgment - skip tests only for trivial glue code (one-liners, obvious passthroughs), scratch/throwaway experiments, or when the user explicitly opts out. Default is: write tests. Always deploy and test after creating functions - don't ask permission, just do it.
Where the testing details live: load the app-testing skill - the test() / ctx.fn.call contract, calling authenticated functions as a fixture user (ctx.fn.callAs(ctx.users.alice, ...)), and testing auth: user functions for the signed-in happy path and cross-user isolation.
In test files, do NOT import node:test or node:assert - the harness provides test() and assert as globals (and strips such imports).
After every deploy, read the phase results. Any phase with status: warning starts with "FIX" and means something is deprecated or shaped wrong - usually in gipity.yaml. Treat these as TODOs, not info: fix the underlying file and redeploy. status: failed phases block the deploy from completing correctly - fix before moving on.
gipity.yaml - function permissions
Functions deploy as public endpoints. Deploy adds an entry for an undeclared one, with the tables/services its code uses; an existing entry is authoritative. For the full manifest format, phases, and deploy flags see deploy; this section covers only functions (per-function permissions).
Declare in functions only when you need to:
- Change auth level (
user,member) - Grant database access (
tables) - Allow external HTTP calls (
fetch_domains) - third-party APIs only (nota.gipity.ai; see app-function-services) - Declare app services (
services: [...]) - which injected app services this function may call (see app-function-services). An undeclared service throws; an unknown name fails the deploy.
deploy:
phases:
- name: functions
type: functions
source: functions
functions:
- name: get-items
auth: public
tables: [items] # DB access
- name: get-quote
auth: public
fetch_domains: [api.example.com] # HTTP access
- name: my-todos
auth: user # Requires login
tables: [todos]
Auth Levels
- public - no auth needed, call directly
- user - any signed-in Gipity user; requires X-App-Token, X-Api-Key, or Authorization header (load
app-authfor details) - member - you, the app owner (plus anyone you add to the project). This is the owner-only gate: admin screens, settings, moderation, and decision queues.
Personal data means auth: user. For the user's own things ("my location", "my journal"), functions touching that data are auth: user and filter by ctx.auth.userGuid; a public one lets anyone add and read rows. Deploys warn (fn-public-write) on public functions that write; deploy has the public_write opt-out.
A script, cron, or agent calls your app with a project API key - never a hand-rolled one. The platform already mints revocable, named, per-project keys; the caller sends X-Api-Key: <key> and passes the user/member gate with no browser and no login. Inside the handler ctx.auth.via is 'api_key' (vs 'user' for a signed-in person, 'anonymous' for public) and ctx.auth.apiKeyName is that key's label - so "which rows did the script write?" is one column stamped from ctx.auth. Never build your own api_keys table, token minting, or revoke endpoint - see app-api-keys.
"Nothing happens until I approve it" is auth: member + a status column. Owner-decides-each-one apps (refund desk, moderation queue, booking requests) are one shape: a public function (public_write: true) writes the request with status = 'pending', an auth: member function lists the pending ones, and an auth: member function flips one to approved/denied (record who and when). Nothing auto-decides because only the member endpoint can write the status. To tell the owner a decision is waiting, email them from the create function: await email({ to: 'owner', subject, text }) (services: ['email']) goes to the app owner's account email, which the function never sees. notify() reaches only user guids subscribed in this app, so it pings the owner only after they sign in and turn on notifications. Test it with ctx.fn.callAs(ctx.users.owner, ...) (see app-testing). Workflow approval steps are not this - they pause a workflow run, not a deployed app.
Writing Functions
Functions are JavaScript files in functions/. Each exports a default async handler:
// functions/get-items.js
export default async function getItems(ctx, { db }) {
const { category } = ctx.body;
const { rows } = await db.query(
'SELECT * FROM items WHERE category = $1', [category]
);
return rows;
}
Arguments:
- First:
ctx= request context with{ body, rawBody, query, headers, method, auth } - Second: services object
{ db, fetch, secrets, env, console, jobs, guid, randomToken, storage, crypto, records, llm, image, tts, sound, music, video, transcribe, location, notify, email, realtime, embed, approval }- the last twelve are app services (see "What a function can call" below); each only works if declared ingipity.yamlservices: [...].storageworks on the app's uploaded files:storage.info(fileGuid)names a file's uploader (check it before linking a browser-supplied guid to a record),storage.delete(fileGuid)removes its bytes + variants,storage.importUrl(url, opts?)saves a file from a URL (a webhook keeping a finished render),storage.read(fileGuid, { encoding? })reads a file's bytes (or text, max 20 MB), andstorage.readTextreads a PDF's text; see app-files-storage. Likedb/jobs,storageneeds noservices:declaration, but importUrl's host goes infetch_domains.guid('prefix')mints a complete, ready-to-use unique id -prefix+_+ 12 crypto-random chars (e.g.guid('RF')→RF_a7k2mq9pd3xe); store and show it whole as the code, don't slice a suffix out of it to build your own (that's the trap - you get an empty/short fragment that collides).randomToken(chars?)mints crypto-random SECRETS (API keys, invite codes; 16-64 chars, default 40).cryptodoes hashing, HMAC and constant-time compares (see app-development-reference).recordsdoes validated, audited writes that fire record.* workflow triggers (see app-database). - Service names don't reserve anything. Your own top-level
const db,function storage(), orimport { randomToken } from '../_lib/util.js'is fine: it shadows the injected one in that file, and the second argument still carries the real services.
Return value becomes { data: <your return> } in the HTTP response. The data wrapper is always present on 2xx, so client code must read json.data, never json directly. On 4xx/5xx the body is { error: { code, message } } instead.
Imports must be relative (./helper.js) - bare imports (import _ from 'lodash') and Node built-ins (fs, path, crypto) are rejected; there is no node_modules and no WebCrypto. For hashing/HMAC use the injected crypto service.
Share code across functions: put the common helper in functions/_lib/ and import it as ../_lib/<file>.js from any function file - never copy it into each function or invent a functions/lib/. _lib/ files bundle into every function at deploy. Full ES-module rules, multi-file functions (functions/<name>/index.js + helpers), _lib details, and kits that ship backend pieces: read app-development-reference.
Request context (ctx)
ctx.body // request arguments land here - both Gipity.fn(name, body) and the test harness ctx.fn.call(name, body) send args in the POST body, so read every param (including a limit/page/filter) from ctx.body
ctx.query // URL query string (?a=1) - only populated if you build a URL with one yourself; the SDK and test harness never use it, so don't reach for ctx.query expecting a passed-in arg
ctx.rawBody // the request body exactly as sent, as a string (JSON, form or text/* bodies; null when there is none). Verify webhook signatures over THIS, never JSON.stringify(ctx.body)
ctx.headers // every request header, keys lowercased, except credentials (authorization, cookie, x-app-token, x-api-key, proxy-authorization)
// so custom headers like stripe-signature / x-hub-signature-256 / x-shopify-hmac-sha256 are readable
// x-forwarded-for is the original caller's IP chain - use ctx.headers['x-forwarded-for']?.split(',')[0].trim() to get the user's IP,
// which you pass to the injected location.ip({ ip }) capability from a function (see app-location)
ctx.method // HTTP method (always uppercase, e.g. "POST")
ctx.auth // { userId, userGuid, displayName, role, via, apiKeyName, identity } - populated when auth_level is 'user' or 'member'
// Key per-user data on userGuid (stable external id). userId is an internal numeric id - don't store it. See "Using auth".
Calling functions from the client
Every Gipity template auto-injects the client SDK (gipity.js), which exposes Gipity.fn(name, body?, opts?) for calling functions. Always use Gipity.fn - it unwraps the { data: ... } envelope, throws on non-2xx with the server's error message, and reports failures to gipity logs app. A hand-rolled fetch reading json.field instead of json.data.field is the most common bug agents ship: it silently gets undefined on a 200, and nothing reaches the logs because the request succeeded.
// Inside your entry script - no setup needed; the SDK reads data-app from its script tag.
const data = await Gipity.fn('list-items');
document.getElementById('count').textContent = `${data.items.length} items`;
If a 200 comes back with a shape you didn't expect (missing field, wrong type), report it explicitly so it lands in gipity logs app:
const data = await Gipity.fn('add-post', { x, y, text });
if (!data?.post) {
Gipity.captureError(new Error('add-post returned no post field'));
return;
}
The web-fullstack template is the canonical reference. See app-debugging for everything else the auto-monitor catches and what it doesn't.
Signaling failure / status codes
Two ways a function reports a problem, and they map to different HTTP statuses:
- Validation / business errors →
return { error: 'name is required' }on a 200. The client readsdata.errorafterGipity.fn(the{ data }wrapper still applies). Use this for expected, recoverable conditions ("name is required", "item not found", "already claimed"). - System / unexpected errors →
throw. The runtime catches it and returns a 500{ error: { code, message } }(the envelope from the Return value note above). Use this for bugs and broken invariants - don't swallow them into{ error }on a 200, that hides real failures from the monitor.
There is no first-class API for returning an arbitrary 4xx status (e.g. 403/404/422) from app code - a function returns 200 or throws → 500 (platform failures: 403 permission, 429 governor limit, 504 timeout). Auth gating (401/403) is the platform's job: declare auth: user / auth: member in gipity.yaml and the runtime rejects unauthenticated callers before your handler runs. So: validate-and-return { error } for "the request was understood but can't be fulfilled", throw for "something is broken".
Database
Functions read and write a per-app PostgreSQL database through the injected db helper - db.query plus findOne/findMany/insert/update/delete, db.tx transactions, and db.describe. Schema lives in migrations/; each function's table access is granted with tables: in gipity.yaml (below).
Full reference → the app-database skill: setup and PostgreSQL types, the db helpers and db.tx, per-invocation limits (and the limits: block to raise them), RETURNING / array-param / upsert patterns, views and * globs in tables:, and why schema must live in migrations/ rather than a one-off gipity db query.
What a function can call (fetch, app services, secrets, ...)
Beyond db, a function reaches the outside world through the injected services on its second argument. Each one has its own rules, covered in app-function-services:
fetch- third-party HTTP APIs only, hosts declared infetch_domains, 1MB response cap. To keep a file from a URL usestorage.importUrlinstead (see app-files-storage).- App services -
llm,image,tts,sound,music,video,transcribe,location,notify,email,realtime,embed, each declared inservices: [...]. Billed ones needowner_paysto run from a function. "Email me when ..." isemail({ to: 'owner', subject, text }): it reaches the app owner's account email without the function ever seeing it (see email). secrets- API keys and tokens, never hardcoded.env- read-only config.console- logs ingipity fn logs <name>.crypto- HMAC for webhook signatures overctx.rawBody(app-development-reference).
Using auth
ctx.auth is { userId, userGuid, displayName, role, via, apiKeyName, identity }, populated when the function's auth is user or member. identity is set only for players who signed in to this app without a Gipity account (Steam or guest; see steam-game): { provider: 'steam', id: '<SteamID64>' } or { provider: 'guest', id }, and null otherwise.
Key all per-user data on ctx.auth.userGuid. userGuid (e.g. u_qpx38ujc) is the stable external identity; userId is an internal numeric DB id that isn't stored in app data or returned to clients (same rule as everywhere else on the platform - external code uses guids, not ids). Store it in a user_guid TEXT column and filter every read/write by it. If userGuid is missing the caller isn't signed in - return the auth error:
export default async function myTodos(ctx, { db }) {
const userGuid = ctx.auth?.userGuid;
if (!userGuid) return { error: 'Sign in required.' };
const { rows } = await db.query(
'SELECT * FROM todos WHERE user_guid = $1',
[userGuid]
);
return { todos: rows };
}
Writing Tests
Write a test file per function in tests/api/<name>.test.js and run gipity test; ctx.fn.call(name, params) returns the function's value unwrapped against an isolated, auto-reset test database, and ctx.fn.callAs(ctx.users.alice, ...) tests auth: user functions. Full reference: the app-testing skill.
Calling Functions
Public functions need no authentication:
curl -s -X POST https://a.gipity.ai/api/<PROJECT_GUID>/fn/<name> \
-H 'Content-Type: application/json' -d '{"key": "value"}'
Always use the project GUID in URLs - never the slug. This POST .../api/<PROJECT_GUID>/fn/<name> address IS the public URL to hand an external caller - a webhook, a device, another server. deploy prints the exact reachable URL for each public function (its examples), and gipity fn list prints the endpoint; copy that, don't guess a host.
gipity fn call <name> [body] is the quick CLI way to hit a deployed function - but note it runs authenticated as the logged-in CLI user, so calling a mutating auth: user function writes real rows owned by your account (real production state on prod). To test the logged-out path, call the endpoint without an auth header (plain curl). See app-debugging.
On-demand actions: button to function vs. a Gipity workflow
A button that does one thing calls a function directly; a multi-step, approval or scheduled flow is a workflow. Decision guide: app-development-reference.
Versioning, Management Commands & Rate Limits
Function versioning & rollback, management commands (gipity fn list/logs/delete), and API rate limits: read app-development-reference.
Related Skills
Load these for specific features:
app-development-reference- the long tail of this guide: ES module rules, multi-file functions,_libshared modules, backend-bearing kits, verifying webhook signatures, button vs. workflow, versioning & rollback, management commands, rate limitsapp-database- the per-app Postgres database: migrations, thedbhelper, transactions, table permissionsapp-testing- testing deployed functions:ctx.fn.call/callAs, the isolated test DB, fixturesworkflow- scheduled / manual / webhook / data-change server automation (workflows/*.yaml)realtime-scheduled-app- recipe wiring functions + DB + realtime + a scheduled poster end-to-endweb-app-basics- HTML/CSS/JS patterns and templatesdeploy- the deploy pipeline andgipity.yamlmanifestapp-debugging- inspect deployed pages, screenshots, function logsapp-auth- user authentication (Sign in with Gipity or app users);app-auth-clientfor the sign-in client codeapp-function-services-fetch, app services (llm,email,realtime.publish,embed, ...),secrets,envandconsolefrom a functionapp-files- file uploads;app-files-storagefor thestoragehelper (import from a URL, check the uploader, delete);app-files-displayfor showing filesapp-realtime- rooms, andrealtime.publish()from a function- Per-service params:
app-llm,app-image,app-video,app-audio,app-tts,app-location,app-notify,email,app-vector-search,app-approvals