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:

  1. Write the function in functions/{name}.js
  2. Add it to gipity.yaml under functions inside the type: functions phase, never at the root (deploy rejects that):
    deploy:
      phases:
        - name: functions
          type: functions
          source: functions
          functions:
            - name: my-todos
              auth: user
              tables: [todos]
    
  3. Write tests in tests/api/{name}.test.js
  4. Deploy: gipity deploy
  5. 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:

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

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:

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:

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:

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: