Skip to the page

Guides · Frameworks

A backend service

Call Napalm from a Python or Go backend on behalf of a signed-in user or with a service key, read your own writes and handle signed action calls.

In the schema
—

What you’ll build#

You will build a compact HTTP service beside a Napalm project that exports a person’s notes as CSV, imports notes from CSV, processes signed change webhooks and serves an external action handler. Together, those four routes cover every server integration posture: forwarding a caller’s bearer token, chaining read-your-writes bookmarks across replicas, reading with a scoped service key and trading an action’s ES256 assertion for a 60-second caller session.

Switch between Python (FastAPI, httpx and PyJWT) and Go (net/http) in the Language picker above. Because PostgreSQL enforces your schema’s access policies on every query, the backend service never re-implements authorization checks in route code.

Before you start#

Start from Your first app, which defines myNotes and addNote. Add a notify declaration and emailed_at timestamp on Note, deploy a service read query and an action gatekeeper query, and register your service host.

dbschema/default.gel
module default {  # Set to 'service' in endpoint serviceGlobals for service keys; user sessions cannot set this global.  global role: str;   type Note {    # … existing Note properties, plus:    emailed_at: datetime;    notify note_changed after insert, update, delete;     access policy service_can_read      allow select      using (global role ?= 'service');  }}
dbschema/queries/allNotes.edgeql
# Deployed as allNotes.edgeql for the read-only service key.select Note { id, title, body }
dbschema/queries/emailNote.edgeql
# Deployed as emailNote.edgeql and attached to the external action handler.select Note { id, title, body, recipient := <str>$email }filter .id = <uuid>$note
Terminal
# Set the project's HTTPS address for the backend serviceexport NAPALM_URL=https://<project-address> # Issue a read-only service key for background webhook work. Store the secret once.napalm keys create notes --label notes-api --read-only # Allow outbound requests to your service host, then register the webhook and action.napalm webhooks hosts notes --add api.example.comnapalm webhooks add notes https://api.example.com/hooks/napalm --event note_changednapalm actions add notes emailNote https://api.example.com/actions/email-note

Configure { "default::role": "service" } in serviceGlobals on the project’s endpoint so access policies distinguish service keys from user sessions. Billing & payments walks through serviceGlobals.

Call a deployed query#

Every deployed query executes via POST /query/{name} with JSON variables, an Authorization: Bearer header identifying the caller and an optional Napalm-Bookmark header. One shared helper handles every call across all four routes.

service.py
# service.pyimport csvimport hashlibimport hmacimport ioimport jsonimport os import httpximport jwtfrom fastapi import FastAPI, Header, HTTPException, Request, Response napalm = httpx.AsyncClient(base_url=os.environ["NAPALM_URL"], timeout=30)jwks_client = jwt.PyJWKClient(f"{os.environ['NAPALM_URL']}/.well-known/jwks.json")app = FastAPI()  async def call(    name: str, variables: dict, bearer: str, bookmark: str = "") -> tuple[list, str]:    """Runs a deployed query as the given bearer and returns rows plus Napalm-Bookmark."""    answer = await napalm.post(        f"/query/{name}",        json={"variables": variables},        headers={"Authorization": f"Bearer {bearer}", "Napalm-Bookmark": bookmark},    )    if answer.is_error:        # Forward the project's status code and structured error body unchanged.        raise HTTPException(answer.status_code, answer.json().get("error"))    return answer.json()["data"], answer.headers.get("Napalm-Bookmark", bookmark)  def bearer_of(authorization: str) -> str:    """Extracts the caller's bearer token so the service forwards rather than stores sessions."""    scheme, _, token = authorization.partition(" ")    if scheme.lower() != "bearer" or not token:        raise HTTPException(401)    return token

Running napalm generate for Python or Go replaces this helper with generated request and response types per query while keeping bearer forwarding and Napalm-Bookmark propagation identical.

Act as the requesting person#

Your client app calls the backend service with the same bearer token it sends to Napalm. Forwarding that token directly to POST /query/myNotes runs the statement under that person’s Identity and returns only permitted rows without manual JWT parsing or WHERE filters.

service.py
@app.get("/export")async def export(authorization: str = Header()):    # Runs as the requesting person; the schema policy filters rows automatically.    notes, _ = await call("myNotes", {}, bearer_of(authorization))    out = io.StringIO()    csv.writer(out).writerows([note["title"], note["body"]] for note in notes)    return Response(out.getvalue(), media_type="text/csv")
Accepted tokens
Browser SPAs and mobile apps send the session token directly. Server-rendered web apps pass a five-minute token from signIn.pageToken(). Both tokens work interchangeably as bearers.
Caller identity
When your service needs the caller’s UUID or email, run a deployed select global caller { id } query with that bearer rather than decoding session tokens locally.
Never substitute a service key
Never answer an end-user request using NAPALM_KEY and a hand-written filter. A single missed parameter would bypass per-user isolation.

Read your own writes#

Read replicas serve SELECT queries and can trail the primary by a few milliseconds. Every Napalm response returns a Napalm-Bookmark header naming the commit position reached. Passing that bookmark on the next request holds the read until the chosen read replica catches up.

Atomic CSV batch writes & causal bookmarks

Bulk CSV imports commit deployed write queries on the primary and thread the returned Napalm-Bookmark header into follow-up replica reads so callers immediately see their own writes.

service.py
@app.post("/import")async def import_notes(request: Request, authorization: str = Header()):    bearer = bearer_of(authorization)    bookmark = ""    for title, body in csv.reader(io.StringIO((await request.body()).decode())):        # Carry each mutation's Napalm-Bookmark into the next step.        added = {"title": title, "body": body}        _, bookmark = await call("addNote", added, bearer, bookmark)    # Forwarding the final bookmark guarantees replica reads include every imported row.    notes, _ = await call("myNotes", {}, bearer, bookmark)    return {"count": len(notes)}

Scope bookmarks to a single request sequence rather than a process-wide global variable. When a browser or phone chains requests across your service and the Project API, echo Napalm-Bookmark on your HTTP response so the client keeps advancing from the server’s write position.

Act as the service itself#

Background tasks and webhook receivers run without a signed-in user, authenticating instead with a scoped service key. Each webhook delivery carries Napalm-Signature over the raw body bytes and Napalm-Position so your follow-up read sees the triggering commit immediately.

Scoped branch service keys

Branch-scoped ndb_… service keys execute with empty global caller and endpoint serviceGlobals, seeing zero rows on closed types until a policy grants global role ?= 'service'. Audit reach with napalm keys reach.

service.py
@app.post("/hooks/napalm")async def changed(    request: Request,    napalm_signature: str = Header(),    napalm_position: str = Header(""),):    # Verify the HMAC-SHA256 signature against the raw request bytes before parsing JSON.    body = await request.body()    secret = os.environ["NAPALM_WEBHOOK_SECRET"].encode()    expected = hmac.new(secret, body, hashlib.sha256).hexdigest()    if not hmac.compare_digest(napalm_signature.removeprefix("sha256="), expected):        raise HTTPException(401)    # Console test pings carry an empty position header.    if napalm_position:        notes, _ = await call("allNotes", {}, os.environ["NAPALM_KEY"], napalm_position)        await index(notes)    return Response(status_code=204)  async def index(notes: list) -> None:    """Forwards committed rows to an external search index, warehouse or Slack channel."""
Least privilege
Service keys see zero rows on closed types unless an access policy explicitly grants global role ?= "service". Audit a key’s exact table reach before deployment with napalm keys reach.
Acknowledge quickly
Napalm retries non-2xx webhook deliveries with exponential backoff. Production receivers verify the HMAC, enqueue background work keyed by Napalm-Delivery and return 204 immediately.
Incremental sync
Reading allNotes fits small catalogs. For large tables, stream exact committed deltas from GET /changes using the delivery position as shown in Warehouse sync.

Handle action calls as the caller#

When a browser, mobile app or MCP agent invokes POST /query/emailNote, Napalm runs the gatekeeper query under the caller’s access policies first. If the caller cannot read that note, Napalm returns 403 nothing_found and never contacts your server. When rows match, Napalm POSTs those rows to your handler with a 60-second ES256 JWT assertion instead of exposing the caller’s raw session token.

service.py
@app.post("/actions/email-note")async def email_note(request: Request, authorization: str = Header()):    assertion = bearer_of(authorization)    raw_body = await request.body()     # Verify the 60-second ES256 assertion against the project's JWKS and raw body digest.    signing_key = jwks_client.get_signing_key_from_jwt(assertion)    claims = jwt.decode(        assertion,        signing_key.key,        algorithms=["ES256"],        issuer=os.environ["NAPALM_URL"],        audience="https://api.example.com/actions/email-note",    )    body_sha256 = hashlib.sha256(raw_body).hexdigest()    if not hmac.compare_digest(claims["napalm_body_sha256"], body_sha256):        raise HTTPException(401)     payload = json.loads(raw_body)    note = payload["data"][0]     # Trade the assertion at RFC 8693 token exchange for a 60-second caller session.    exchanged = await napalm.post(        "/sign-in/agents/token",        headers={"Authorization": f"Bearer {os.environ['NAPALM_ACTION_SECRET']}"},        data={            "grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",            "subject_token_type": "urn:ietf:params:oauth:token-type:jwt",            "subject_token": assertion,        },    )    if exchanged.is_error:        raise HTTPException(exchanged.status_code, exchanged.json().get("error"))    caller_token = exchanged.json()["access_token"]     await send_mail(note["recipient"], note["title"], note["body"])    await call("markNoteEmailed", {"note": note["id"]}, caller_token)    return {"sent": True}  async def send_mail(recipient: str, title: str, body: str) -> None:    """Delivers the email through your mail provider."""
Assertion verification
Verify the ES256 signature against <NAPALM_URL>/.well-known/jwks.json, check iss (NAPALM_URL) and aud (your exact handler URL), and compare napalm_body_sha256 in constant time against the raw request bytes.
RFC 8693 token exchange
Exchange assertion plus NAPALM_ACTION_SECRET at POST /sign-in/agents/token to obtain a 60-second bearer token scoped to the original person, agent grant or scheduled service key.
SDK shortcut
In TypeScript, handleCalls from napalm-client performs JWKS caching, body hashing and token exchange automatically. In Go, napalm.Serve from napalmdata.com/go/napalm provides the same wrapper.

Handle refusals#

Project API errors return an HTTP status and { "error": { "code", "message" } }. Forwarding the status code lets browser and mobile clients handle refusals consistently across direct and proxied routes.

Status and codeCauseService or client action
401 invalid_sessionThe user session expired or signed out.Service or client actionPrompt the person to sign in again.
401 invalid_keyThe service key is unknown, expired or revoked.Service or client actionRenew NAPALM_KEY using napalm keys create without exposing internal details to end users.
401 invalid_clientToken exchange at /sign-in/agents/token carried an outdated NAPALM_ACTION_SECRET.Service or client actionUpdate the action secret environment variable and redeploy.
403 nothing_foundAn action’s gatekeeper query matched zero rows for the caller.Service or client actionReturn 403 or 404 to the caller. The handler was never invoked.
404 not_foundThe query name is not deployed on this branch, or the Project API is disabled.Service or client actionDeploy the query catalog with napalm queries push.
400 query_failedAn access policy or schema constraint refused the mutation.Service or client actionSurface error.message to the caller.
503 project_unavailableThe cluster was briefly unreachable during failover or wake.Service or client actionRetry idempotent reads or mutations with short jittered backoff.

Ordinary SELECT queries that match zero permitted rows return 200 OK with data: [] rather than an error. Troubleshooting & auditing contrasts filtered reads with refused writes and actions.

Check the service#

  1. Export CSV as two different people

    Call GET /export with each user’s bearer token. Each response contains only that user’s notes without a single user-ID filter in service.py.

  2. Import three CSV rows and verify replica consistency

    Send a three-row CSV to POST /import. The returned count immediately reflects all three additions across read replicas because Napalm-Bookmark threaded through each call.

  3. Trigger and tamper-test the webhook

    Insert a note and verify POST /hooks/napalm logs the delivery within a second. Replay the request with an altered body byte and confirm the route rejects the payload with 401.

  4. Invoke the emailNote action as owner and non-owner

    Call POST /query/emailNote on the Project API as the note’s owner and confirm emailed_at updates via the exchanged caller token. Call the same endpoint as another user and confirm Napalm refuses with 403 nothing_found before reaching /actions/email-note.

Next steps#

Hosted handlers
Move standalone endpoints onto per-branch machines that sleep when idle and verify calls automatically.
Key and secret renewal
Renew service keys, webhook secrets and action secrets without dropping in-flight traffic.
Warehouse sync
Stream ordered change-log pages into ClickHouse, Snowflake, BigQuery or DuckDB.

Type a word or two to search every docs page.